babylon.viewer.max.js 6.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145
  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 = 15);
  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__(18); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(19); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(20); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = function (right) {
  1980. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1981. };
  1982. /**
  1983. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. 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)];
  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._observers.splice(index, 1);
  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._observers.splice(index, 1);
  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. /**
  8330. * Notify all Observers by calling their respective callback with the given data
  8331. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8332. * @param eventData defines the data to send to all observers
  8333. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8334. * @param target defines the original target of the state
  8335. * @param currentTarget defines the current target of the state
  8336. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8337. */
  8338. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8339. if (mask === void 0) { mask = -1; }
  8340. if (!this._observers.length) {
  8341. return true;
  8342. }
  8343. var state = this._eventState;
  8344. state.mask = mask;
  8345. state.target = target;
  8346. state.currentTarget = currentTarget;
  8347. state.skipNextObservers = false;
  8348. state.lastReturnValue = eventData;
  8349. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8350. var obs = _a[_i];
  8351. if (obs._willBeUnregistered) {
  8352. continue;
  8353. }
  8354. if (obs.mask & mask) {
  8355. if (obs.scope) {
  8356. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8357. }
  8358. else {
  8359. state.lastReturnValue = obs.callback(eventData, state);
  8360. }
  8361. if (obs.unregisterOnNextCall) {
  8362. this._deferUnregister(obs);
  8363. }
  8364. }
  8365. if (state.skipNextObservers) {
  8366. return false;
  8367. }
  8368. }
  8369. return true;
  8370. };
  8371. /**
  8372. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8373. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8374. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8375. * and it is crucial that all callbacks will be executed.
  8376. * The order of the callbacks is kept, callbacks are not executed parallel.
  8377. *
  8378. * @param eventData The data to be sent to each callback
  8379. * @param mask is used to filter observers defaults to -1
  8380. * @param target defines the callback target (see EventState)
  8381. * @param currentTarget defines he current object in the bubbling phase
  8382. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8383. */
  8384. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8385. var _this = this;
  8386. if (mask === void 0) { mask = -1; }
  8387. // create an empty promise
  8388. var p = Promise.resolve(eventData);
  8389. // no observers? return this promise.
  8390. if (!this._observers.length) {
  8391. return p;
  8392. }
  8393. var state = this._eventState;
  8394. state.mask = mask;
  8395. state.target = target;
  8396. state.currentTarget = currentTarget;
  8397. state.skipNextObservers = false;
  8398. // execute one callback after another (not using Promise.all, the order is important)
  8399. this._observers.forEach(function (obs) {
  8400. if (state.skipNextObservers) {
  8401. return;
  8402. }
  8403. if (obs._willBeUnregistered) {
  8404. return;
  8405. }
  8406. if (obs.mask & mask) {
  8407. if (obs.scope) {
  8408. p = p.then(function (lastReturnedValue) {
  8409. state.lastReturnValue = lastReturnedValue;
  8410. return obs.callback.apply(obs.scope, [eventData, state]);
  8411. });
  8412. }
  8413. else {
  8414. p = p.then(function (lastReturnedValue) {
  8415. state.lastReturnValue = lastReturnedValue;
  8416. return obs.callback(eventData, state);
  8417. });
  8418. }
  8419. if (obs.unregisterOnNextCall) {
  8420. _this._deferUnregister(obs);
  8421. }
  8422. }
  8423. });
  8424. // return the eventData
  8425. return p.then(function () { return eventData; });
  8426. };
  8427. /**
  8428. * Notify a specific observer
  8429. * @param observer defines the observer to notify
  8430. * @param eventData defines the data to be sent to each callback
  8431. * @param mask is used to filter observers defaults to -1
  8432. */
  8433. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8434. if (mask === void 0) { mask = -1; }
  8435. var state = this._eventState;
  8436. state.mask = mask;
  8437. state.skipNextObservers = false;
  8438. observer.callback(eventData, state);
  8439. };
  8440. /**
  8441. * Gets a boolean indicating if the observable has at least one observer
  8442. * @returns true is the Observable has at least one Observer registered
  8443. */
  8444. Observable.prototype.hasObservers = function () {
  8445. return this._observers.length > 0;
  8446. };
  8447. /**
  8448. * Clear the list of observers
  8449. */
  8450. Observable.prototype.clear = function () {
  8451. this._observers = new Array();
  8452. this._onObserverAdded = null;
  8453. };
  8454. /**
  8455. * Clone the current observable
  8456. * @returns a new observable
  8457. */
  8458. Observable.prototype.clone = function () {
  8459. var result = new Observable();
  8460. result._observers = this._observers.slice(0);
  8461. return result;
  8462. };
  8463. /**
  8464. * Does this observable handles observer registered with a given mask
  8465. * @param mask defines the mask to be tested
  8466. * @return whether or not one observer registered with the given mask is handeled
  8467. **/
  8468. Observable.prototype.hasSpecificMask = function (mask) {
  8469. if (mask === void 0) { mask = -1; }
  8470. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8471. var obs = _a[_i];
  8472. if (obs.mask & mask || obs.mask === mask) {
  8473. return true;
  8474. }
  8475. }
  8476. return false;
  8477. };
  8478. return Observable;
  8479. }());
  8480. BABYLON.Observable = Observable;
  8481. })(BABYLON || (BABYLON = {}));
  8482. //# sourceMappingURL=babylon.observable.js.map
  8483. var BABYLON;
  8484. (function (BABYLON) {
  8485. var SmartArray = /** @class */ (function () {
  8486. function SmartArray(capacity) {
  8487. this.length = 0;
  8488. this.data = new Array(capacity);
  8489. this._id = SmartArray._GlobalId++;
  8490. }
  8491. SmartArray.prototype.push = function (value) {
  8492. this.data[this.length++] = value;
  8493. if (this.length > this.data.length) {
  8494. this.data.length *= 2;
  8495. }
  8496. };
  8497. SmartArray.prototype.forEach = function (func) {
  8498. for (var index = 0; index < this.length; index++) {
  8499. func(this.data[index]);
  8500. }
  8501. };
  8502. SmartArray.prototype.sort = function (compareFn) {
  8503. this.data.sort(compareFn);
  8504. };
  8505. SmartArray.prototype.reset = function () {
  8506. this.length = 0;
  8507. };
  8508. SmartArray.prototype.dispose = function () {
  8509. this.reset();
  8510. if (this.data) {
  8511. this.data.length = 0;
  8512. this.data = [];
  8513. }
  8514. };
  8515. SmartArray.prototype.concat = function (array) {
  8516. if (array.length === 0) {
  8517. return;
  8518. }
  8519. if (this.length + array.length > this.data.length) {
  8520. this.data.length = (this.length + array.length) * 2;
  8521. }
  8522. for (var index = 0; index < array.length; index++) {
  8523. this.data[this.length++] = (array.data || array)[index];
  8524. }
  8525. };
  8526. SmartArray.prototype.indexOf = function (value) {
  8527. var position = this.data.indexOf(value);
  8528. if (position >= this.length) {
  8529. return -1;
  8530. }
  8531. return position;
  8532. };
  8533. SmartArray.prototype.contains = function (value) {
  8534. return this.data.indexOf(value) !== -1;
  8535. };
  8536. // Statics
  8537. SmartArray._GlobalId = 0;
  8538. return SmartArray;
  8539. }());
  8540. BABYLON.SmartArray = SmartArray;
  8541. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8542. __extends(SmartArrayNoDuplicate, _super);
  8543. function SmartArrayNoDuplicate() {
  8544. var _this = _super !== null && _super.apply(this, arguments) || this;
  8545. _this._duplicateId = 0;
  8546. return _this;
  8547. }
  8548. SmartArrayNoDuplicate.prototype.push = function (value) {
  8549. _super.prototype.push.call(this, value);
  8550. if (!value.__smartArrayFlags) {
  8551. value.__smartArrayFlags = {};
  8552. }
  8553. value.__smartArrayFlags[this._id] = this._duplicateId;
  8554. };
  8555. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8556. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8557. return false;
  8558. }
  8559. this.push(value);
  8560. return true;
  8561. };
  8562. SmartArrayNoDuplicate.prototype.reset = function () {
  8563. _super.prototype.reset.call(this);
  8564. this._duplicateId++;
  8565. };
  8566. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8567. if (array.length === 0) {
  8568. return;
  8569. }
  8570. if (this.length + array.length > this.data.length) {
  8571. this.data.length = (this.length + array.length) * 2;
  8572. }
  8573. for (var index = 0; index < array.length; index++) {
  8574. var item = (array.data || array)[index];
  8575. this.pushNoDuplicate(item);
  8576. }
  8577. };
  8578. return SmartArrayNoDuplicate;
  8579. }(SmartArray));
  8580. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8581. })(BABYLON || (BABYLON = {}));
  8582. //# sourceMappingURL=babylon.smartArray.js.map
  8583. var BABYLON;
  8584. (function (BABYLON) {
  8585. /** Class used to store color gradient */
  8586. var ColorGradient = /** @class */ (function () {
  8587. function ColorGradient() {
  8588. }
  8589. return ColorGradient;
  8590. }());
  8591. BABYLON.ColorGradient = ColorGradient;
  8592. /** Class used to store factor gradient */
  8593. var FactorGradient = /** @class */ (function () {
  8594. function FactorGradient() {
  8595. }
  8596. return FactorGradient;
  8597. }());
  8598. BABYLON.FactorGradient = FactorGradient;
  8599. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8600. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8601. var LoadFileError = /** @class */ (function (_super) {
  8602. __extends(LoadFileError, _super);
  8603. function LoadFileError(message, request) {
  8604. var _this = _super.call(this, message) || this;
  8605. _this.request = request;
  8606. _this.name = "LoadFileError";
  8607. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8608. return _this;
  8609. }
  8610. // Polyfill for Object.setPrototypeOf if necessary.
  8611. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8612. return LoadFileError;
  8613. }(Error));
  8614. BABYLON.LoadFileError = LoadFileError;
  8615. var RetryStrategy = /** @class */ (function () {
  8616. function RetryStrategy() {
  8617. }
  8618. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8619. if (maxRetries === void 0) { maxRetries = 3; }
  8620. if (baseInterval === void 0) { baseInterval = 500; }
  8621. return function (url, request, retryIndex) {
  8622. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8623. return -1;
  8624. }
  8625. return Math.pow(2, retryIndex) * baseInterval;
  8626. };
  8627. };
  8628. return RetryStrategy;
  8629. }());
  8630. BABYLON.RetryStrategy = RetryStrategy;
  8631. // Screenshots
  8632. var screenshotCanvas;
  8633. var cloneValue = function (source, destinationObject) {
  8634. if (!source)
  8635. return null;
  8636. if (source instanceof BABYLON.Mesh) {
  8637. return null;
  8638. }
  8639. if (source instanceof BABYLON.SubMesh) {
  8640. return source.clone(destinationObject);
  8641. }
  8642. else if (source.clone) {
  8643. return source.clone();
  8644. }
  8645. return null;
  8646. };
  8647. var Tools = /** @class */ (function () {
  8648. function Tools() {
  8649. }
  8650. /**
  8651. * Interpolates between a and b via alpha
  8652. * @param a The lower value (returned when alpha = 0)
  8653. * @param b The upper value (returned when alpha = 1)
  8654. * @param alpha The interpolation-factor
  8655. * @return The mixed value
  8656. */
  8657. Tools.Mix = function (a, b, alpha) {
  8658. return a * (1 - alpha) + b * alpha;
  8659. };
  8660. Tools.Instantiate = function (className) {
  8661. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8662. return Tools.RegisteredExternalClasses[className];
  8663. }
  8664. var arr = className.split(".");
  8665. var fn = (window || this);
  8666. for (var i = 0, len = arr.length; i < len; i++) {
  8667. fn = fn[arr[i]];
  8668. }
  8669. if (typeof fn !== "function") {
  8670. return null;
  8671. }
  8672. return fn;
  8673. };
  8674. /**
  8675. * Provides a slice function that will work even on IE
  8676. * @param data defines the array to slice
  8677. * @param start defines the start of the data (optional)
  8678. * @param end defines the end of the data (optional)
  8679. * @returns the new sliced array
  8680. */
  8681. Tools.Slice = function (data, start, end) {
  8682. if (data.slice) {
  8683. return data.slice(start, end);
  8684. }
  8685. return Array.prototype.slice.call(data, start, end);
  8686. };
  8687. Tools.SetImmediate = function (action) {
  8688. if (window.setImmediate) {
  8689. window.setImmediate(action);
  8690. }
  8691. else {
  8692. setTimeout(action, 1);
  8693. }
  8694. };
  8695. Tools.IsExponentOfTwo = function (value) {
  8696. var count = 1;
  8697. do {
  8698. count *= 2;
  8699. } while (count < value);
  8700. return count === value;
  8701. };
  8702. /**
  8703. * Returns the nearest 32-bit single precision float representation of a Number
  8704. * @param value A Number. If the parameter is of a different type, it will get converted
  8705. * to a number or to NaN if it cannot be converted
  8706. * @returns number
  8707. */
  8708. Tools.FloatRound = function (value) {
  8709. if (Math.fround) {
  8710. return Math.fround(value);
  8711. }
  8712. return (Tools._tmpFloatArray[0] = value);
  8713. };
  8714. /**
  8715. * Find the next highest power of two.
  8716. * @param x Number to start search from.
  8717. * @return Next highest power of two.
  8718. */
  8719. Tools.CeilingPOT = function (x) {
  8720. x--;
  8721. x |= x >> 1;
  8722. x |= x >> 2;
  8723. x |= x >> 4;
  8724. x |= x >> 8;
  8725. x |= x >> 16;
  8726. x++;
  8727. return x;
  8728. };
  8729. /**
  8730. * Find the next lowest power of two.
  8731. * @param x Number to start search from.
  8732. * @return Next lowest power of two.
  8733. */
  8734. Tools.FloorPOT = function (x) {
  8735. x = x | (x >> 1);
  8736. x = x | (x >> 2);
  8737. x = x | (x >> 4);
  8738. x = x | (x >> 8);
  8739. x = x | (x >> 16);
  8740. return x - (x >> 1);
  8741. };
  8742. /**
  8743. * Find the nearest power of two.
  8744. * @param x Number to start search from.
  8745. * @return Next nearest power of two.
  8746. */
  8747. Tools.NearestPOT = function (x) {
  8748. var c = Tools.CeilingPOT(x);
  8749. var f = Tools.FloorPOT(x);
  8750. return (c - x) > (x - f) ? f : c;
  8751. };
  8752. Tools.GetExponentOfTwo = function (value, max, mode) {
  8753. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8754. var pot;
  8755. switch (mode) {
  8756. case BABYLON.Engine.SCALEMODE_FLOOR:
  8757. pot = Tools.FloorPOT(value);
  8758. break;
  8759. case BABYLON.Engine.SCALEMODE_NEAREST:
  8760. pot = Tools.NearestPOT(value);
  8761. break;
  8762. case BABYLON.Engine.SCALEMODE_CEILING:
  8763. default:
  8764. pot = Tools.CeilingPOT(value);
  8765. break;
  8766. }
  8767. return Math.min(pot, max);
  8768. };
  8769. Tools.GetFilename = function (path) {
  8770. var index = path.lastIndexOf("/");
  8771. if (index < 0)
  8772. return path;
  8773. return path.substring(index + 1);
  8774. };
  8775. /**
  8776. * Extracts the "folder" part of a path (everything before the filename).
  8777. * @param uri The URI to extract the info from
  8778. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8779. * @returns The "folder" part of the path
  8780. */
  8781. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8782. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8783. var index = uri.lastIndexOf("/");
  8784. if (index < 0) {
  8785. if (returnUnchangedIfNoSlash) {
  8786. return uri;
  8787. }
  8788. return "";
  8789. }
  8790. return uri.substring(0, index + 1);
  8791. };
  8792. Tools.GetDOMTextContent = function (element) {
  8793. var result = "";
  8794. var child = element.firstChild;
  8795. while (child) {
  8796. if (child.nodeType === 3) {
  8797. result += child.textContent;
  8798. }
  8799. child = child.nextSibling;
  8800. }
  8801. return result;
  8802. };
  8803. Tools.ToDegrees = function (angle) {
  8804. return angle * 180 / Math.PI;
  8805. };
  8806. Tools.ToRadians = function (angle) {
  8807. return angle * Math.PI / 180;
  8808. };
  8809. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8810. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8811. var output = "";
  8812. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8813. var i = 0;
  8814. var bytes = new Uint8Array(buffer);
  8815. while (i < bytes.length) {
  8816. chr1 = bytes[i++];
  8817. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8818. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8819. enc1 = chr1 >> 2;
  8820. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8821. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8822. enc4 = chr3 & 63;
  8823. if (isNaN(chr2)) {
  8824. enc3 = enc4 = 64;
  8825. }
  8826. else if (isNaN(chr3)) {
  8827. enc4 = 64;
  8828. }
  8829. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8830. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8831. }
  8832. return "data:image/png;base64," + output;
  8833. };
  8834. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8835. if (bias === void 0) { bias = null; }
  8836. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8837. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8838. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8839. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8840. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8841. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8842. }
  8843. if (bias) {
  8844. minimum.x -= minimum.x * bias.x + bias.y;
  8845. minimum.y -= minimum.y * bias.x + bias.y;
  8846. minimum.z -= minimum.z * bias.x + bias.y;
  8847. maximum.x += maximum.x * bias.x + bias.y;
  8848. maximum.y += maximum.y * bias.x + bias.y;
  8849. maximum.z += maximum.z * bias.x + bias.y;
  8850. }
  8851. return {
  8852. minimum: minimum,
  8853. maximum: maximum
  8854. };
  8855. };
  8856. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8857. if (bias === void 0) { bias = null; }
  8858. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8859. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8860. if (!stride) {
  8861. stride = 3;
  8862. }
  8863. for (var index = start; index < start + count; index++) {
  8864. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8865. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8866. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8867. }
  8868. if (bias) {
  8869. minimum.x -= minimum.x * bias.x + bias.y;
  8870. minimum.y -= minimum.y * bias.x + bias.y;
  8871. minimum.z -= minimum.z * bias.x + bias.y;
  8872. maximum.x += maximum.x * bias.x + bias.y;
  8873. maximum.y += maximum.y * bias.x + bias.y;
  8874. maximum.z += maximum.z * bias.x + bias.y;
  8875. }
  8876. return {
  8877. minimum: minimum,
  8878. maximum: maximum
  8879. };
  8880. };
  8881. Tools.Vector2ArrayFeeder = function (array) {
  8882. return function (index) {
  8883. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8884. var length = isFloatArray ? array.length / 2 : array.length;
  8885. if (index >= length) {
  8886. return null;
  8887. }
  8888. if (isFloatArray) {
  8889. var fa = array;
  8890. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8891. }
  8892. var a = array;
  8893. return a[index];
  8894. };
  8895. };
  8896. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8897. if (bias === void 0) { bias = null; }
  8898. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8899. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8900. var i = 0;
  8901. var cur = feeder(i++);
  8902. while (cur) {
  8903. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8904. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8905. cur = feeder(i++);
  8906. }
  8907. if (bias) {
  8908. minimum.x -= minimum.x * bias.x + bias.y;
  8909. minimum.y -= minimum.y * bias.x + bias.y;
  8910. maximum.x += maximum.x * bias.x + bias.y;
  8911. maximum.y += maximum.y * bias.x + bias.y;
  8912. }
  8913. return {
  8914. minimum: minimum,
  8915. maximum: maximum
  8916. };
  8917. };
  8918. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8919. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8920. return null;
  8921. return Array.isArray(obj) ? obj : [obj];
  8922. };
  8923. // Misc.
  8924. Tools.GetPointerPrefix = function () {
  8925. var eventPrefix = "pointer";
  8926. // Check if pointer events are supported
  8927. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8928. eventPrefix = "mouse";
  8929. }
  8930. return eventPrefix;
  8931. };
  8932. /**
  8933. * @param func - the function to be called
  8934. * @param requester - the object that will request the next frame. Falls back to window.
  8935. */
  8936. Tools.QueueNewFrame = function (func, requester) {
  8937. if (!Tools.IsWindowObjectExist()) {
  8938. return setTimeout(func, 16);
  8939. }
  8940. if (!requester) {
  8941. requester = window;
  8942. }
  8943. if (requester.requestAnimationFrame) {
  8944. return requester.requestAnimationFrame(func);
  8945. }
  8946. else if (requester.msRequestAnimationFrame) {
  8947. return requester.msRequestAnimationFrame(func);
  8948. }
  8949. else if (requester.webkitRequestAnimationFrame) {
  8950. return requester.webkitRequestAnimationFrame(func);
  8951. }
  8952. else if (requester.mozRequestAnimationFrame) {
  8953. return requester.mozRequestAnimationFrame(func);
  8954. }
  8955. else if (requester.oRequestAnimationFrame) {
  8956. return requester.oRequestAnimationFrame(func);
  8957. }
  8958. else {
  8959. return window.setTimeout(func, 16);
  8960. }
  8961. };
  8962. Tools.RequestFullscreen = function (element) {
  8963. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8964. if (!requestFunction)
  8965. return;
  8966. requestFunction.call(element);
  8967. };
  8968. Tools.ExitFullscreen = function () {
  8969. if (document.exitFullscreen) {
  8970. document.exitFullscreen();
  8971. }
  8972. else if (document.mozCancelFullScreen) {
  8973. document.mozCancelFullScreen();
  8974. }
  8975. else if (document.webkitCancelFullScreen) {
  8976. document.webkitCancelFullScreen();
  8977. }
  8978. else if (document.msCancelFullScreen) {
  8979. document.msCancelFullScreen();
  8980. }
  8981. };
  8982. Tools.SetCorsBehavior = function (url, element) {
  8983. if (url && url.indexOf("data:") === 0) {
  8984. return;
  8985. }
  8986. if (Tools.CorsBehavior) {
  8987. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8988. element.crossOrigin = Tools.CorsBehavior;
  8989. }
  8990. else {
  8991. var result = Tools.CorsBehavior(url);
  8992. if (result) {
  8993. element.crossOrigin = result;
  8994. }
  8995. }
  8996. }
  8997. };
  8998. // External files
  8999. Tools.CleanUrl = function (url) {
  9000. url = url.replace(/#/mg, "%23");
  9001. return url;
  9002. };
  9003. /**
  9004. * Loads an image as an HTMLImageElement.
  9005. * @param input url string, ArrayBuffer, or Blob to load
  9006. * @param onLoad callback called when the image successfully loads
  9007. * @param onError callback called when the image fails to load
  9008. * @param database database for caching
  9009. * @returns the HTMLImageElement of the loaded image
  9010. */
  9011. Tools.LoadImage = function (input, onLoad, onError, database) {
  9012. var url;
  9013. var usingObjectURL = false;
  9014. if (input instanceof ArrayBuffer) {
  9015. url = URL.createObjectURL(new Blob([input]));
  9016. usingObjectURL = true;
  9017. }
  9018. else if (input instanceof Blob) {
  9019. url = URL.createObjectURL(input);
  9020. usingObjectURL = true;
  9021. }
  9022. else {
  9023. url = Tools.CleanUrl(input);
  9024. url = Tools.PreprocessUrl(input);
  9025. }
  9026. var img = new Image();
  9027. Tools.SetCorsBehavior(url, img);
  9028. var loadHandler = function () {
  9029. if (usingObjectURL && img.src) {
  9030. URL.revokeObjectURL(img.src);
  9031. }
  9032. img.removeEventListener("load", loadHandler);
  9033. img.removeEventListener("error", errorHandler);
  9034. onLoad(img);
  9035. };
  9036. var errorHandler = function (err) {
  9037. if (usingObjectURL && img.src) {
  9038. URL.revokeObjectURL(img.src);
  9039. }
  9040. img.removeEventListener("load", loadHandler);
  9041. img.removeEventListener("error", errorHandler);
  9042. Tools.Error("Error while trying to load image: " + input);
  9043. if (onError) {
  9044. onError("Error while trying to load image: " + input, err);
  9045. }
  9046. };
  9047. img.addEventListener("load", loadHandler);
  9048. img.addEventListener("error", errorHandler);
  9049. var noIndexedDB = function () {
  9050. img.src = url;
  9051. };
  9052. var loadFromIndexedDB = function () {
  9053. if (database) {
  9054. database.loadImageFromDB(url, img);
  9055. }
  9056. };
  9057. //ANY database to do!
  9058. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9059. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9060. }
  9061. else {
  9062. if (url.indexOf("file:") !== -1) {
  9063. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9064. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9065. try {
  9066. var blobURL;
  9067. try {
  9068. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9069. }
  9070. catch (ex) {
  9071. // Chrome doesn't support oneTimeOnly parameter
  9072. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9073. }
  9074. img.src = blobURL;
  9075. usingObjectURL = true;
  9076. }
  9077. catch (e) {
  9078. img.src = "";
  9079. }
  9080. return img;
  9081. }
  9082. }
  9083. noIndexedDB();
  9084. }
  9085. return img;
  9086. };
  9087. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9088. url = Tools.CleanUrl(url);
  9089. url = Tools.PreprocessUrl(url);
  9090. // If file and file input are set
  9091. if (url.indexOf("file:") !== -1) {
  9092. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9093. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9094. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9095. }
  9096. }
  9097. var loadUrl = Tools.BaseUrl + url;
  9098. var aborted = false;
  9099. var fileRequest = {
  9100. onCompleteObservable: new BABYLON.Observable(),
  9101. abort: function () { return aborted = true; },
  9102. };
  9103. var requestFile = function () {
  9104. var request = new XMLHttpRequest();
  9105. var retryHandle = null;
  9106. fileRequest.abort = function () {
  9107. aborted = true;
  9108. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9109. request.abort();
  9110. }
  9111. if (retryHandle !== null) {
  9112. clearTimeout(retryHandle);
  9113. retryHandle = null;
  9114. }
  9115. };
  9116. var retryLoop = function (retryIndex) {
  9117. request.open('GET', loadUrl, true);
  9118. if (useArrayBuffer) {
  9119. request.responseType = "arraybuffer";
  9120. }
  9121. if (onProgress) {
  9122. request.addEventListener("progress", onProgress);
  9123. }
  9124. var onLoadEnd = function () {
  9125. request.removeEventListener("loadend", onLoadEnd);
  9126. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9127. fileRequest.onCompleteObservable.clear();
  9128. };
  9129. request.addEventListener("loadend", onLoadEnd);
  9130. var onReadyStateChange = function () {
  9131. if (aborted) {
  9132. return;
  9133. }
  9134. // In case of undefined state in some browsers.
  9135. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9136. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9137. request.removeEventListener("readystatechange", onReadyStateChange);
  9138. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9139. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9140. return;
  9141. }
  9142. var retryStrategy = Tools.DefaultRetryStrategy;
  9143. if (retryStrategy) {
  9144. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9145. if (waitTime !== -1) {
  9146. // Prevent the request from completing for retry.
  9147. request.removeEventListener("loadend", onLoadEnd);
  9148. request = new XMLHttpRequest();
  9149. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9150. return;
  9151. }
  9152. }
  9153. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9154. if (onError) {
  9155. onError(request, e);
  9156. }
  9157. else {
  9158. throw e;
  9159. }
  9160. }
  9161. };
  9162. request.addEventListener("readystatechange", onReadyStateChange);
  9163. request.send();
  9164. };
  9165. retryLoop(0);
  9166. };
  9167. // Caching all files
  9168. if (database && database.enableSceneOffline) {
  9169. var noIndexedDB_1 = function () {
  9170. if (!aborted) {
  9171. requestFile();
  9172. }
  9173. };
  9174. var loadFromIndexedDB = function () {
  9175. // TODO: database needs to support aborting and should return a IFileRequest
  9176. if (aborted) {
  9177. return;
  9178. }
  9179. if (database) {
  9180. database.loadFileFromDB(url, function (data) {
  9181. if (!aborted) {
  9182. onSuccess(data);
  9183. }
  9184. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9185. }, onProgress ? function (event) {
  9186. if (!aborted) {
  9187. onProgress(event);
  9188. }
  9189. } : undefined, noIndexedDB_1, useArrayBuffer);
  9190. }
  9191. };
  9192. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9193. }
  9194. else {
  9195. requestFile();
  9196. }
  9197. return fileRequest;
  9198. };
  9199. /**
  9200. * Load a script (identified by an url). When the url returns, the
  9201. * content of this file is added into a new script element, attached to the DOM (body element)
  9202. */
  9203. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9204. var head = document.getElementsByTagName('head')[0];
  9205. var script = document.createElement('script');
  9206. script.type = 'text/javascript';
  9207. script.src = scriptUrl;
  9208. script.onload = function () {
  9209. if (onSuccess) {
  9210. onSuccess();
  9211. }
  9212. };
  9213. script.onerror = function (e) {
  9214. if (onError) {
  9215. onError("Unable to load script '" + scriptUrl + "'", e);
  9216. }
  9217. };
  9218. head.appendChild(script);
  9219. };
  9220. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9221. var reader = new FileReader();
  9222. var request = {
  9223. onCompleteObservable: new BABYLON.Observable(),
  9224. abort: function () { return reader.abort(); },
  9225. };
  9226. reader.onloadend = function (e) {
  9227. request.onCompleteObservable.notifyObservers(request);
  9228. };
  9229. reader.onload = function (e) {
  9230. //target doesn't have result from ts 1.3
  9231. callback(e.target['result']);
  9232. };
  9233. reader.onprogress = progressCallback;
  9234. reader.readAsDataURL(fileToLoad);
  9235. return request;
  9236. };
  9237. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9238. var reader = new FileReader();
  9239. var request = {
  9240. onCompleteObservable: new BABYLON.Observable(),
  9241. abort: function () { return reader.abort(); },
  9242. };
  9243. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9244. reader.onerror = function (e) {
  9245. Tools.Log("Error while reading file: " + fileToLoad.name);
  9246. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9247. };
  9248. reader.onload = function (e) {
  9249. //target doesn't have result from ts 1.3
  9250. callback(e.target['result']);
  9251. };
  9252. if (progressCallBack) {
  9253. reader.onprogress = progressCallBack;
  9254. }
  9255. if (!useArrayBuffer) {
  9256. // Asynchronous read
  9257. reader.readAsText(fileToLoad);
  9258. }
  9259. else {
  9260. reader.readAsArrayBuffer(fileToLoad);
  9261. }
  9262. return request;
  9263. };
  9264. //returns a downloadable url to a file content.
  9265. Tools.FileAsURL = function (content) {
  9266. var fileBlob = new Blob([content]);
  9267. var url = window.URL || window.webkitURL;
  9268. var link = url.createObjectURL(fileBlob);
  9269. return link;
  9270. };
  9271. // Misc.
  9272. Tools.Format = function (value, decimals) {
  9273. if (decimals === void 0) { decimals = 2; }
  9274. return value.toFixed(decimals);
  9275. };
  9276. Tools.CheckExtends = function (v, min, max) {
  9277. if (v.x < min.x)
  9278. min.x = v.x;
  9279. if (v.y < min.y)
  9280. min.y = v.y;
  9281. if (v.z < min.z)
  9282. min.z = v.z;
  9283. if (v.x > max.x)
  9284. max.x = v.x;
  9285. if (v.y > max.y)
  9286. max.y = v.y;
  9287. if (v.z > max.z)
  9288. max.z = v.z;
  9289. };
  9290. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9291. for (var prop in source) {
  9292. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9293. continue;
  9294. }
  9295. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9296. continue;
  9297. }
  9298. var sourceValue = source[prop];
  9299. var typeOfSourceValue = typeof sourceValue;
  9300. if (typeOfSourceValue === "function") {
  9301. continue;
  9302. }
  9303. try {
  9304. if (typeOfSourceValue === "object") {
  9305. if (sourceValue instanceof Array) {
  9306. destination[prop] = [];
  9307. if (sourceValue.length > 0) {
  9308. if (typeof sourceValue[0] == "object") {
  9309. for (var index = 0; index < sourceValue.length; index++) {
  9310. var clonedValue = cloneValue(sourceValue[index], destination);
  9311. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9312. destination[prop].push(clonedValue);
  9313. }
  9314. }
  9315. }
  9316. else {
  9317. destination[prop] = sourceValue.slice(0);
  9318. }
  9319. }
  9320. }
  9321. else {
  9322. destination[prop] = cloneValue(sourceValue, destination);
  9323. }
  9324. }
  9325. else {
  9326. destination[prop] = sourceValue;
  9327. }
  9328. }
  9329. catch (e) {
  9330. // Just ignore error (it could be because of a read-only property)
  9331. }
  9332. }
  9333. };
  9334. Tools.IsEmpty = function (obj) {
  9335. for (var i in obj) {
  9336. if (obj.hasOwnProperty(i)) {
  9337. return false;
  9338. }
  9339. }
  9340. return true;
  9341. };
  9342. Tools.RegisterTopRootEvents = function (events) {
  9343. for (var index = 0; index < events.length; index++) {
  9344. var event = events[index];
  9345. window.addEventListener(event.name, event.handler, false);
  9346. try {
  9347. if (window.parent) {
  9348. window.parent.addEventListener(event.name, event.handler, false);
  9349. }
  9350. }
  9351. catch (e) {
  9352. // Silently fails...
  9353. }
  9354. }
  9355. };
  9356. Tools.UnregisterTopRootEvents = function (events) {
  9357. for (var index = 0; index < events.length; index++) {
  9358. var event = events[index];
  9359. window.removeEventListener(event.name, event.handler);
  9360. try {
  9361. if (window.parent) {
  9362. window.parent.removeEventListener(event.name, event.handler);
  9363. }
  9364. }
  9365. catch (e) {
  9366. // Silently fails...
  9367. }
  9368. }
  9369. };
  9370. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9371. if (mimeType === void 0) { mimeType = "image/png"; }
  9372. // Read the contents of the framebuffer
  9373. var numberOfChannelsByLine = width * 4;
  9374. var halfHeight = height / 2;
  9375. //Reading datas from WebGL
  9376. var data = engine.readPixels(0, 0, width, height);
  9377. //To flip image on Y axis.
  9378. for (var i = 0; i < halfHeight; i++) {
  9379. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9380. var currentCell = j + i * numberOfChannelsByLine;
  9381. var targetLine = height - i - 1;
  9382. var targetCell = j + targetLine * numberOfChannelsByLine;
  9383. var temp = data[currentCell];
  9384. data[currentCell] = data[targetCell];
  9385. data[targetCell] = temp;
  9386. }
  9387. }
  9388. // Create a 2D canvas to store the result
  9389. if (!screenshotCanvas) {
  9390. screenshotCanvas = document.createElement('canvas');
  9391. }
  9392. screenshotCanvas.width = width;
  9393. screenshotCanvas.height = height;
  9394. var context = screenshotCanvas.getContext('2d');
  9395. if (context) {
  9396. // Copy the pixels to a 2D canvas
  9397. var imageData = context.createImageData(width, height);
  9398. var castData = (imageData.data);
  9399. castData.set(data);
  9400. context.putImageData(imageData, 0, 0);
  9401. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9402. }
  9403. };
  9404. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9405. if (mimeType === void 0) { mimeType = "image/png"; }
  9406. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9407. if (successCallback) {
  9408. successCallback(base64Image);
  9409. }
  9410. else {
  9411. // We need HTMLCanvasElement.toBlob for HD screenshots
  9412. if (!screenshotCanvas.toBlob) {
  9413. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9414. screenshotCanvas.toBlob = function (callback, type, quality) {
  9415. var _this = this;
  9416. setTimeout(function () {
  9417. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9418. for (var i = 0; i < len; i++) {
  9419. arr[i] = binStr.charCodeAt(i);
  9420. }
  9421. callback(new Blob([arr], { type: type || 'image/png' }));
  9422. });
  9423. };
  9424. }
  9425. screenshotCanvas.toBlob(function (blob) {
  9426. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9427. if (("download" in document.createElement("a"))) {
  9428. if (!fileName) {
  9429. var date = new Date();
  9430. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9431. fileName = "screenshot_" + stringDate + ".png";
  9432. }
  9433. Tools.Download(blob, fileName);
  9434. }
  9435. else {
  9436. var url = URL.createObjectURL(blob);
  9437. var newWindow = window.open("");
  9438. if (!newWindow)
  9439. return;
  9440. var img = newWindow.document.createElement("img");
  9441. img.onload = function () {
  9442. // no longer need to read the blob so it's revoked
  9443. URL.revokeObjectURL(url);
  9444. };
  9445. img.src = url;
  9446. newWindow.document.body.appendChild(img);
  9447. }
  9448. });
  9449. }
  9450. };
  9451. /**
  9452. * Downloads a blob in the browser
  9453. * @param blob defines the blob to download
  9454. * @param fileName defines the name of the downloaded file
  9455. */
  9456. Tools.Download = function (blob, fileName) {
  9457. var url = window.URL.createObjectURL(blob);
  9458. var a = document.createElement("a");
  9459. document.body.appendChild(a);
  9460. a.style.display = "none";
  9461. a.href = url;
  9462. a.download = fileName;
  9463. a.addEventListener("click", function () {
  9464. if (a.parentElement) {
  9465. a.parentElement.removeChild(a);
  9466. }
  9467. });
  9468. a.click();
  9469. window.URL.revokeObjectURL(url);
  9470. };
  9471. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9472. if (mimeType === void 0) { mimeType = "image/png"; }
  9473. var width;
  9474. var height;
  9475. // If a precision value is specified
  9476. if (size.precision) {
  9477. width = Math.round(engine.getRenderWidth() * size.precision);
  9478. height = Math.round(width / engine.getAspectRatio(camera));
  9479. }
  9480. else if (size.width && size.height) {
  9481. width = size.width;
  9482. height = size.height;
  9483. }
  9484. //If passing only width, computing height to keep display canvas ratio.
  9485. else if (size.width && !size.height) {
  9486. width = size.width;
  9487. height = Math.round(width / engine.getAspectRatio(camera));
  9488. }
  9489. //If passing only height, computing width to keep display canvas ratio.
  9490. else if (size.height && !size.width) {
  9491. height = size.height;
  9492. width = Math.round(height * engine.getAspectRatio(camera));
  9493. }
  9494. //Assuming here that "size" parameter is a number
  9495. else if (!isNaN(size)) {
  9496. height = size;
  9497. width = size;
  9498. }
  9499. else {
  9500. Tools.Error("Invalid 'size' parameter !");
  9501. return;
  9502. }
  9503. if (!screenshotCanvas) {
  9504. screenshotCanvas = document.createElement('canvas');
  9505. }
  9506. screenshotCanvas.width = width;
  9507. screenshotCanvas.height = height;
  9508. var renderContext = screenshotCanvas.getContext("2d");
  9509. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9510. var newWidth = width;
  9511. var newHeight = newWidth / ratio;
  9512. if (newHeight > height) {
  9513. newHeight = height;
  9514. newWidth = newHeight * ratio;
  9515. }
  9516. var offsetX = Math.max(0, width - newWidth) / 2;
  9517. var offsetY = Math.max(0, height - newHeight) / 2;
  9518. var renderingCanvas = engine.getRenderingCanvas();
  9519. if (renderContext && renderingCanvas) {
  9520. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9521. }
  9522. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9523. };
  9524. /**
  9525. * Generates an image screenshot from the specified camera.
  9526. *
  9527. * @param engine The engine to use for rendering
  9528. * @param camera The camera to use for rendering
  9529. * @param size This parameter can be set to a single number or to an object with the
  9530. * following (optional) properties: precision, width, height. If a single number is passed,
  9531. * it will be used for both width and height. If an object is passed, the screenshot size
  9532. * will be derived from the parameters. The precision property is a multiplier allowing
  9533. * rendering at a higher or lower resolution.
  9534. * @param successCallback The callback receives a single parameter which contains the
  9535. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9536. * src parameter of an <img> to display it.
  9537. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9538. * Check your browser for supported MIME types.
  9539. * @param samples Texture samples (default: 1)
  9540. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9541. * @param fileName A name for for the downloaded file.
  9542. * @constructor
  9543. */
  9544. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9545. if (mimeType === void 0) { mimeType = "image/png"; }
  9546. if (samples === void 0) { samples = 1; }
  9547. if (antialiasing === void 0) { antialiasing = false; }
  9548. var width;
  9549. var height;
  9550. //If a precision value is specified
  9551. if (size.precision) {
  9552. width = Math.round(engine.getRenderWidth() * size.precision);
  9553. height = Math.round(width / engine.getAspectRatio(camera));
  9554. size = { width: width, height: height };
  9555. }
  9556. else if (size.width && size.height) {
  9557. width = size.width;
  9558. height = size.height;
  9559. }
  9560. //If passing only width, computing height to keep display canvas ratio.
  9561. else if (size.width && !size.height) {
  9562. width = size.width;
  9563. height = Math.round(width / engine.getAspectRatio(camera));
  9564. size = { width: width, height: height };
  9565. }
  9566. //If passing only height, computing width to keep display canvas ratio.
  9567. else if (size.height && !size.width) {
  9568. height = size.height;
  9569. width = Math.round(height * engine.getAspectRatio(camera));
  9570. size = { width: width, height: height };
  9571. }
  9572. //Assuming here that "size" parameter is a number
  9573. else if (!isNaN(size)) {
  9574. height = size;
  9575. width = size;
  9576. }
  9577. else {
  9578. Tools.Error("Invalid 'size' parameter !");
  9579. return;
  9580. }
  9581. var scene = camera.getScene();
  9582. var previousCamera = null;
  9583. if (scene.activeCamera !== camera) {
  9584. previousCamera = scene.activeCamera;
  9585. scene.activeCamera = camera;
  9586. }
  9587. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9588. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9589. texture.renderList = null;
  9590. texture.samples = samples;
  9591. if (antialiasing) {
  9592. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9593. }
  9594. texture.onAfterRenderObservable.add(function () {
  9595. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9596. });
  9597. scene.incrementRenderId();
  9598. scene.resetCachedMaterial();
  9599. texture.render(true);
  9600. texture.dispose();
  9601. if (previousCamera) {
  9602. scene.activeCamera = previousCamera;
  9603. }
  9604. camera.getProjectionMatrix(true); // Force cache refresh;
  9605. };
  9606. // XHR response validator for local file scenario
  9607. Tools.ValidateXHRData = function (xhr, dataType) {
  9608. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9609. if (dataType === void 0) { dataType = 7; }
  9610. try {
  9611. if (dataType & 1) {
  9612. if (xhr.responseText && xhr.responseText.length > 0) {
  9613. return true;
  9614. }
  9615. else if (dataType === 1) {
  9616. return false;
  9617. }
  9618. }
  9619. if (dataType & 2) {
  9620. // Check header width and height since there is no "TGA" magic number
  9621. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9622. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9623. return true;
  9624. }
  9625. else if (dataType === 2) {
  9626. return false;
  9627. }
  9628. }
  9629. if (dataType & 4) {
  9630. // Check for the "DDS" magic number
  9631. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9632. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9633. return true;
  9634. }
  9635. else {
  9636. return false;
  9637. }
  9638. }
  9639. }
  9640. catch (e) {
  9641. // Global protection
  9642. }
  9643. return false;
  9644. };
  9645. /**
  9646. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9647. * Be aware Math.random() could cause collisions, but:
  9648. * "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"
  9649. */
  9650. Tools.RandomId = function () {
  9651. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9652. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9653. return v.toString(16);
  9654. });
  9655. };
  9656. /**
  9657. * Test if the given uri is a base64 string.
  9658. * @param uri The uri to test
  9659. * @return True if the uri is a base64 string or false otherwise.
  9660. */
  9661. Tools.IsBase64 = function (uri) {
  9662. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9663. };
  9664. /**
  9665. * Decode the given base64 uri.
  9666. * @param uri The uri to decode
  9667. * @return The decoded base64 data.
  9668. */
  9669. Tools.DecodeBase64 = function (uri) {
  9670. var decodedString = atob(uri.split(",")[1]);
  9671. var bufferLength = decodedString.length;
  9672. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9673. for (var i = 0; i < bufferLength; i++) {
  9674. bufferView[i] = decodedString.charCodeAt(i);
  9675. }
  9676. return bufferView.buffer;
  9677. };
  9678. Object.defineProperty(Tools, "NoneLogLevel", {
  9679. get: function () {
  9680. return Tools._NoneLogLevel;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(Tools, "MessageLogLevel", {
  9686. get: function () {
  9687. return Tools._MessageLogLevel;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(Tools, "WarningLogLevel", {
  9693. get: function () {
  9694. return Tools._WarningLogLevel;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Object.defineProperty(Tools, "ErrorLogLevel", {
  9700. get: function () {
  9701. return Tools._ErrorLogLevel;
  9702. },
  9703. enumerable: true,
  9704. configurable: true
  9705. });
  9706. Object.defineProperty(Tools, "AllLogLevel", {
  9707. get: function () {
  9708. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Tools._AddLogEntry = function (entry) {
  9714. Tools._LogCache = entry + Tools._LogCache;
  9715. if (Tools.OnNewCacheEntry) {
  9716. Tools.OnNewCacheEntry(entry);
  9717. }
  9718. };
  9719. Tools._FormatMessage = function (message) {
  9720. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9721. var date = new Date();
  9722. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9723. };
  9724. Tools._LogDisabled = function (message) {
  9725. // nothing to do
  9726. };
  9727. Tools._LogEnabled = function (message) {
  9728. var formattedMessage = Tools._FormatMessage(message);
  9729. console.log("BJS - " + formattedMessage);
  9730. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9731. Tools._AddLogEntry(entry);
  9732. };
  9733. Tools._WarnDisabled = function (message) {
  9734. // nothing to do
  9735. };
  9736. Tools._WarnEnabled = function (message) {
  9737. var formattedMessage = Tools._FormatMessage(message);
  9738. console.warn("BJS - " + formattedMessage);
  9739. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9740. Tools._AddLogEntry(entry);
  9741. };
  9742. Tools._ErrorDisabled = function (message) {
  9743. // nothing to do
  9744. };
  9745. Tools._ErrorEnabled = function (message) {
  9746. Tools.errorsCount++;
  9747. var formattedMessage = Tools._FormatMessage(message);
  9748. console.error("BJS - " + formattedMessage);
  9749. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9750. Tools._AddLogEntry(entry);
  9751. };
  9752. Object.defineProperty(Tools, "LogCache", {
  9753. get: function () {
  9754. return Tools._LogCache;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Tools.ClearLogCache = function () {
  9760. Tools._LogCache = "";
  9761. Tools.errorsCount = 0;
  9762. };
  9763. Object.defineProperty(Tools, "LogLevels", {
  9764. set: function (level) {
  9765. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9766. Tools.Log = Tools._LogEnabled;
  9767. }
  9768. else {
  9769. Tools.Log = Tools._LogDisabled;
  9770. }
  9771. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9772. Tools.Warn = Tools._WarnEnabled;
  9773. }
  9774. else {
  9775. Tools.Warn = Tools._WarnDisabled;
  9776. }
  9777. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9778. Tools.Error = Tools._ErrorEnabled;
  9779. }
  9780. else {
  9781. Tools.Error = Tools._ErrorDisabled;
  9782. }
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Tools.IsWindowObjectExist = function () {
  9788. return (typeof window) !== "undefined";
  9789. };
  9790. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9791. get: function () {
  9792. return Tools._PerformanceNoneLogLevel;
  9793. },
  9794. enumerable: true,
  9795. configurable: true
  9796. });
  9797. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9798. get: function () {
  9799. return Tools._PerformanceUserMarkLogLevel;
  9800. },
  9801. enumerable: true,
  9802. configurable: true
  9803. });
  9804. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9805. get: function () {
  9806. return Tools._PerformanceConsoleLogLevel;
  9807. },
  9808. enumerable: true,
  9809. configurable: true
  9810. });
  9811. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9812. set: function (level) {
  9813. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9814. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9815. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9816. return;
  9817. }
  9818. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9819. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9820. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9821. return;
  9822. }
  9823. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9824. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9830. };
  9831. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9832. };
  9833. Tools._StartUserMark = function (counterName, condition) {
  9834. if (condition === void 0) { condition = true; }
  9835. if (!Tools._performance) {
  9836. if (!Tools.IsWindowObjectExist()) {
  9837. return;
  9838. }
  9839. Tools._performance = window.performance;
  9840. }
  9841. if (!condition || !Tools._performance.mark) {
  9842. return;
  9843. }
  9844. Tools._performance.mark(counterName + "-Begin");
  9845. };
  9846. Tools._EndUserMark = function (counterName, condition) {
  9847. if (condition === void 0) { condition = true; }
  9848. if (!condition || !Tools._performance.mark) {
  9849. return;
  9850. }
  9851. Tools._performance.mark(counterName + "-End");
  9852. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9853. };
  9854. Tools._StartPerformanceConsole = function (counterName, condition) {
  9855. if (condition === void 0) { condition = true; }
  9856. if (!condition) {
  9857. return;
  9858. }
  9859. Tools._StartUserMark(counterName, condition);
  9860. if (console.time) {
  9861. console.time(counterName);
  9862. }
  9863. };
  9864. Tools._EndPerformanceConsole = function (counterName, condition) {
  9865. if (condition === void 0) { condition = true; }
  9866. if (!condition) {
  9867. return;
  9868. }
  9869. Tools._EndUserMark(counterName, condition);
  9870. if (console.time) {
  9871. console.timeEnd(counterName);
  9872. }
  9873. };
  9874. Object.defineProperty(Tools, "Now", {
  9875. get: function () {
  9876. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9877. return window.performance.now();
  9878. }
  9879. return Date.now();
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. /**
  9885. * This method will return the name of the class used to create the instance of the given object.
  9886. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9887. * @param object the object to get the class name from
  9888. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9889. */
  9890. Tools.GetClassName = function (object, isType) {
  9891. if (isType === void 0) { isType = false; }
  9892. var name = null;
  9893. if (!isType && object.getClassName) {
  9894. name = object.getClassName();
  9895. }
  9896. else {
  9897. if (object instanceof Object) {
  9898. var classObj = isType ? object : Object.getPrototypeOf(object);
  9899. name = classObj.constructor["__bjsclassName__"];
  9900. }
  9901. if (!name) {
  9902. name = typeof object;
  9903. }
  9904. }
  9905. return name;
  9906. };
  9907. Tools.First = function (array, predicate) {
  9908. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9909. var el = array_1[_i];
  9910. if (predicate(el)) {
  9911. return el;
  9912. }
  9913. }
  9914. return null;
  9915. };
  9916. /**
  9917. * This method will return the name of the full name of the class, including its owning module (if any).
  9918. * 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).
  9919. * @param object the object to get the class name from
  9920. * @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.
  9921. */
  9922. Tools.getFullClassName = function (object, isType) {
  9923. if (isType === void 0) { isType = false; }
  9924. var className = null;
  9925. var moduleName = null;
  9926. if (!isType && object.getClassName) {
  9927. className = object.getClassName();
  9928. }
  9929. else {
  9930. if (object instanceof Object) {
  9931. var classObj = isType ? object : Object.getPrototypeOf(object);
  9932. className = classObj.constructor["__bjsclassName__"];
  9933. moduleName = classObj.constructor["__bjsmoduleName__"];
  9934. }
  9935. if (!className) {
  9936. className = typeof object;
  9937. }
  9938. }
  9939. if (!className) {
  9940. return null;
  9941. }
  9942. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9943. };
  9944. /**
  9945. * 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.
  9946. * @param array
  9947. */
  9948. Tools.arrayOrStringFeeder = function (array) {
  9949. return function (index) {
  9950. if (index >= array.length) {
  9951. return null;
  9952. }
  9953. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9954. if (val && val.getHashCode) {
  9955. val = val.getHashCode();
  9956. }
  9957. if (typeof val === "string") {
  9958. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9959. }
  9960. return val;
  9961. };
  9962. };
  9963. /**
  9964. * Compute the hashCode of a stream of number
  9965. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9966. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9967. * @return the hash code computed
  9968. */
  9969. Tools.hashCodeFromStream = function (feeder) {
  9970. // Based from here: http://stackoverflow.com/a/7616484/802124
  9971. var hash = 0;
  9972. var index = 0;
  9973. var chr = feeder(index++);
  9974. while (chr != null) {
  9975. hash = ((hash << 5) - hash) + chr;
  9976. hash |= 0; // Convert to 32bit integer
  9977. chr = feeder(index++);
  9978. }
  9979. return hash;
  9980. };
  9981. /**
  9982. * Returns a promise that resolves after the given amount of time.
  9983. * @param delay Number of milliseconds to delay
  9984. * @returns Promise that resolves after the given amount of time
  9985. */
  9986. Tools.DelayAsync = function (delay) {
  9987. return new Promise(function (resolve) {
  9988. setTimeout(function () {
  9989. resolve();
  9990. }, delay);
  9991. });
  9992. };
  9993. /**
  9994. * Gets the current gradient from an array of IValueGradient
  9995. * @param ratio defines the current ratio to get
  9996. * @param gradients defines the array of IValueGradient
  9997. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9998. */
  9999. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10000. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10001. var currentGradient = gradients[gradientIndex];
  10002. var nextGradient = gradients[gradientIndex + 1];
  10003. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10004. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10005. updateFunc(currentGradient, nextGradient, scale);
  10006. }
  10007. }
  10008. };
  10009. Tools.BaseUrl = "";
  10010. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10011. /**
  10012. * Default behaviour for cors in the application.
  10013. * It can be a string if the expected behavior is identical in the entire app.
  10014. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10015. */
  10016. Tools.CorsBehavior = "anonymous";
  10017. Tools.UseFallbackTexture = true;
  10018. /**
  10019. * Use this object to register external classes like custom textures or material
  10020. * to allow the laoders to instantiate them
  10021. */
  10022. Tools.RegisteredExternalClasses = {};
  10023. // Used in case of a texture loading problem
  10024. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhY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ivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  10025. Tools._tmpFloatArray = new Float32Array(1);
  10026. Tools.PreprocessUrl = function (url) {
  10027. return url;
  10028. };
  10029. // Logs
  10030. Tools._NoneLogLevel = 0;
  10031. Tools._MessageLogLevel = 1;
  10032. Tools._WarningLogLevel = 2;
  10033. Tools._ErrorLogLevel = 4;
  10034. Tools._LogCache = "";
  10035. Tools.errorsCount = 0;
  10036. Tools.Log = Tools._LogEnabled;
  10037. Tools.Warn = Tools._WarnEnabled;
  10038. Tools.Error = Tools._ErrorEnabled;
  10039. // Performances
  10040. Tools._PerformanceNoneLogLevel = 0;
  10041. Tools._PerformanceUserMarkLogLevel = 1;
  10042. Tools._PerformanceConsoleLogLevel = 2;
  10043. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10044. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10045. return Tools;
  10046. }());
  10047. BABYLON.Tools = Tools;
  10048. /**
  10049. * This class is used to track a performance counter which is number based.
  10050. * The user has access to many properties which give statistics of different nature
  10051. *
  10052. * The implementer can track two kinds of Performance Counter: time and count
  10053. * 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.
  10054. * 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.
  10055. */
  10056. var PerfCounter = /** @class */ (function () {
  10057. function PerfCounter() {
  10058. this._startMonitoringTime = 0;
  10059. this._min = 0;
  10060. this._max = 0;
  10061. this._average = 0;
  10062. this._lastSecAverage = 0;
  10063. this._current = 0;
  10064. this._totalValueCount = 0;
  10065. this._totalAccumulated = 0;
  10066. this._lastSecAccumulated = 0;
  10067. this._lastSecTime = 0;
  10068. this._lastSecValueCount = 0;
  10069. }
  10070. Object.defineProperty(PerfCounter.prototype, "min", {
  10071. /**
  10072. * Returns the smallest value ever
  10073. */
  10074. get: function () {
  10075. return this._min;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(PerfCounter.prototype, "max", {
  10081. /**
  10082. * Returns the biggest value ever
  10083. */
  10084. get: function () {
  10085. return this._max;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(PerfCounter.prototype, "average", {
  10091. /**
  10092. * Returns the average value since the performance counter is running
  10093. */
  10094. get: function () {
  10095. return this._average;
  10096. },
  10097. enumerable: true,
  10098. configurable: true
  10099. });
  10100. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10101. /**
  10102. * Returns the average value of the last second the counter was monitored
  10103. */
  10104. get: function () {
  10105. return this._lastSecAverage;
  10106. },
  10107. enumerable: true,
  10108. configurable: true
  10109. });
  10110. Object.defineProperty(PerfCounter.prototype, "current", {
  10111. /**
  10112. * Returns the current value
  10113. */
  10114. get: function () {
  10115. return this._current;
  10116. },
  10117. enumerable: true,
  10118. configurable: true
  10119. });
  10120. Object.defineProperty(PerfCounter.prototype, "total", {
  10121. get: function () {
  10122. return this._totalAccumulated;
  10123. },
  10124. enumerable: true,
  10125. configurable: true
  10126. });
  10127. Object.defineProperty(PerfCounter.prototype, "count", {
  10128. get: function () {
  10129. return this._totalValueCount;
  10130. },
  10131. enumerable: true,
  10132. configurable: true
  10133. });
  10134. /**
  10135. * Call this method to start monitoring a new frame.
  10136. * 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.
  10137. */
  10138. PerfCounter.prototype.fetchNewFrame = function () {
  10139. this._totalValueCount++;
  10140. this._current = 0;
  10141. this._lastSecValueCount++;
  10142. };
  10143. /**
  10144. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10145. * @param newCount the count value to add to the monitored count
  10146. * @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.
  10147. */
  10148. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10149. if (!PerfCounter.Enabled) {
  10150. return;
  10151. }
  10152. this._current += newCount;
  10153. if (fetchResult) {
  10154. this._fetchResult();
  10155. }
  10156. };
  10157. /**
  10158. * Start monitoring this performance counter
  10159. */
  10160. PerfCounter.prototype.beginMonitoring = function () {
  10161. if (!PerfCounter.Enabled) {
  10162. return;
  10163. }
  10164. this._startMonitoringTime = Tools.Now;
  10165. };
  10166. /**
  10167. * Compute the time lapsed since the previous beginMonitoring() call.
  10168. * @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
  10169. */
  10170. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10171. if (newFrame === void 0) { newFrame = true; }
  10172. if (!PerfCounter.Enabled) {
  10173. return;
  10174. }
  10175. if (newFrame) {
  10176. this.fetchNewFrame();
  10177. }
  10178. var currentTime = Tools.Now;
  10179. this._current = currentTime - this._startMonitoringTime;
  10180. if (newFrame) {
  10181. this._fetchResult();
  10182. }
  10183. };
  10184. PerfCounter.prototype._fetchResult = function () {
  10185. this._totalAccumulated += this._current;
  10186. this._lastSecAccumulated += this._current;
  10187. // Min/Max update
  10188. this._min = Math.min(this._min, this._current);
  10189. this._max = Math.max(this._max, this._current);
  10190. this._average = this._totalAccumulated / this._totalValueCount;
  10191. // Reset last sec?
  10192. var now = Tools.Now;
  10193. if ((now - this._lastSecTime) > 1000) {
  10194. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10195. this._lastSecTime = now;
  10196. this._lastSecAccumulated = 0;
  10197. this._lastSecValueCount = 0;
  10198. }
  10199. };
  10200. PerfCounter.Enabled = true;
  10201. return PerfCounter;
  10202. }());
  10203. BABYLON.PerfCounter = PerfCounter;
  10204. /**
  10205. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10206. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10207. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10208. * @param name The name of the class, case should be preserved
  10209. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10210. */
  10211. function className(name, module) {
  10212. return function (target) {
  10213. target["__bjsclassName__"] = name;
  10214. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10215. };
  10216. }
  10217. BABYLON.className = className;
  10218. /**
  10219. * An implementation of a loop for asynchronous functions.
  10220. */
  10221. var AsyncLoop = /** @class */ (function () {
  10222. /**
  10223. * Constroctor.
  10224. * @param iterations the number of iterations.
  10225. * @param _fn the function to run each iteration
  10226. * @param _successCallback the callback that will be called upon succesful execution
  10227. * @param offset starting offset.
  10228. */
  10229. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10230. if (offset === void 0) { offset = 0; }
  10231. this.iterations = iterations;
  10232. this._fn = _fn;
  10233. this._successCallback = _successCallback;
  10234. this.index = offset - 1;
  10235. this._done = false;
  10236. }
  10237. /**
  10238. * Execute the next iteration. Must be called after the last iteration was finished.
  10239. */
  10240. AsyncLoop.prototype.executeNext = function () {
  10241. if (!this._done) {
  10242. if (this.index + 1 < this.iterations) {
  10243. ++this.index;
  10244. this._fn(this);
  10245. }
  10246. else {
  10247. this.breakLoop();
  10248. }
  10249. }
  10250. };
  10251. /**
  10252. * Break the loop and run the success callback.
  10253. */
  10254. AsyncLoop.prototype.breakLoop = function () {
  10255. this._done = true;
  10256. this._successCallback();
  10257. };
  10258. /**
  10259. * Helper function
  10260. */
  10261. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10262. if (offset === void 0) { offset = 0; }
  10263. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10264. loop.executeNext();
  10265. return loop;
  10266. };
  10267. /**
  10268. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10269. * @param iterations total number of iterations
  10270. * @param syncedIterations number of synchronous iterations in each async iteration.
  10271. * @param fn the function to call each iteration.
  10272. * @param callback a success call back that will be called when iterating stops.
  10273. * @param breakFunction a break condition (optional)
  10274. * @param timeout timeout settings for the setTimeout function. default - 0.
  10275. * @constructor
  10276. */
  10277. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10278. if (timeout === void 0) { timeout = 0; }
  10279. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10280. if (breakFunction && breakFunction())
  10281. loop.breakLoop();
  10282. else {
  10283. setTimeout(function () {
  10284. for (var i = 0; i < syncedIterations; ++i) {
  10285. var iteration = (loop.index * syncedIterations) + i;
  10286. if (iteration >= iterations)
  10287. break;
  10288. fn(iteration);
  10289. if (breakFunction && breakFunction()) {
  10290. loop.breakLoop();
  10291. break;
  10292. }
  10293. }
  10294. loop.executeNext();
  10295. }, timeout);
  10296. }
  10297. }, callback);
  10298. };
  10299. return AsyncLoop;
  10300. }());
  10301. BABYLON.AsyncLoop = AsyncLoop;
  10302. })(BABYLON || (BABYLON = {}));
  10303. //# sourceMappingURL=babylon.tools.js.map
  10304. var BABYLON;
  10305. (function (BABYLON) {
  10306. var PromiseStates;
  10307. (function (PromiseStates) {
  10308. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10309. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10310. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10311. })(PromiseStates || (PromiseStates = {}));
  10312. var FulFillmentAgregator = /** @class */ (function () {
  10313. function FulFillmentAgregator() {
  10314. this.count = 0;
  10315. this.target = 0;
  10316. this.results = [];
  10317. }
  10318. return FulFillmentAgregator;
  10319. }());
  10320. var InternalPromise = /** @class */ (function () {
  10321. function InternalPromise(resolver) {
  10322. var _this = this;
  10323. this._state = PromiseStates.Pending;
  10324. this._children = new Array();
  10325. this._rejectWasConsumed = false;
  10326. if (!resolver) {
  10327. return;
  10328. }
  10329. try {
  10330. resolver(function (value) {
  10331. _this._resolve(value);
  10332. }, function (reason) {
  10333. _this._reject(reason);
  10334. });
  10335. }
  10336. catch (e) {
  10337. this._reject(e);
  10338. }
  10339. }
  10340. Object.defineProperty(InternalPromise.prototype, "_result", {
  10341. get: function () {
  10342. return this._resultValue;
  10343. },
  10344. set: function (value) {
  10345. this._resultValue = value;
  10346. if (this._parent && this._parent._result === undefined) {
  10347. this._parent._result = value;
  10348. }
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. InternalPromise.prototype.catch = function (onRejected) {
  10354. return this.then(undefined, onRejected);
  10355. };
  10356. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10357. var _this = this;
  10358. var newPromise = new InternalPromise();
  10359. newPromise._onFulfilled = onFulfilled;
  10360. newPromise._onRejected = onRejected;
  10361. // Composition
  10362. this._children.push(newPromise);
  10363. newPromise._parent = this;
  10364. if (this._state !== PromiseStates.Pending) {
  10365. BABYLON.Tools.SetImmediate(function () {
  10366. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10367. var returnedValue = newPromise._resolve(_this._result);
  10368. if (returnedValue !== undefined && returnedValue !== null) {
  10369. if (returnedValue._state !== undefined) {
  10370. var returnedPromise = returnedValue;
  10371. newPromise._children.push(returnedPromise);
  10372. returnedPromise._parent = newPromise;
  10373. newPromise = returnedPromise;
  10374. }
  10375. else {
  10376. newPromise._result = returnedValue;
  10377. }
  10378. }
  10379. }
  10380. else {
  10381. newPromise._reject(_this._reason);
  10382. }
  10383. });
  10384. }
  10385. return newPromise;
  10386. };
  10387. InternalPromise.prototype._moveChildren = function (children) {
  10388. var _this = this;
  10389. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10390. this._children.forEach(function (child) {
  10391. child._parent = _this;
  10392. });
  10393. if (this._state === PromiseStates.Fulfilled) {
  10394. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10395. var child = _b[_i];
  10396. child._resolve(this._result);
  10397. }
  10398. }
  10399. else if (this._state === PromiseStates.Rejected) {
  10400. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10401. var child = _d[_c];
  10402. child._reject(this._reason);
  10403. }
  10404. }
  10405. var _a;
  10406. };
  10407. InternalPromise.prototype._resolve = function (value) {
  10408. try {
  10409. this._state = PromiseStates.Fulfilled;
  10410. var returnedValue = null;
  10411. if (this._onFulfilled) {
  10412. returnedValue = this._onFulfilled(value);
  10413. }
  10414. if (returnedValue !== undefined && returnedValue !== null) {
  10415. if (returnedValue._state !== undefined) {
  10416. // Transmit children
  10417. var returnedPromise = returnedValue;
  10418. returnedPromise._parent = this;
  10419. returnedPromise._moveChildren(this._children);
  10420. value = returnedPromise._result;
  10421. }
  10422. else {
  10423. value = returnedValue;
  10424. }
  10425. }
  10426. this._result = value;
  10427. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10428. var child = _a[_i];
  10429. child._resolve(value);
  10430. }
  10431. this._children.length = 0;
  10432. delete this._onFulfilled;
  10433. delete this._onRejected;
  10434. }
  10435. catch (e) {
  10436. this._reject(e, true);
  10437. }
  10438. };
  10439. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10440. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10441. this._state = PromiseStates.Rejected;
  10442. this._reason = reason;
  10443. if (this._onRejected && !onLocalThrow) {
  10444. try {
  10445. this._onRejected(reason);
  10446. this._rejectWasConsumed = true;
  10447. }
  10448. catch (e) {
  10449. reason = e;
  10450. }
  10451. }
  10452. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10453. var child = _a[_i];
  10454. if (this._rejectWasConsumed) {
  10455. child._resolve(null);
  10456. }
  10457. else {
  10458. child._reject(reason);
  10459. }
  10460. }
  10461. this._children.length = 0;
  10462. delete this._onFulfilled;
  10463. delete this._onRejected;
  10464. };
  10465. InternalPromise.resolve = function (value) {
  10466. var newPromise = new InternalPromise();
  10467. newPromise._resolve(value);
  10468. return newPromise;
  10469. };
  10470. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10471. promise.then(function (value) {
  10472. agregator.results[index] = value;
  10473. agregator.count++;
  10474. if (agregator.count === agregator.target) {
  10475. agregator.rootPromise._resolve(agregator.results);
  10476. }
  10477. return null;
  10478. }, function (reason) {
  10479. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10480. agregator.rootPromise._reject(reason);
  10481. }
  10482. });
  10483. };
  10484. InternalPromise.all = function (promises) {
  10485. var newPromise = new InternalPromise();
  10486. var agregator = new FulFillmentAgregator();
  10487. agregator.target = promises.length;
  10488. agregator.rootPromise = newPromise;
  10489. if (promises.length) {
  10490. for (var index = 0; index < promises.length; index++) {
  10491. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10492. }
  10493. }
  10494. else {
  10495. newPromise._resolve([]);
  10496. }
  10497. return newPromise;
  10498. };
  10499. InternalPromise.race = function (promises) {
  10500. var newPromise = new InternalPromise();
  10501. if (promises.length) {
  10502. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10503. var promise = promises_1[_i];
  10504. promise.then(function (value) {
  10505. if (newPromise) {
  10506. newPromise._resolve(value);
  10507. newPromise = null;
  10508. }
  10509. return null;
  10510. }, function (reason) {
  10511. if (newPromise) {
  10512. newPromise._reject(reason);
  10513. newPromise = null;
  10514. }
  10515. });
  10516. }
  10517. }
  10518. return newPromise;
  10519. };
  10520. return InternalPromise;
  10521. }());
  10522. /**
  10523. * Helper class that provides a small promise polyfill
  10524. */
  10525. var PromisePolyfill = /** @class */ (function () {
  10526. function PromisePolyfill() {
  10527. }
  10528. /**
  10529. * Static function used to check if the polyfill is required
  10530. * If this is the case then the function will inject the polyfill to window.Promise
  10531. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10532. */
  10533. PromisePolyfill.Apply = function (force) {
  10534. if (force === void 0) { force = false; }
  10535. if (force || typeof Promise === 'undefined') {
  10536. var root = window;
  10537. root.Promise = InternalPromise;
  10538. }
  10539. };
  10540. return PromisePolyfill;
  10541. }());
  10542. BABYLON.PromisePolyfill = PromisePolyfill;
  10543. })(BABYLON || (BABYLON = {}));
  10544. //# sourceMappingURL=babylon.promise.js.map
  10545. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10546. var BABYLON;
  10547. (function (BABYLON) {
  10548. /**
  10549. * Helper class to push actions to a pool of workers.
  10550. */
  10551. var WorkerPool = /** @class */ (function () {
  10552. /**
  10553. * Constructor
  10554. * @param workers Array of workers to use for actions
  10555. */
  10556. function WorkerPool(workers) {
  10557. this._pendingActions = new Array();
  10558. this._workerInfos = workers.map(function (worker) { return ({
  10559. worker: worker,
  10560. active: false
  10561. }); });
  10562. }
  10563. /**
  10564. * Terminates all workers and clears any pending actions.
  10565. */
  10566. WorkerPool.prototype.dispose = function () {
  10567. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10568. var workerInfo = _a[_i];
  10569. workerInfo.worker.terminate();
  10570. }
  10571. delete this._workerInfos;
  10572. delete this._pendingActions;
  10573. };
  10574. /**
  10575. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10576. * pended until a worker has completed its action.
  10577. * @param action The action to perform. Call onComplete when the action is complete.
  10578. */
  10579. WorkerPool.prototype.push = function (action) {
  10580. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10581. var workerInfo = _a[_i];
  10582. if (!workerInfo.active) {
  10583. this._execute(workerInfo, action);
  10584. return;
  10585. }
  10586. }
  10587. this._pendingActions.push(action);
  10588. };
  10589. WorkerPool.prototype._execute = function (workerInfo, action) {
  10590. var _this = this;
  10591. workerInfo.active = true;
  10592. action(workerInfo.worker, function () {
  10593. workerInfo.active = false;
  10594. var nextAction = _this._pendingActions.shift();
  10595. if (nextAction) {
  10596. _this._execute(workerInfo, nextAction);
  10597. }
  10598. });
  10599. };
  10600. return WorkerPool;
  10601. }());
  10602. BABYLON.WorkerPool = WorkerPool;
  10603. })(BABYLON || (BABYLON = {}));
  10604. //# sourceMappingURL=babylon.workerPool.js.map
  10605. var BABYLON;
  10606. (function (BABYLON) {
  10607. /**
  10608. * @hidden
  10609. **/
  10610. var _AlphaState = /** @class */ (function () {
  10611. /**
  10612. * Initializes the state.
  10613. */
  10614. function _AlphaState() {
  10615. this._isAlphaBlendDirty = false;
  10616. this._isBlendFunctionParametersDirty = false;
  10617. this._isBlendEquationParametersDirty = false;
  10618. this._isBlendConstantsDirty = false;
  10619. this._alphaBlend = false;
  10620. this._blendFunctionParameters = new Array(4);
  10621. this._blendEquationParameters = new Array(2);
  10622. this._blendConstants = new Array(4);
  10623. this.reset();
  10624. }
  10625. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10626. get: function () {
  10627. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10628. },
  10629. enumerable: true,
  10630. configurable: true
  10631. });
  10632. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10633. get: function () {
  10634. return this._alphaBlend;
  10635. },
  10636. set: function (value) {
  10637. if (this._alphaBlend === value) {
  10638. return;
  10639. }
  10640. this._alphaBlend = value;
  10641. this._isAlphaBlendDirty = true;
  10642. },
  10643. enumerable: true,
  10644. configurable: true
  10645. });
  10646. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10647. if (this._blendConstants[0] === r &&
  10648. this._blendConstants[1] === g &&
  10649. this._blendConstants[2] === b &&
  10650. this._blendConstants[3] === a) {
  10651. return;
  10652. }
  10653. this._blendConstants[0] = r;
  10654. this._blendConstants[1] = g;
  10655. this._blendConstants[2] = b;
  10656. this._blendConstants[3] = a;
  10657. this._isBlendConstantsDirty = true;
  10658. };
  10659. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10660. if (this._blendFunctionParameters[0] === value0 &&
  10661. this._blendFunctionParameters[1] === value1 &&
  10662. this._blendFunctionParameters[2] === value2 &&
  10663. this._blendFunctionParameters[3] === value3) {
  10664. return;
  10665. }
  10666. this._blendFunctionParameters[0] = value0;
  10667. this._blendFunctionParameters[1] = value1;
  10668. this._blendFunctionParameters[2] = value2;
  10669. this._blendFunctionParameters[3] = value3;
  10670. this._isBlendFunctionParametersDirty = true;
  10671. };
  10672. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10673. if (this._blendEquationParameters[0] === rgb &&
  10674. this._blendEquationParameters[1] === alpha) {
  10675. return;
  10676. }
  10677. this._blendEquationParameters[0] = rgb;
  10678. this._blendEquationParameters[1] = alpha;
  10679. this._isBlendEquationParametersDirty = true;
  10680. };
  10681. _AlphaState.prototype.reset = function () {
  10682. this._alphaBlend = false;
  10683. this._blendFunctionParameters[0] = null;
  10684. this._blendFunctionParameters[1] = null;
  10685. this._blendFunctionParameters[2] = null;
  10686. this._blendFunctionParameters[3] = null;
  10687. this._blendEquationParameters[0] = null;
  10688. this._blendEquationParameters[1] = null;
  10689. this._blendConstants[0] = null;
  10690. this._blendConstants[1] = null;
  10691. this._blendConstants[2] = null;
  10692. this._blendConstants[3] = null;
  10693. this._isAlphaBlendDirty = true;
  10694. this._isBlendFunctionParametersDirty = false;
  10695. this._isBlendEquationParametersDirty = false;
  10696. this._isBlendConstantsDirty = false;
  10697. };
  10698. _AlphaState.prototype.apply = function (gl) {
  10699. if (!this.isDirty) {
  10700. return;
  10701. }
  10702. // Alpha blend
  10703. if (this._isAlphaBlendDirty) {
  10704. if (this._alphaBlend) {
  10705. gl.enable(gl.BLEND);
  10706. }
  10707. else {
  10708. gl.disable(gl.BLEND);
  10709. }
  10710. this._isAlphaBlendDirty = false;
  10711. }
  10712. // Alpha function
  10713. if (this._isBlendFunctionParametersDirty) {
  10714. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10715. this._isBlendFunctionParametersDirty = false;
  10716. }
  10717. // Alpha equation
  10718. if (this._isBlendEquationParametersDirty) {
  10719. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10720. this._isBlendEquationParametersDirty = false;
  10721. }
  10722. // Constants
  10723. if (this._isBlendConstantsDirty) {
  10724. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10725. this._isBlendConstantsDirty = false;
  10726. }
  10727. };
  10728. return _AlphaState;
  10729. }());
  10730. BABYLON._AlphaState = _AlphaState;
  10731. })(BABYLON || (BABYLON = {}));
  10732. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10733. var BABYLON;
  10734. (function (BABYLON) {
  10735. /**
  10736. * @hidden
  10737. **/
  10738. var _DepthCullingState = /** @class */ (function () {
  10739. /**
  10740. * Initializes the state.
  10741. */
  10742. function _DepthCullingState() {
  10743. this._isDepthTestDirty = false;
  10744. this._isDepthMaskDirty = false;
  10745. this._isDepthFuncDirty = false;
  10746. this._isCullFaceDirty = false;
  10747. this._isCullDirty = false;
  10748. this._isZOffsetDirty = false;
  10749. this._isFrontFaceDirty = false;
  10750. this.reset();
  10751. }
  10752. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10753. get: function () {
  10754. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10755. },
  10756. enumerable: true,
  10757. configurable: true
  10758. });
  10759. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10760. get: function () {
  10761. return this._zOffset;
  10762. },
  10763. set: function (value) {
  10764. if (this._zOffset === value) {
  10765. return;
  10766. }
  10767. this._zOffset = value;
  10768. this._isZOffsetDirty = true;
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10774. get: function () {
  10775. return this._cullFace;
  10776. },
  10777. set: function (value) {
  10778. if (this._cullFace === value) {
  10779. return;
  10780. }
  10781. this._cullFace = value;
  10782. this._isCullFaceDirty = true;
  10783. },
  10784. enumerable: true,
  10785. configurable: true
  10786. });
  10787. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10788. get: function () {
  10789. return this._cull;
  10790. },
  10791. set: function (value) {
  10792. if (this._cull === value) {
  10793. return;
  10794. }
  10795. this._cull = value;
  10796. this._isCullDirty = true;
  10797. },
  10798. enumerable: true,
  10799. configurable: true
  10800. });
  10801. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10802. get: function () {
  10803. return this._depthFunc;
  10804. },
  10805. set: function (value) {
  10806. if (this._depthFunc === value) {
  10807. return;
  10808. }
  10809. this._depthFunc = value;
  10810. this._isDepthFuncDirty = true;
  10811. },
  10812. enumerable: true,
  10813. configurable: true
  10814. });
  10815. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10816. get: function () {
  10817. return this._depthMask;
  10818. },
  10819. set: function (value) {
  10820. if (this._depthMask === value) {
  10821. return;
  10822. }
  10823. this._depthMask = value;
  10824. this._isDepthMaskDirty = true;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10830. get: function () {
  10831. return this._depthTest;
  10832. },
  10833. set: function (value) {
  10834. if (this._depthTest === value) {
  10835. return;
  10836. }
  10837. this._depthTest = value;
  10838. this._isDepthTestDirty = true;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10844. get: function () {
  10845. return this._frontFace;
  10846. },
  10847. set: function (value) {
  10848. if (this._frontFace === value) {
  10849. return;
  10850. }
  10851. this._frontFace = value;
  10852. this._isFrontFaceDirty = true;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. _DepthCullingState.prototype.reset = function () {
  10858. this._depthMask = true;
  10859. this._depthTest = true;
  10860. this._depthFunc = null;
  10861. this._cullFace = null;
  10862. this._cull = null;
  10863. this._zOffset = 0;
  10864. this._frontFace = null;
  10865. this._isDepthTestDirty = true;
  10866. this._isDepthMaskDirty = true;
  10867. this._isDepthFuncDirty = false;
  10868. this._isCullFaceDirty = false;
  10869. this._isCullDirty = false;
  10870. this._isZOffsetDirty = false;
  10871. this._isFrontFaceDirty = false;
  10872. };
  10873. _DepthCullingState.prototype.apply = function (gl) {
  10874. if (!this.isDirty) {
  10875. return;
  10876. }
  10877. // Cull
  10878. if (this._isCullDirty) {
  10879. if (this.cull) {
  10880. gl.enable(gl.CULL_FACE);
  10881. }
  10882. else {
  10883. gl.disable(gl.CULL_FACE);
  10884. }
  10885. this._isCullDirty = false;
  10886. }
  10887. // Cull face
  10888. if (this._isCullFaceDirty) {
  10889. gl.cullFace(this.cullFace);
  10890. this._isCullFaceDirty = false;
  10891. }
  10892. // Depth mask
  10893. if (this._isDepthMaskDirty) {
  10894. gl.depthMask(this.depthMask);
  10895. this._isDepthMaskDirty = false;
  10896. }
  10897. // Depth test
  10898. if (this._isDepthTestDirty) {
  10899. if (this.depthTest) {
  10900. gl.enable(gl.DEPTH_TEST);
  10901. }
  10902. else {
  10903. gl.disable(gl.DEPTH_TEST);
  10904. }
  10905. this._isDepthTestDirty = false;
  10906. }
  10907. // Depth func
  10908. if (this._isDepthFuncDirty) {
  10909. gl.depthFunc(this.depthFunc);
  10910. this._isDepthFuncDirty = false;
  10911. }
  10912. // zOffset
  10913. if (this._isZOffsetDirty) {
  10914. if (this.zOffset) {
  10915. gl.enable(gl.POLYGON_OFFSET_FILL);
  10916. gl.polygonOffset(this.zOffset, 0);
  10917. }
  10918. else {
  10919. gl.disable(gl.POLYGON_OFFSET_FILL);
  10920. }
  10921. this._isZOffsetDirty = false;
  10922. }
  10923. // Front face
  10924. if (this._isFrontFaceDirty) {
  10925. gl.frontFace(this.frontFace);
  10926. this._isFrontFaceDirty = false;
  10927. }
  10928. };
  10929. return _DepthCullingState;
  10930. }());
  10931. BABYLON._DepthCullingState = _DepthCullingState;
  10932. })(BABYLON || (BABYLON = {}));
  10933. //# sourceMappingURL=babylon.depthCullingState.js.map
  10934. var BABYLON;
  10935. (function (BABYLON) {
  10936. /**
  10937. * @hidden
  10938. **/
  10939. var _StencilState = /** @class */ (function () {
  10940. function _StencilState() {
  10941. this._isStencilTestDirty = false;
  10942. this._isStencilMaskDirty = false;
  10943. this._isStencilFuncDirty = false;
  10944. this._isStencilOpDirty = false;
  10945. this.reset();
  10946. }
  10947. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10948. get: function () {
  10949. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10955. get: function () {
  10956. return this._stencilFunc;
  10957. },
  10958. set: function (value) {
  10959. if (this._stencilFunc === value) {
  10960. return;
  10961. }
  10962. this._stencilFunc = value;
  10963. this._isStencilFuncDirty = true;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10969. get: function () {
  10970. return this._stencilFuncRef;
  10971. },
  10972. set: function (value) {
  10973. if (this._stencilFuncRef === value) {
  10974. return;
  10975. }
  10976. this._stencilFuncRef = value;
  10977. this._isStencilFuncDirty = true;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10983. get: function () {
  10984. return this._stencilFuncMask;
  10985. },
  10986. set: function (value) {
  10987. if (this._stencilFuncMask === value) {
  10988. return;
  10989. }
  10990. this._stencilFuncMask = value;
  10991. this._isStencilFuncDirty = true;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10997. get: function () {
  10998. return this._stencilOpStencilFail;
  10999. },
  11000. set: function (value) {
  11001. if (this._stencilOpStencilFail === value) {
  11002. return;
  11003. }
  11004. this._stencilOpStencilFail = value;
  11005. this._isStencilOpDirty = true;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11011. get: function () {
  11012. return this._stencilOpDepthFail;
  11013. },
  11014. set: function (value) {
  11015. if (this._stencilOpDepthFail === value) {
  11016. return;
  11017. }
  11018. this._stencilOpDepthFail = value;
  11019. this._isStencilOpDirty = true;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11025. get: function () {
  11026. return this._stencilOpStencilDepthPass;
  11027. },
  11028. set: function (value) {
  11029. if (this._stencilOpStencilDepthPass === value) {
  11030. return;
  11031. }
  11032. this._stencilOpStencilDepthPass = value;
  11033. this._isStencilOpDirty = true;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11039. get: function () {
  11040. return this._stencilMask;
  11041. },
  11042. set: function (value) {
  11043. if (this._stencilMask === value) {
  11044. return;
  11045. }
  11046. this._stencilMask = value;
  11047. this._isStencilMaskDirty = true;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11053. get: function () {
  11054. return this._stencilTest;
  11055. },
  11056. set: function (value) {
  11057. if (this._stencilTest === value) {
  11058. return;
  11059. }
  11060. this._stencilTest = value;
  11061. this._isStencilTestDirty = true;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. _StencilState.prototype.reset = function () {
  11067. this._stencilTest = false;
  11068. this._stencilMask = 0xFF;
  11069. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11070. this._stencilFuncRef = 1;
  11071. this._stencilFuncMask = 0xFF;
  11072. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11073. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11074. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11075. this._isStencilTestDirty = true;
  11076. this._isStencilMaskDirty = true;
  11077. this._isStencilFuncDirty = true;
  11078. this._isStencilOpDirty = true;
  11079. };
  11080. _StencilState.prototype.apply = function (gl) {
  11081. if (!this.isDirty) {
  11082. return;
  11083. }
  11084. // Stencil test
  11085. if (this._isStencilTestDirty) {
  11086. if (this.stencilTest) {
  11087. gl.enable(gl.STENCIL_TEST);
  11088. }
  11089. else {
  11090. gl.disable(gl.STENCIL_TEST);
  11091. }
  11092. this._isStencilTestDirty = false;
  11093. }
  11094. // Stencil mask
  11095. if (this._isStencilMaskDirty) {
  11096. gl.stencilMask(this.stencilMask);
  11097. this._isStencilMaskDirty = false;
  11098. }
  11099. // Stencil func
  11100. if (this._isStencilFuncDirty) {
  11101. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11102. this._isStencilFuncDirty = false;
  11103. }
  11104. // Stencil op
  11105. if (this._isStencilOpDirty) {
  11106. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11107. this._isStencilOpDirty = false;
  11108. }
  11109. };
  11110. return _StencilState;
  11111. }());
  11112. BABYLON._StencilState = _StencilState;
  11113. })(BABYLON || (BABYLON = {}));
  11114. //# sourceMappingURL=babylon.stencilState.js.map
  11115. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11116. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11117. s = arguments[i];
  11118. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11119. t[p] = s[p];
  11120. }
  11121. return t;
  11122. };
  11123. var BABYLON;
  11124. (function (BABYLON) {
  11125. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11126. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11127. };
  11128. var compileRawShader = function (gl, source, type) {
  11129. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11130. gl.shaderSource(shader, source);
  11131. gl.compileShader(shader);
  11132. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11133. var log = gl.getShaderInfoLog(shader);
  11134. if (log) {
  11135. throw new Error(log);
  11136. }
  11137. }
  11138. if (!shader) {
  11139. throw new Error("Something went wrong while compile the shader.");
  11140. }
  11141. return shader;
  11142. };
  11143. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11144. var magFilter = gl.NEAREST;
  11145. var minFilter = gl.NEAREST;
  11146. switch (samplingMode) {
  11147. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11148. magFilter = gl.LINEAR;
  11149. if (generateMipMaps) {
  11150. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11151. }
  11152. else {
  11153. minFilter = gl.LINEAR;
  11154. }
  11155. break;
  11156. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11157. magFilter = gl.LINEAR;
  11158. if (generateMipMaps) {
  11159. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11160. }
  11161. else {
  11162. minFilter = gl.LINEAR;
  11163. }
  11164. break;
  11165. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11166. magFilter = gl.NEAREST;
  11167. if (generateMipMaps) {
  11168. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11169. }
  11170. else {
  11171. minFilter = gl.NEAREST;
  11172. }
  11173. break;
  11174. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11175. magFilter = gl.NEAREST;
  11176. if (generateMipMaps) {
  11177. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11178. }
  11179. else {
  11180. minFilter = gl.NEAREST;
  11181. }
  11182. break;
  11183. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11184. magFilter = gl.NEAREST;
  11185. if (generateMipMaps) {
  11186. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11187. }
  11188. else {
  11189. minFilter = gl.LINEAR;
  11190. }
  11191. break;
  11192. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11193. magFilter = gl.NEAREST;
  11194. if (generateMipMaps) {
  11195. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11196. }
  11197. else {
  11198. minFilter = gl.LINEAR;
  11199. }
  11200. break;
  11201. case BABYLON.Texture.NEAREST_LINEAR:
  11202. magFilter = gl.NEAREST;
  11203. minFilter = gl.LINEAR;
  11204. break;
  11205. case BABYLON.Texture.NEAREST_NEAREST:
  11206. magFilter = gl.NEAREST;
  11207. minFilter = gl.NEAREST;
  11208. break;
  11209. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11210. magFilter = gl.LINEAR;
  11211. if (generateMipMaps) {
  11212. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11213. }
  11214. else {
  11215. minFilter = gl.NEAREST;
  11216. }
  11217. break;
  11218. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11219. magFilter = gl.LINEAR;
  11220. if (generateMipMaps) {
  11221. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11222. }
  11223. else {
  11224. minFilter = gl.NEAREST;
  11225. }
  11226. break;
  11227. case BABYLON.Texture.LINEAR_LINEAR:
  11228. magFilter = gl.LINEAR;
  11229. minFilter = gl.LINEAR;
  11230. break;
  11231. case BABYLON.Texture.LINEAR_NEAREST:
  11232. magFilter = gl.LINEAR;
  11233. minFilter = gl.NEAREST;
  11234. break;
  11235. }
  11236. return {
  11237. min: minFilter,
  11238. mag: magFilter
  11239. };
  11240. };
  11241. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11242. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11243. var img;
  11244. var onload = function () {
  11245. loadedImages[index] = img;
  11246. loadedImages._internalCount++;
  11247. if (scene) {
  11248. scene._removePendingData(img);
  11249. }
  11250. if (loadedImages._internalCount === 6) {
  11251. onfinish(loadedImages);
  11252. }
  11253. };
  11254. var onerror = function (message, exception) {
  11255. if (scene) {
  11256. scene._removePendingData(img);
  11257. }
  11258. if (onErrorCallBack) {
  11259. onErrorCallBack(message, exception);
  11260. }
  11261. };
  11262. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11263. if (scene) {
  11264. scene._addPendingData(img);
  11265. }
  11266. };
  11267. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11268. if (onError === void 0) { onError = null; }
  11269. var loadedImages = [];
  11270. loadedImages._internalCount = 0;
  11271. for (var index = 0; index < 6; index++) {
  11272. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11273. }
  11274. };
  11275. var BufferPointer = /** @class */ (function () {
  11276. function BufferPointer() {
  11277. }
  11278. return BufferPointer;
  11279. }());
  11280. /**
  11281. * Interface for attribute information associated with buffer instanciation
  11282. */
  11283. var InstancingAttributeInfo = /** @class */ (function () {
  11284. function InstancingAttributeInfo() {
  11285. }
  11286. return InstancingAttributeInfo;
  11287. }());
  11288. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11289. /**
  11290. * Define options used to create a render target texture
  11291. */
  11292. var RenderTargetCreationOptions = /** @class */ (function () {
  11293. function RenderTargetCreationOptions() {
  11294. }
  11295. return RenderTargetCreationOptions;
  11296. }());
  11297. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11298. /**
  11299. * Define options used to create a depth texture
  11300. */
  11301. var DepthTextureCreationOptions = /** @class */ (function () {
  11302. function DepthTextureCreationOptions() {
  11303. }
  11304. return DepthTextureCreationOptions;
  11305. }());
  11306. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11307. /**
  11308. * Class used to describe the capabilities of the engine relatively to the current browser
  11309. */
  11310. var EngineCapabilities = /** @class */ (function () {
  11311. function EngineCapabilities() {
  11312. }
  11313. return EngineCapabilities;
  11314. }());
  11315. BABYLON.EngineCapabilities = EngineCapabilities;
  11316. /**
  11317. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11318. */
  11319. var Engine = /** @class */ (function () {
  11320. /**
  11321. * Creates a new engine
  11322. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11323. * @param antialias defines enable antialiasing (default: false)
  11324. * @param options defines further options to be sent to the getContext() function
  11325. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11326. */
  11327. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11328. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11329. var _this = this;
  11330. // Public members
  11331. /**
  11332. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11333. */
  11334. this.forcePOTTextures = false;
  11335. /**
  11336. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11337. */
  11338. this.isFullscreen = false;
  11339. /**
  11340. * Gets a boolean indicating if the pointer is currently locked
  11341. */
  11342. this.isPointerLock = false;
  11343. /**
  11344. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11345. */
  11346. this.cullBackFaces = true;
  11347. /**
  11348. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11349. */
  11350. this.renderEvenInBackground = true;
  11351. /**
  11352. * Gets or sets a boolean indicating that cache can be kept between frames
  11353. */
  11354. this.preventCacheWipeBetweenFrames = false;
  11355. /**
  11356. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11357. **/
  11358. this.enableOfflineSupport = false;
  11359. /**
  11360. * 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)
  11361. **/
  11362. this.disableManifestCheck = false;
  11363. /**
  11364. * Gets the list of created scenes
  11365. */
  11366. this.scenes = new Array();
  11367. /**
  11368. * Gets the list of created postprocesses
  11369. */
  11370. this.postProcesses = new Array();
  11371. // Observables
  11372. /**
  11373. * Observable event triggered each time the rendering canvas is resized
  11374. */
  11375. this.onResizeObservable = new BABYLON.Observable();
  11376. /**
  11377. * Observable event triggered each time the canvas loses focus
  11378. */
  11379. this.onCanvasBlurObservable = new BABYLON.Observable();
  11380. /**
  11381. * Observable event triggered each time the canvas gains focus
  11382. */
  11383. this.onCanvasFocusObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable event triggered each time the canvas receives pointerout event
  11386. */
  11387. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11388. /**
  11389. * Observable event triggered before each texture is initialized
  11390. */
  11391. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11392. //WebVR
  11393. this._vrDisplay = undefined;
  11394. this._vrSupported = false;
  11395. this._vrExclusivePointerMode = false;
  11396. // Uniform buffers list
  11397. /**
  11398. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11399. */
  11400. this.disableUniformBuffers = false;
  11401. /** @hidden */
  11402. this._uniformBuffers = new Array();
  11403. // Observables
  11404. /**
  11405. * Observable raised when the engine begins a new frame
  11406. */
  11407. this.onBeginFrameObservable = new BABYLON.Observable();
  11408. /**
  11409. * Observable raised when the engine ends the current frame
  11410. */
  11411. this.onEndFrameObservable = new BABYLON.Observable();
  11412. /**
  11413. * Observable raised when the engine is about to compile a shader
  11414. */
  11415. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11416. /**
  11417. * Observable raised when the engine has jsut compiled a shader
  11418. */
  11419. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11420. this._windowIsBackground = false;
  11421. this._webGLVersion = 1.0;
  11422. /** @hidden */
  11423. this._badOS = false;
  11424. /** @hidden */
  11425. this._badDesktopOS = false;
  11426. /**
  11427. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11428. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11429. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11430. */
  11431. this.disableTextureBindingOptimization = false;
  11432. /**
  11433. * Observable signaled when VR display mode changes
  11434. */
  11435. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11436. /**
  11437. * Observable signaled when VR request present is complete
  11438. */
  11439. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11440. /**
  11441. * Observable signaled when VR request present starts
  11442. */
  11443. this.onVRRequestPresentStart = new BABYLON.Observable();
  11444. this._colorWrite = true;
  11445. /** @hidden */
  11446. this._drawCalls = new BABYLON.PerfCounter();
  11447. /** @hidden */
  11448. this._textureCollisions = new BABYLON.PerfCounter();
  11449. this._renderingQueueLaunched = false;
  11450. this._activeRenderLoops = new Array();
  11451. // Deterministic lockstepMaxSteps
  11452. this._deterministicLockstep = false;
  11453. this._lockstepMaxSteps = 4;
  11454. // Lost context
  11455. /**
  11456. * Observable signaled when a context lost event is raised
  11457. */
  11458. this.onContextLostObservable = new BABYLON.Observable();
  11459. /**
  11460. * Observable signaled when a context restored event is raised
  11461. */
  11462. this.onContextRestoredObservable = new BABYLON.Observable();
  11463. this._contextWasLost = false;
  11464. this._doNotHandleContextLost = false;
  11465. // FPS
  11466. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11467. this._fps = 60;
  11468. this._deltaTime = 0;
  11469. /**
  11470. * Turn this value on if you want to pause FPS computation when in background
  11471. */
  11472. this.disablePerformanceMonitorInBackground = false;
  11473. // States
  11474. /** @hidden */
  11475. this._depthCullingState = new BABYLON._DepthCullingState();
  11476. /** @hidden */
  11477. this._stencilState = new BABYLON._StencilState();
  11478. /** @hidden */
  11479. this._alphaState = new BABYLON._AlphaState();
  11480. /** @hidden */
  11481. this._alphaMode = Engine.ALPHA_DISABLE;
  11482. // Cache
  11483. this._internalTexturesCache = new Array();
  11484. /** @hidden */
  11485. this._activeChannel = 0;
  11486. this._currentTextureChannel = -1;
  11487. /** @hidden */
  11488. this._boundTexturesCache = {};
  11489. this._compiledEffects = {};
  11490. this._vertexAttribArraysEnabled = [];
  11491. this._uintIndicesCurrentlySet = false;
  11492. this._currentBoundBuffer = new Array();
  11493. this._currentBufferPointers = new Array();
  11494. this._currentInstanceLocations = new Array();
  11495. this._currentInstanceBuffers = new Array();
  11496. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11497. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11498. this._vaoRecordInProgress = false;
  11499. this._mustWipeVertexAttributes = false;
  11500. this._nextFreeTextureSlots = new Array();
  11501. this._maxSimultaneousTextures = 0;
  11502. this._activeRequests = new Array();
  11503. // Hardware supported Compressed Textures
  11504. this._texturesSupported = new Array();
  11505. /**
  11506. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11507. */
  11508. this.premultipliedAlpha = true;
  11509. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11510. this._onVRFullScreenTriggered = function () {
  11511. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11512. //get the old size before we change
  11513. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11514. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11515. //get the width and height, change the render size
  11516. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11517. _this.setHardwareScalingLevel(1);
  11518. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11519. }
  11520. else {
  11521. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11522. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11523. }
  11524. };
  11525. this._unpackFlipYCached = null;
  11526. this._boundUniforms = {};
  11527. // Register promises
  11528. BABYLON.PromisePolyfill.Apply();
  11529. var canvas = null;
  11530. Engine.Instances.push(this);
  11531. if (!canvasOrContext) {
  11532. return;
  11533. }
  11534. options = options || {};
  11535. if (canvasOrContext.getContext) {
  11536. canvas = canvasOrContext;
  11537. this._renderingCanvas = canvas;
  11538. if (antialias != null) {
  11539. options.antialias = antialias;
  11540. }
  11541. if (options.deterministicLockstep === undefined) {
  11542. options.deterministicLockstep = false;
  11543. }
  11544. if (options.lockstepMaxSteps === undefined) {
  11545. options.lockstepMaxSteps = 4;
  11546. }
  11547. if (options.preserveDrawingBuffer === undefined) {
  11548. options.preserveDrawingBuffer = false;
  11549. }
  11550. if (options.audioEngine === undefined) {
  11551. options.audioEngine = true;
  11552. }
  11553. if (options.stencil === undefined) {
  11554. options.stencil = true;
  11555. }
  11556. if (options.premultipliedAlpha === false) {
  11557. this.premultipliedAlpha = false;
  11558. }
  11559. this._deterministicLockstep = options.deterministicLockstep;
  11560. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11561. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11562. // Exceptions
  11563. if (navigator && navigator.userAgent) {
  11564. var ua = navigator.userAgent;
  11565. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11566. var exception = _a[_i];
  11567. var key = exception.key;
  11568. var targets = exception.targets;
  11569. if (ua.indexOf(key) > -1) {
  11570. if (exception.capture && exception.captureConstraint) {
  11571. var capture = exception.capture;
  11572. var constraint = exception.captureConstraint;
  11573. var regex = new RegExp(capture);
  11574. var matches = regex.exec(ua);
  11575. if (matches && matches.length > 0) {
  11576. var capturedValue = parseInt(matches[matches.length - 1]);
  11577. if (capturedValue >= constraint) {
  11578. continue;
  11579. }
  11580. }
  11581. }
  11582. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11583. var target = targets_1[_b];
  11584. switch (target) {
  11585. case "uniformBuffer":
  11586. this.disableUniformBuffers = true;
  11587. break;
  11588. case "textureBindingOptimization":
  11589. this.disableTextureBindingOptimization = true;
  11590. break;
  11591. }
  11592. }
  11593. }
  11594. }
  11595. }
  11596. // GL
  11597. if (!options.disableWebGL2Support) {
  11598. try {
  11599. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11600. if (this._gl) {
  11601. this._webGLVersion = 2.0;
  11602. }
  11603. }
  11604. catch (e) {
  11605. // Do nothing
  11606. }
  11607. }
  11608. if (!this._gl) {
  11609. if (!canvas) {
  11610. throw new Error("The provided canvas is null or undefined.");
  11611. }
  11612. try {
  11613. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11614. }
  11615. catch (e) {
  11616. throw new Error("WebGL not supported");
  11617. }
  11618. }
  11619. if (!this._gl) {
  11620. throw new Error("WebGL not supported");
  11621. }
  11622. this._onCanvasFocus = function () {
  11623. _this.onCanvasFocusObservable.notifyObservers(_this);
  11624. };
  11625. this._onCanvasBlur = function () {
  11626. _this.onCanvasBlurObservable.notifyObservers(_this);
  11627. };
  11628. canvas.addEventListener("focus", this._onCanvasFocus);
  11629. canvas.addEventListener("blur", this._onCanvasBlur);
  11630. this._onBlur = function () {
  11631. if (_this.disablePerformanceMonitorInBackground) {
  11632. _this._performanceMonitor.disable();
  11633. }
  11634. _this._windowIsBackground = true;
  11635. };
  11636. this._onFocus = function () {
  11637. if (_this.disablePerformanceMonitorInBackground) {
  11638. _this._performanceMonitor.enable();
  11639. }
  11640. _this._windowIsBackground = false;
  11641. };
  11642. this._onCanvasPointerOut = function (ev) {
  11643. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11644. };
  11645. window.addEventListener("blur", this._onBlur);
  11646. window.addEventListener("focus", this._onFocus);
  11647. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11648. // Context lost
  11649. if (!this._doNotHandleContextLost) {
  11650. this._onContextLost = function (evt) {
  11651. evt.preventDefault();
  11652. _this._contextWasLost = true;
  11653. BABYLON.Tools.Warn("WebGL context lost.");
  11654. _this.onContextLostObservable.notifyObservers(_this);
  11655. };
  11656. this._onContextRestored = function (evt) {
  11657. // Adding a timeout to avoid race condition at browser level
  11658. setTimeout(function () {
  11659. // Rebuild gl context
  11660. _this._initGLContext();
  11661. // Rebuild effects
  11662. _this._rebuildEffects();
  11663. // Rebuild textures
  11664. _this._rebuildInternalTextures();
  11665. // Rebuild buffers
  11666. _this._rebuildBuffers();
  11667. // Cache
  11668. _this.wipeCaches(true);
  11669. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11670. _this.onContextRestoredObservable.notifyObservers(_this);
  11671. _this._contextWasLost = false;
  11672. }, 0);
  11673. };
  11674. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11675. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11676. }
  11677. }
  11678. else {
  11679. this._gl = canvasOrContext;
  11680. this._renderingCanvas = this._gl.canvas;
  11681. if (this._gl.renderbufferStorageMultisample) {
  11682. this._webGLVersion = 2.0;
  11683. }
  11684. options.stencil = this._gl.getContextAttributes().stencil;
  11685. }
  11686. // Viewport
  11687. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11688. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11689. this.resize();
  11690. this._isStencilEnable = options.stencil ? true : false;
  11691. this._initGLContext();
  11692. if (canvas) {
  11693. // Fullscreen
  11694. this._onFullscreenChange = function () {
  11695. if (document.fullscreen !== undefined) {
  11696. _this.isFullscreen = document.fullscreen;
  11697. }
  11698. else if (document.mozFullScreen !== undefined) {
  11699. _this.isFullscreen = document.mozFullScreen;
  11700. }
  11701. else if (document.webkitIsFullScreen !== undefined) {
  11702. _this.isFullscreen = document.webkitIsFullScreen;
  11703. }
  11704. else if (document.msIsFullScreen !== undefined) {
  11705. _this.isFullscreen = document.msIsFullScreen;
  11706. }
  11707. // Pointer lock
  11708. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11709. canvas.requestPointerLock = canvas.requestPointerLock ||
  11710. canvas.msRequestPointerLock ||
  11711. canvas.mozRequestPointerLock ||
  11712. canvas.webkitRequestPointerLock;
  11713. if (canvas.requestPointerLock) {
  11714. canvas.requestPointerLock();
  11715. }
  11716. }
  11717. };
  11718. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11719. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11720. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11721. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11722. // Pointer lock
  11723. this._onPointerLockChange = function () {
  11724. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11725. document.webkitPointerLockElement === canvas ||
  11726. document.msPointerLockElement === canvas ||
  11727. document.pointerLockElement === canvas);
  11728. };
  11729. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11730. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11731. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11732. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11733. this._onVRDisplayPointerRestricted = function () {
  11734. if (canvas) {
  11735. canvas.requestPointerLock();
  11736. }
  11737. };
  11738. this._onVRDisplayPointerUnrestricted = function () {
  11739. document.exitPointerLock();
  11740. };
  11741. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11742. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11743. }
  11744. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11745. Engine.audioEngine = new BABYLON.AudioEngine();
  11746. }
  11747. // Prepare buffer pointers
  11748. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11749. this._currentBufferPointers[i] = new BufferPointer();
  11750. }
  11751. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11752. // Load WebVR Devices
  11753. if (options.autoEnableWebVR) {
  11754. this.initWebVR();
  11755. }
  11756. // Detect if we are running on a faulty buggy OS.
  11757. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11758. // Detect if we are running on a faulty buggy desktop OS.
  11759. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11760. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11761. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11762. }
  11763. Object.defineProperty(Engine, "LastCreatedEngine", {
  11764. /**
  11765. * Gets the latest created engine
  11766. */
  11767. get: function () {
  11768. if (Engine.Instances.length === 0) {
  11769. return null;
  11770. }
  11771. return Engine.Instances[Engine.Instances.length - 1];
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(Engine, "LastCreatedScene", {
  11777. /**
  11778. * Gets the latest created scene
  11779. */
  11780. get: function () {
  11781. var lastCreatedEngine = Engine.LastCreatedEngine;
  11782. if (!lastCreatedEngine) {
  11783. return null;
  11784. }
  11785. if (lastCreatedEngine.scenes.length === 0) {
  11786. return null;
  11787. }
  11788. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. /**
  11794. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11795. * @param flag defines which part of the materials must be marked as dirty
  11796. * @param predicate defines a predicate used to filter which materials should be affected
  11797. */
  11798. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11799. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11800. var engine = Engine.Instances[engineIndex];
  11801. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11802. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11803. }
  11804. }
  11805. };
  11806. Object.defineProperty(Engine, "NEVER", {
  11807. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11808. get: function () {
  11809. return Engine._NEVER;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(Engine, "ALWAYS", {
  11815. /** 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 */
  11816. get: function () {
  11817. return Engine._ALWAYS;
  11818. },
  11819. enumerable: true,
  11820. configurable: true
  11821. });
  11822. Object.defineProperty(Engine, "LESS", {
  11823. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11824. get: function () {
  11825. return Engine._LESS;
  11826. },
  11827. enumerable: true,
  11828. configurable: true
  11829. });
  11830. Object.defineProperty(Engine, "EQUAL", {
  11831. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11832. get: function () {
  11833. return Engine._EQUAL;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. Object.defineProperty(Engine, "LEQUAL", {
  11839. /** 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 */
  11840. get: function () {
  11841. return Engine._LEQUAL;
  11842. },
  11843. enumerable: true,
  11844. configurable: true
  11845. });
  11846. Object.defineProperty(Engine, "GREATER", {
  11847. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11848. get: function () {
  11849. return Engine._GREATER;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine, "GEQUAL", {
  11855. /** 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 */
  11856. get: function () {
  11857. return Engine._GEQUAL;
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(Engine, "NOTEQUAL", {
  11863. /** 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 */
  11864. get: function () {
  11865. return Engine._NOTEQUAL;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Engine, "KEEP", {
  11871. /** Passed to stencilOperation to specify that stencil value must be kept */
  11872. get: function () {
  11873. return Engine._KEEP;
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(Engine, "REPLACE", {
  11879. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11880. get: function () {
  11881. return Engine._REPLACE;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. Object.defineProperty(Engine, "INCR", {
  11887. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11888. get: function () {
  11889. return Engine._INCR;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine, "DECR", {
  11895. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11896. get: function () {
  11897. return Engine._DECR;
  11898. },
  11899. enumerable: true,
  11900. configurable: true
  11901. });
  11902. Object.defineProperty(Engine, "INVERT", {
  11903. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11904. get: function () {
  11905. return Engine._INVERT;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine, "INCR_WRAP", {
  11911. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11912. get: function () {
  11913. return Engine._INCR_WRAP;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. Object.defineProperty(Engine, "DECR_WRAP", {
  11919. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11920. get: function () {
  11921. return Engine._DECR_WRAP;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11927. // Alpha
  11928. /** Defines that alpha blending is disabled */
  11929. get: function () {
  11930. return Engine._ALPHA_DISABLE;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11936. /** Defines that alpha blending to SRC + DEST */
  11937. get: function () {
  11938. return Engine._ALPHA_ONEONE;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "ALPHA_ADD", {
  11944. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11945. get: function () {
  11946. return Engine._ALPHA_ADD;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11952. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11953. get: function () {
  11954. return Engine._ALPHA_COMBINE;
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11960. /** Defines that alpha blending to DEST - SRC * DEST */
  11961. get: function () {
  11962. return Engine._ALPHA_SUBTRACT;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11968. /** Defines that alpha blending to SRC * DEST */
  11969. get: function () {
  11970. return Engine._ALPHA_MULTIPLY;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11976. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11977. get: function () {
  11978. return Engine._ALPHA_MAXIMIZED;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11984. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11985. get: function () {
  11986. return Engine._ALPHA_PREMULTIPLIED;
  11987. },
  11988. enumerable: true,
  11989. configurable: true
  11990. });
  11991. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11992. /**
  11993. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11994. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11995. */
  11996. get: function () {
  11997. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  12003. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  12004. get: function () {
  12005. return Engine._ALPHA_INTERPOLATE;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  12011. /**
  12012. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  12013. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  12014. */
  12015. get: function () {
  12016. return Engine._ALPHA_SCREENMODE;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  12022. // Delays
  12023. /** Defines that the ressource is not delayed*/
  12024. get: function () {
  12025. return Engine._DELAYLOADSTATE_NONE;
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  12031. /** Defines that the ressource was successfully delay loaded */
  12032. get: function () {
  12033. return Engine._DELAYLOADSTATE_LOADED;
  12034. },
  12035. enumerable: true,
  12036. configurable: true
  12037. });
  12038. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  12039. /** Defines that the ressource is currently delay loading */
  12040. get: function () {
  12041. return Engine._DELAYLOADSTATE_LOADING;
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12047. /** Defines that the ressource is delayed and has not started loading */
  12048. get: function () {
  12049. return Engine._DELAYLOADSTATE_NOTLOADED;
  12050. },
  12051. enumerable: true,
  12052. configurable: true
  12053. });
  12054. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12055. /** ALPHA */
  12056. get: function () {
  12057. return Engine._TEXTUREFORMAT_ALPHA;
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12063. /** LUMINANCE */
  12064. get: function () {
  12065. return Engine._TEXTUREFORMAT_LUMINANCE;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12071. /**
  12072. * R
  12073. */
  12074. get: function () {
  12075. return Engine._TEXTUREFORMAT_R;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12081. /**
  12082. * RG
  12083. */
  12084. get: function () {
  12085. return Engine._TEXTUREFORMAT_RG;
  12086. },
  12087. enumerable: true,
  12088. configurable: true
  12089. });
  12090. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12091. /** LUMINANCE_ALPHA */
  12092. get: function () {
  12093. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12094. },
  12095. enumerable: true,
  12096. configurable: true
  12097. });
  12098. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12099. /** RGB */
  12100. get: function () {
  12101. return Engine._TEXTUREFORMAT_RGB;
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12107. /** RGBA */
  12108. get: function () {
  12109. return Engine._TEXTUREFORMAT_RGBA;
  12110. },
  12111. enumerable: true,
  12112. configurable: true
  12113. });
  12114. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12115. /** UNSIGNED_INT */
  12116. get: function () {
  12117. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12123. /** FLOAT */
  12124. get: function () {
  12125. return Engine._TEXTURETYPE_FLOAT;
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12131. /** HALF_FLOAT */
  12132. get: function () {
  12133. return Engine._TEXTURETYPE_HALF_FLOAT;
  12134. },
  12135. enumerable: true,
  12136. configurable: true
  12137. });
  12138. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12139. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12140. get: function () {
  12141. return Engine._SCALEMODE_FLOOR;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12147. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12148. get: function () {
  12149. return Engine._SCALEMODE_NEAREST;
  12150. },
  12151. enumerable: true,
  12152. configurable: true
  12153. });
  12154. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12155. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12156. get: function () {
  12157. return Engine._SCALEMODE_CEILING;
  12158. },
  12159. enumerable: true,
  12160. configurable: true
  12161. });
  12162. Object.defineProperty(Engine, "Version", {
  12163. /**
  12164. * Returns the current version of the framework
  12165. */
  12166. get: function () {
  12167. return "3.3.0-alpha.8";
  12168. },
  12169. enumerable: true,
  12170. configurable: true
  12171. });
  12172. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12173. /**
  12174. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12175. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12176. */
  12177. get: function () {
  12178. return this._vrExclusivePointerMode;
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12184. /**
  12185. * Gets a boolean indicating that the engine supports uniform buffers
  12186. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12187. */
  12188. get: function () {
  12189. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12195. /**
  12196. * Gets a boolean indicating that only power of 2 textures are supported
  12197. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12198. */
  12199. get: function () {
  12200. return this._webGLVersion < 2 || this.forcePOTTextures;
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12206. /**
  12207. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12208. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12209. */
  12210. get: function () {
  12211. return this._doNotHandleContextLost;
  12212. },
  12213. set: function (value) {
  12214. this._doNotHandleContextLost = value;
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12220. /**
  12221. * Gets the performance monitor attached to this engine
  12222. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12223. */
  12224. get: function () {
  12225. return this._performanceMonitor;
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12231. /**
  12232. * Gets the list of texture formats supported
  12233. */
  12234. get: function () {
  12235. return this._texturesSupported;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12241. /**
  12242. * Gets the list of texture formats in use
  12243. */
  12244. get: function () {
  12245. return this._textureFormatInUse;
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(Engine.prototype, "currentViewport", {
  12251. /**
  12252. * Gets the current viewport
  12253. */
  12254. get: function () {
  12255. return this._cachedViewport;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12261. /**
  12262. * Gets the default empty texture
  12263. */
  12264. get: function () {
  12265. if (!this._emptyTexture) {
  12266. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12267. }
  12268. return this._emptyTexture;
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12274. /**
  12275. * Gets the default empty 3D texture
  12276. */
  12277. get: function () {
  12278. if (!this._emptyTexture3D) {
  12279. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12280. }
  12281. return this._emptyTexture3D;
  12282. },
  12283. enumerable: true,
  12284. configurable: true
  12285. });
  12286. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12287. /**
  12288. * Gets the default empty cube texture
  12289. */
  12290. get: function () {
  12291. if (!this._emptyCubeTexture) {
  12292. var faceData = new Uint8Array(4);
  12293. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12294. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12295. }
  12296. return this._emptyCubeTexture;
  12297. },
  12298. enumerable: true,
  12299. configurable: true
  12300. });
  12301. Engine.prototype._rebuildInternalTextures = function () {
  12302. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12303. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12304. var internalTexture = currentState_1[_i];
  12305. internalTexture._rebuild();
  12306. }
  12307. };
  12308. Engine.prototype._rebuildEffects = function () {
  12309. for (var key in this._compiledEffects) {
  12310. var effect = this._compiledEffects[key];
  12311. effect._prepareEffect();
  12312. }
  12313. BABYLON.Effect.ResetCache();
  12314. };
  12315. Engine.prototype._rebuildBuffers = function () {
  12316. // Index / Vertex
  12317. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12318. var scene = _a[_i];
  12319. scene.resetCachedMaterial();
  12320. scene._rebuildGeometries();
  12321. scene._rebuildTextures();
  12322. }
  12323. // Uniforms
  12324. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12325. var uniformBuffer = _c[_b];
  12326. uniformBuffer._rebuild();
  12327. }
  12328. };
  12329. Engine.prototype._initGLContext = function () {
  12330. // Caps
  12331. this._caps = new EngineCapabilities();
  12332. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12333. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12334. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12335. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12336. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12337. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12338. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12339. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12340. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12341. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12342. // Infos
  12343. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12344. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12345. if (rendererInfo != null) {
  12346. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12347. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12348. }
  12349. if (!this._glVendor) {
  12350. this._glVendor = "Unknown vendor";
  12351. }
  12352. if (!this._glRenderer) {
  12353. this._glRenderer = "Unknown renderer";
  12354. }
  12355. // Constants
  12356. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12357. if (this._gl.RGBA16F !== 0x881A) {
  12358. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12359. }
  12360. if (this._gl.RGBA32F !== 0x8814) {
  12361. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12362. }
  12363. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12364. this._gl.DEPTH24_STENCIL8 = 35056;
  12365. }
  12366. // Extensions
  12367. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12368. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12369. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12370. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12371. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12372. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12373. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12374. 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');
  12375. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12376. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12377. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12378. this._caps.highPrecisionShaderSupported = true;
  12379. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12380. if (this._caps.timerQuery) {
  12381. if (this._webGLVersion === 1) {
  12382. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12383. }
  12384. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12385. }
  12386. // Checks if some of the format renders first to allow the use of webgl inspector.
  12387. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12388. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12389. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12390. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12391. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12392. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12393. if (this._webGLVersion > 1) {
  12394. this._gl.HALF_FLOAT_OES = 0x140B;
  12395. }
  12396. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12397. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12398. // Draw buffers
  12399. if (this._webGLVersion > 1) {
  12400. this._caps.drawBuffersExtension = true;
  12401. }
  12402. else {
  12403. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12404. if (drawBuffersExtension !== null) {
  12405. this._caps.drawBuffersExtension = true;
  12406. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12407. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12408. for (var i = 0; i < 16; i++) {
  12409. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12410. }
  12411. }
  12412. else {
  12413. this._caps.drawBuffersExtension = false;
  12414. }
  12415. }
  12416. // Depth Texture
  12417. if (this._webGLVersion > 1) {
  12418. this._caps.depthTextureExtension = true;
  12419. }
  12420. else {
  12421. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12422. if (depthTextureExtension != null) {
  12423. this._caps.depthTextureExtension = true;
  12424. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12425. }
  12426. }
  12427. // Vertex array object
  12428. if (this._webGLVersion > 1) {
  12429. this._caps.vertexArrayObject = true;
  12430. }
  12431. else {
  12432. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12433. if (vertexArrayObjectExtension != null) {
  12434. this._caps.vertexArrayObject = true;
  12435. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12436. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12437. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12438. }
  12439. else {
  12440. this._caps.vertexArrayObject = false;
  12441. }
  12442. }
  12443. // Instances count
  12444. if (this._webGLVersion > 1) {
  12445. this._caps.instancedArrays = true;
  12446. }
  12447. else {
  12448. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12449. if (instanceExtension != null) {
  12450. this._caps.instancedArrays = true;
  12451. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12452. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12453. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12454. }
  12455. else {
  12456. this._caps.instancedArrays = false;
  12457. }
  12458. }
  12459. // Intelligently add supported compressed formats in order to check for.
  12460. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12461. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12462. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12463. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12464. if (this._caps.astc)
  12465. this.texturesSupported.push('-astc.ktx');
  12466. if (this._caps.s3tc)
  12467. this.texturesSupported.push('-dxt.ktx');
  12468. if (this._caps.pvrtc)
  12469. this.texturesSupported.push('-pvrtc.ktx');
  12470. if (this._caps.etc2)
  12471. this.texturesSupported.push('-etc2.ktx');
  12472. if (this._caps.etc1)
  12473. this.texturesSupported.push('-etc1.ktx');
  12474. if (this._gl.getShaderPrecisionFormat) {
  12475. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12476. if (highp) {
  12477. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12478. }
  12479. }
  12480. // Depth buffer
  12481. this.setDepthBuffer(true);
  12482. this.setDepthFunctionToLessOrEqual();
  12483. this.setDepthWrite(true);
  12484. // Texture maps
  12485. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12486. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12487. this._nextFreeTextureSlots.push(slot);
  12488. }
  12489. };
  12490. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12491. /**
  12492. * Gets version of the current webGL context
  12493. */
  12494. get: function () {
  12495. return this._webGLVersion;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12501. /**
  12502. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12503. */
  12504. get: function () {
  12505. return this._isStencilEnable;
  12506. },
  12507. enumerable: true,
  12508. configurable: true
  12509. });
  12510. Engine.prototype._prepareWorkingCanvas = function () {
  12511. if (this._workingCanvas) {
  12512. return;
  12513. }
  12514. this._workingCanvas = document.createElement("canvas");
  12515. var context = this._workingCanvas.getContext("2d");
  12516. if (context) {
  12517. this._workingContext = context;
  12518. }
  12519. };
  12520. /**
  12521. * Reset the texture cache to empty state
  12522. */
  12523. Engine.prototype.resetTextureCache = function () {
  12524. for (var key in this._boundTexturesCache) {
  12525. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12526. continue;
  12527. }
  12528. var boundTexture = this._boundTexturesCache[key];
  12529. if (boundTexture) {
  12530. this._removeDesignatedSlot(boundTexture);
  12531. }
  12532. this._boundTexturesCache[key] = null;
  12533. }
  12534. if (!this.disableTextureBindingOptimization) {
  12535. this._nextFreeTextureSlots = [];
  12536. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12537. this._nextFreeTextureSlots.push(slot);
  12538. }
  12539. }
  12540. this._currentTextureChannel = -1;
  12541. };
  12542. /**
  12543. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12544. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12545. * @returns true if engine is in deterministic lock step mode
  12546. */
  12547. Engine.prototype.isDeterministicLockStep = function () {
  12548. return this._deterministicLockstep;
  12549. };
  12550. /**
  12551. * Gets the max steps when engine is running in deterministic lock step
  12552. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12553. * @returns the max steps
  12554. */
  12555. Engine.prototype.getLockstepMaxSteps = function () {
  12556. return this._lockstepMaxSteps;
  12557. };
  12558. /**
  12559. * Gets an object containing information about the current webGL context
  12560. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12561. */
  12562. Engine.prototype.getGlInfo = function () {
  12563. return {
  12564. vendor: this._glVendor,
  12565. renderer: this._glRenderer,
  12566. version: this._glVersion
  12567. };
  12568. };
  12569. /**
  12570. * Gets current aspect ratio
  12571. * @param camera defines the camera to use to get the aspect ratio
  12572. * @param useScreen defines if screen size must be used (or the current render target if any)
  12573. * @returns a number defining the aspect ratio
  12574. */
  12575. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12576. if (useScreen === void 0) { useScreen = false; }
  12577. var viewport = camera.viewport;
  12578. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12579. };
  12580. /**
  12581. * Gets current screen aspect ratio
  12582. * @returns a number defining the aspect ratio
  12583. */
  12584. Engine.prototype.getScreenAspectRatio = function () {
  12585. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12586. };
  12587. /**
  12588. * Gets the current render width
  12589. * @param useScreen defines if screen size must be used (or the current render target if any)
  12590. * @returns a number defining the current render width
  12591. */
  12592. Engine.prototype.getRenderWidth = function (useScreen) {
  12593. if (useScreen === void 0) { useScreen = false; }
  12594. if (!useScreen && this._currentRenderTarget) {
  12595. return this._currentRenderTarget.width;
  12596. }
  12597. return this._gl.drawingBufferWidth;
  12598. };
  12599. /**
  12600. * Gets the current render height
  12601. * @param useScreen defines if screen size must be used (or the current render target if any)
  12602. * @returns a number defining the current render height
  12603. */
  12604. Engine.prototype.getRenderHeight = function (useScreen) {
  12605. if (useScreen === void 0) { useScreen = false; }
  12606. if (!useScreen && this._currentRenderTarget) {
  12607. return this._currentRenderTarget.height;
  12608. }
  12609. return this._gl.drawingBufferHeight;
  12610. };
  12611. /**
  12612. * Gets the HTML canvas attached with the current webGL context
  12613. * @returns a HTML canvas
  12614. */
  12615. Engine.prototype.getRenderingCanvas = function () {
  12616. return this._renderingCanvas;
  12617. };
  12618. /**
  12619. * Gets the client rect of the HTML canvas attached with the current webGL context
  12620. * @returns a client rectanglee
  12621. */
  12622. Engine.prototype.getRenderingCanvasClientRect = function () {
  12623. if (!this._renderingCanvas) {
  12624. return null;
  12625. }
  12626. return this._renderingCanvas.getBoundingClientRect();
  12627. };
  12628. /**
  12629. * Defines the hardware scaling level.
  12630. * By default the hardware scaling level is computed from the window device ratio.
  12631. * 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.
  12632. * @param level defines the level to use
  12633. */
  12634. Engine.prototype.setHardwareScalingLevel = function (level) {
  12635. this._hardwareScalingLevel = level;
  12636. this.resize();
  12637. };
  12638. /**
  12639. * Gets the current hardware scaling level.
  12640. * By default the hardware scaling level is computed from the window device ratio.
  12641. * 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.
  12642. * @returns a number indicating the current hardware scaling level
  12643. */
  12644. Engine.prototype.getHardwareScalingLevel = function () {
  12645. return this._hardwareScalingLevel;
  12646. };
  12647. /**
  12648. * Gets the list of loaded textures
  12649. * @returns an array containing all loaded textures
  12650. */
  12651. Engine.prototype.getLoadedTexturesCache = function () {
  12652. return this._internalTexturesCache;
  12653. };
  12654. /**
  12655. * Gets the object containing all engine capabilities
  12656. * @returns the EngineCapabilities object
  12657. */
  12658. Engine.prototype.getCaps = function () {
  12659. return this._caps;
  12660. };
  12661. Object.defineProperty(Engine.prototype, "drawCalls", {
  12662. /** @hidden */
  12663. get: function () {
  12664. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12665. return 0;
  12666. },
  12667. enumerable: true,
  12668. configurable: true
  12669. });
  12670. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12671. /** @hidden */
  12672. get: function () {
  12673. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12674. return null;
  12675. },
  12676. enumerable: true,
  12677. configurable: true
  12678. });
  12679. /**
  12680. * Gets the current depth function
  12681. * @returns a number defining the depth function
  12682. */
  12683. Engine.prototype.getDepthFunction = function () {
  12684. return this._depthCullingState.depthFunc;
  12685. };
  12686. /**
  12687. * Sets the current depth function
  12688. * @param depthFunc defines the function to use
  12689. */
  12690. Engine.prototype.setDepthFunction = function (depthFunc) {
  12691. this._depthCullingState.depthFunc = depthFunc;
  12692. };
  12693. /**
  12694. * Sets the current depth function to GREATER
  12695. */
  12696. Engine.prototype.setDepthFunctionToGreater = function () {
  12697. this._depthCullingState.depthFunc = this._gl.GREATER;
  12698. };
  12699. /**
  12700. * Sets the current depth function to GEQUAL
  12701. */
  12702. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12703. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12704. };
  12705. /**
  12706. * Sets the current depth function to LESS
  12707. */
  12708. Engine.prototype.setDepthFunctionToLess = function () {
  12709. this._depthCullingState.depthFunc = this._gl.LESS;
  12710. };
  12711. /**
  12712. * Sets the current depth function to LEQUAL
  12713. */
  12714. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12715. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12716. };
  12717. /**
  12718. * Gets a boolean indicating if stencil buffer is enabled
  12719. * @returns the current stencil buffer state
  12720. */
  12721. Engine.prototype.getStencilBuffer = function () {
  12722. return this._stencilState.stencilTest;
  12723. };
  12724. /**
  12725. * Enable or disable the stencil buffer
  12726. * @param enable defines if the stencil buffer must be enabled or disabled
  12727. */
  12728. Engine.prototype.setStencilBuffer = function (enable) {
  12729. this._stencilState.stencilTest = enable;
  12730. };
  12731. /**
  12732. * Gets the current stencil mask
  12733. * @returns a number defining the new stencil mask to use
  12734. */
  12735. Engine.prototype.getStencilMask = function () {
  12736. return this._stencilState.stencilMask;
  12737. };
  12738. /**
  12739. * Sets the current stencil mask
  12740. * @param mask defines the new stencil mask to use
  12741. */
  12742. Engine.prototype.setStencilMask = function (mask) {
  12743. this._stencilState.stencilMask = mask;
  12744. };
  12745. /**
  12746. * Gets the current stencil function
  12747. * @returns a number defining the stencil function to use
  12748. */
  12749. Engine.prototype.getStencilFunction = function () {
  12750. return this._stencilState.stencilFunc;
  12751. };
  12752. /**
  12753. * Gets the current stencil reference value
  12754. * @returns a number defining the stencil reference value to use
  12755. */
  12756. Engine.prototype.getStencilFunctionReference = function () {
  12757. return this._stencilState.stencilFuncRef;
  12758. };
  12759. /**
  12760. * Gets the current stencil mask
  12761. * @returns a number defining the stencil mask to use
  12762. */
  12763. Engine.prototype.getStencilFunctionMask = function () {
  12764. return this._stencilState.stencilFuncMask;
  12765. };
  12766. /**
  12767. * Sets the current stencil function
  12768. * @param stencilFunc defines the new stencil function to use
  12769. */
  12770. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12771. this._stencilState.stencilFunc = stencilFunc;
  12772. };
  12773. /**
  12774. * Sets the current stencil reference
  12775. * @param reference defines the new stencil reference to use
  12776. */
  12777. Engine.prototype.setStencilFunctionReference = function (reference) {
  12778. this._stencilState.stencilFuncRef = reference;
  12779. };
  12780. /**
  12781. * Sets the current stencil mask
  12782. * @param mask defines the new stencil mask to use
  12783. */
  12784. Engine.prototype.setStencilFunctionMask = function (mask) {
  12785. this._stencilState.stencilFuncMask = mask;
  12786. };
  12787. /**
  12788. * Gets the current stencil operation when stencil fails
  12789. * @returns a number defining stencil operation to use when stencil fails
  12790. */
  12791. Engine.prototype.getStencilOperationFail = function () {
  12792. return this._stencilState.stencilOpStencilFail;
  12793. };
  12794. /**
  12795. * Gets the current stencil operation when depth fails
  12796. * @returns a number defining stencil operation to use when depth fails
  12797. */
  12798. Engine.prototype.getStencilOperationDepthFail = function () {
  12799. return this._stencilState.stencilOpDepthFail;
  12800. };
  12801. /**
  12802. * Gets the current stencil operation when stencil passes
  12803. * @returns a number defining stencil operation to use when stencil passes
  12804. */
  12805. Engine.prototype.getStencilOperationPass = function () {
  12806. return this._stencilState.stencilOpStencilDepthPass;
  12807. };
  12808. /**
  12809. * Sets the stencil operation to use when stencil fails
  12810. * @param operation defines the stencil operation to use when stencil fails
  12811. */
  12812. Engine.prototype.setStencilOperationFail = function (operation) {
  12813. this._stencilState.stencilOpStencilFail = operation;
  12814. };
  12815. /**
  12816. * Sets the stencil operation to use when depth fails
  12817. * @param operation defines the stencil operation to use when depth fails
  12818. */
  12819. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12820. this._stencilState.stencilOpDepthFail = operation;
  12821. };
  12822. /**
  12823. * Sets the stencil operation to use when stencil passes
  12824. * @param operation defines the stencil operation to use when stencil passes
  12825. */
  12826. Engine.prototype.setStencilOperationPass = function (operation) {
  12827. this._stencilState.stencilOpStencilDepthPass = operation;
  12828. };
  12829. /**
  12830. * Sets a boolean indicating if the dithering state is enabled or disabled
  12831. * @param value defines the dithering state
  12832. */
  12833. Engine.prototype.setDitheringState = function (value) {
  12834. if (value) {
  12835. this._gl.enable(this._gl.DITHER);
  12836. }
  12837. else {
  12838. this._gl.disable(this._gl.DITHER);
  12839. }
  12840. };
  12841. /**
  12842. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12843. * @param value defines the rasterizer state
  12844. */
  12845. Engine.prototype.setRasterizerState = function (value) {
  12846. if (value) {
  12847. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12848. }
  12849. else {
  12850. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12851. }
  12852. };
  12853. /**
  12854. * stop executing a render loop function and remove it from the execution array
  12855. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12856. */
  12857. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12858. if (!renderFunction) {
  12859. this._activeRenderLoops = [];
  12860. return;
  12861. }
  12862. var index = this._activeRenderLoops.indexOf(renderFunction);
  12863. if (index >= 0) {
  12864. this._activeRenderLoops.splice(index, 1);
  12865. }
  12866. };
  12867. /** @hidden */
  12868. Engine.prototype._renderLoop = function () {
  12869. if (!this._contextWasLost) {
  12870. var shouldRender = true;
  12871. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12872. shouldRender = false;
  12873. }
  12874. if (shouldRender) {
  12875. // Start new frame
  12876. this.beginFrame();
  12877. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12878. var renderFunction = this._activeRenderLoops[index];
  12879. renderFunction();
  12880. }
  12881. // Present
  12882. this.endFrame();
  12883. }
  12884. }
  12885. if (this._activeRenderLoops.length > 0) {
  12886. // Register new frame
  12887. var requester = null;
  12888. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12889. requester = this._vrDisplay;
  12890. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12891. }
  12892. else {
  12893. this._renderingQueueLaunched = false;
  12894. }
  12895. };
  12896. /**
  12897. * Register and execute a render loop. The engine can have more than one render function
  12898. * @param renderFunction defines the function to continuously execute
  12899. */
  12900. Engine.prototype.runRenderLoop = function (renderFunction) {
  12901. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12902. return;
  12903. }
  12904. this._activeRenderLoops.push(renderFunction);
  12905. if (!this._renderingQueueLaunched) {
  12906. this._renderingQueueLaunched = true;
  12907. this._bindedRenderFunction = this._renderLoop.bind(this);
  12908. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12909. }
  12910. };
  12911. /**
  12912. * Toggle full screen mode
  12913. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12914. * @param options defines an option object to be sent to the requestFullscreen function
  12915. */
  12916. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12917. if (this.isFullscreen) {
  12918. BABYLON.Tools.ExitFullscreen();
  12919. }
  12920. else {
  12921. this._pointerLockRequested = requestPointerLock;
  12922. if (this._renderingCanvas) {
  12923. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12924. }
  12925. }
  12926. };
  12927. /**
  12928. * Clear the current render buffer or the current render target (if any is set up)
  12929. * @param color defines the color to use
  12930. * @param backBuffer defines if the back buffer must be cleared
  12931. * @param depth defines if the depth buffer must be cleared
  12932. * @param stencil defines if the stencil buffer must be cleared
  12933. */
  12934. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12935. if (stencil === void 0) { stencil = false; }
  12936. this.applyStates();
  12937. var mode = 0;
  12938. if (backBuffer && color) {
  12939. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12940. mode |= this._gl.COLOR_BUFFER_BIT;
  12941. }
  12942. if (depth) {
  12943. this._gl.clearDepth(1.0);
  12944. mode |= this._gl.DEPTH_BUFFER_BIT;
  12945. }
  12946. if (stencil) {
  12947. this._gl.clearStencil(0);
  12948. mode |= this._gl.STENCIL_BUFFER_BIT;
  12949. }
  12950. this._gl.clear(mode);
  12951. };
  12952. /**
  12953. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12954. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12955. * @param y defines the y-coordinate of the corner of the clear rectangle
  12956. * @param width defines the width of the clear rectangle
  12957. * @param height defines the height of the clear rectangle
  12958. * @param clearColor defines the clear color
  12959. */
  12960. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12961. var gl = this._gl;
  12962. // Save state
  12963. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12964. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12965. // Change state
  12966. gl.enable(gl.SCISSOR_TEST);
  12967. gl.scissor(x, y, width, height);
  12968. // Clear
  12969. this.clear(clearColor, true, true, true);
  12970. // Restore state
  12971. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12972. if (curScissor === true) {
  12973. gl.enable(gl.SCISSOR_TEST);
  12974. }
  12975. else {
  12976. gl.disable(gl.SCISSOR_TEST);
  12977. }
  12978. };
  12979. /** @hidden */
  12980. Engine.prototype._viewport = function (x, y, width, height) {
  12981. if (x !== this._viewportCached.x ||
  12982. y !== this._viewportCached.y ||
  12983. width !== this._viewportCached.z ||
  12984. height !== this._viewportCached.w) {
  12985. this._viewportCached.x = x;
  12986. this._viewportCached.y = y;
  12987. this._viewportCached.z = width;
  12988. this._viewportCached.w = height;
  12989. this._gl.viewport(x, y, width, height);
  12990. }
  12991. };
  12992. /**
  12993. * Set the WebGL's viewport
  12994. * @param viewport defines the viewport element to be used
  12995. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12996. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12997. */
  12998. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12999. var width = requiredWidth || this.getRenderWidth();
  13000. var height = requiredHeight || this.getRenderHeight();
  13001. var x = viewport.x || 0;
  13002. var y = viewport.y || 0;
  13003. this._cachedViewport = viewport;
  13004. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13005. };
  13006. /**
  13007. * Directly set the WebGL Viewport
  13008. * @param x defines the x coordinate of the viewport (in screen space)
  13009. * @param y defines the y coordinate of the viewport (in screen space)
  13010. * @param width defines the width of the viewport (in screen space)
  13011. * @param height defines the height of the viewport (in screen space)
  13012. * @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
  13013. */
  13014. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13015. var currentViewport = this._cachedViewport;
  13016. this._cachedViewport = null;
  13017. this._viewport(x, y, width, height);
  13018. return currentViewport;
  13019. };
  13020. /**
  13021. * Begin a new frame
  13022. */
  13023. Engine.prototype.beginFrame = function () {
  13024. this.onBeginFrameObservable.notifyObservers(this);
  13025. this._measureFps();
  13026. };
  13027. /**
  13028. * Enf the current frame
  13029. */
  13030. Engine.prototype.endFrame = function () {
  13031. // Force a flush in case we are using a bad OS.
  13032. if (this._badOS) {
  13033. this.flushFramebuffer();
  13034. }
  13035. // Submit frame to the vr device, if enabled
  13036. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13037. // TODO: We should only submit the frame if we read frameData successfully.
  13038. this._vrDisplay.submitFrame();
  13039. }
  13040. this.onEndFrameObservable.notifyObservers(this);
  13041. };
  13042. /**
  13043. * Resize the view according to the canvas' size
  13044. */
  13045. Engine.prototype.resize = function () {
  13046. // We're not resizing the size of the canvas while in VR mode & presenting
  13047. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13048. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13049. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13050. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13051. }
  13052. };
  13053. /**
  13054. * Force a specific size of the canvas
  13055. * @param width defines the new canvas' width
  13056. * @param height defines the new canvas' height
  13057. */
  13058. Engine.prototype.setSize = function (width, height) {
  13059. if (!this._renderingCanvas) {
  13060. return;
  13061. }
  13062. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13063. return;
  13064. }
  13065. this._renderingCanvas.width = width;
  13066. this._renderingCanvas.height = height;
  13067. for (var index = 0; index < this.scenes.length; index++) {
  13068. var scene = this.scenes[index];
  13069. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13070. var cam = scene.cameras[camIndex];
  13071. cam._currentRenderId = 0;
  13072. }
  13073. }
  13074. if (this.onResizeObservable.hasObservers) {
  13075. this.onResizeObservable.notifyObservers(this);
  13076. }
  13077. };
  13078. // WebVR functions
  13079. /**
  13080. * Gets a boolean indicating if a webVR device was detected
  13081. * @returns true if a webVR device was detected
  13082. */
  13083. Engine.prototype.isVRDevicePresent = function () {
  13084. return !!this._vrDisplay;
  13085. };
  13086. /**
  13087. * Gets the current webVR device
  13088. * @returns the current webVR device (or null)
  13089. */
  13090. Engine.prototype.getVRDevice = function () {
  13091. return this._vrDisplay;
  13092. };
  13093. /**
  13094. * Initializes a webVR display and starts listening to display change events
  13095. * The onVRDisplayChangedObservable will be notified upon these changes
  13096. * @returns The onVRDisplayChangedObservable
  13097. */
  13098. Engine.prototype.initWebVR = function () {
  13099. this.initWebVRAsync();
  13100. return this.onVRDisplayChangedObservable;
  13101. };
  13102. /**
  13103. * Initializes a webVR display and starts listening to display change events
  13104. * The onVRDisplayChangedObservable will be notified upon these changes
  13105. * @returns A promise containing a VRDisplay and if vr is supported
  13106. */
  13107. Engine.prototype.initWebVRAsync = function () {
  13108. var _this = this;
  13109. var notifyObservers = function () {
  13110. var eventArgs = {
  13111. vrDisplay: _this._vrDisplay,
  13112. vrSupported: _this._vrSupported
  13113. };
  13114. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13115. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13116. };
  13117. if (!this._onVrDisplayConnect) {
  13118. this._onVrDisplayConnect = function (event) {
  13119. _this._vrDisplay = event.display;
  13120. notifyObservers();
  13121. };
  13122. this._onVrDisplayDisconnect = function () {
  13123. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13124. _this._vrDisplay = undefined;
  13125. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13126. notifyObservers();
  13127. };
  13128. this._onVrDisplayPresentChange = function () {
  13129. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13130. };
  13131. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13132. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13133. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13134. }
  13135. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13136. this._webVRInitPromise.then(notifyObservers);
  13137. return this._webVRInitPromise;
  13138. };
  13139. /**
  13140. * Call this function to switch to webVR mode
  13141. * Will do nothing if webVR is not supported or if there is no webVR device
  13142. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13143. */
  13144. Engine.prototype.enableVR = function () {
  13145. var _this = this;
  13146. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13147. var onResolved = function () {
  13148. _this.onVRRequestPresentComplete.notifyObservers(true);
  13149. _this._onVRFullScreenTriggered();
  13150. };
  13151. var onRejected = function () {
  13152. _this.onVRRequestPresentComplete.notifyObservers(false);
  13153. };
  13154. this.onVRRequestPresentStart.notifyObservers(this);
  13155. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13156. }
  13157. };
  13158. /**
  13159. * Call this function to leave webVR mode
  13160. * Will do nothing if webVR is not supported or if there is no webVR device
  13161. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13162. */
  13163. Engine.prototype.disableVR = function () {
  13164. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13165. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13166. }
  13167. };
  13168. Engine.prototype._getVRDisplaysAsync = function () {
  13169. var _this = this;
  13170. return new Promise(function (res, rej) {
  13171. if (navigator.getVRDisplays) {
  13172. navigator.getVRDisplays().then(function (devices) {
  13173. _this._vrSupported = true;
  13174. // note that devices may actually be an empty array. This is fine;
  13175. // we expect this._vrDisplay to be undefined in this case.
  13176. _this._vrDisplay = devices[0];
  13177. res({
  13178. vrDisplay: _this._vrDisplay,
  13179. vrSupported: _this._vrSupported
  13180. });
  13181. });
  13182. }
  13183. else {
  13184. _this._vrDisplay = undefined;
  13185. _this._vrSupported = false;
  13186. res({
  13187. vrDisplay: _this._vrDisplay,
  13188. vrSupported: _this._vrSupported
  13189. });
  13190. }
  13191. });
  13192. };
  13193. /**
  13194. * Binds the frame buffer to the specified texture.
  13195. * @param texture The texture to render to or null for the default canvas
  13196. * @param faceIndex The face of the texture to render to in case of cube texture
  13197. * @param requiredWidth The width of the target to render to
  13198. * @param requiredHeight The height of the target to render to
  13199. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13200. * @param depthStencilTexture The depth stencil texture to use to render
  13201. * @param lodLevel defines le lod level to bind to the frame buffer
  13202. */
  13203. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13204. if (lodLevel === void 0) { lodLevel = 0; }
  13205. if (this._currentRenderTarget) {
  13206. this.unBindFramebuffer(this._currentRenderTarget);
  13207. }
  13208. this._currentRenderTarget = texture;
  13209. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13210. var gl = this._gl;
  13211. if (texture.isCube) {
  13212. if (faceIndex === undefined) {
  13213. faceIndex = 0;
  13214. }
  13215. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13216. if (depthStencilTexture) {
  13217. if (depthStencilTexture._generateStencilBuffer) {
  13218. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13219. }
  13220. else {
  13221. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13222. }
  13223. }
  13224. }
  13225. if (this._cachedViewport && !forceFullscreenViewport) {
  13226. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13227. }
  13228. else {
  13229. if (!requiredWidth) {
  13230. requiredWidth = texture.width;
  13231. if (lodLevel) {
  13232. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13233. }
  13234. }
  13235. if (!requiredHeight) {
  13236. requiredHeight = texture.height;
  13237. if (lodLevel) {
  13238. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13239. }
  13240. }
  13241. this._viewport(0, 0, requiredWidth, requiredHeight);
  13242. }
  13243. this.wipeCaches();
  13244. };
  13245. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13246. if (this._currentFramebuffer !== framebuffer) {
  13247. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13248. this._currentFramebuffer = framebuffer;
  13249. }
  13250. };
  13251. /**
  13252. * Unbind the current render target texture from the webGL context
  13253. * @param texture defines the render target texture to unbind
  13254. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13255. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13256. */
  13257. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13258. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13259. this._currentRenderTarget = null;
  13260. // If MSAA, we need to bitblt back to main texture
  13261. var gl = this._gl;
  13262. if (texture._MSAAFramebuffer) {
  13263. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13264. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13265. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13266. }
  13267. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13268. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13269. gl.generateMipmap(gl.TEXTURE_2D);
  13270. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13271. }
  13272. if (onBeforeUnbind) {
  13273. if (texture._MSAAFramebuffer) {
  13274. // Bind the correct framebuffer
  13275. this.bindUnboundFramebuffer(texture._framebuffer);
  13276. }
  13277. onBeforeUnbind();
  13278. }
  13279. this.bindUnboundFramebuffer(null);
  13280. };
  13281. /**
  13282. * Unbind a list of render target textures from the webGL context
  13283. * This is used only when drawBuffer extension or webGL2 are active
  13284. * @param textures defines the render target textures to unbind
  13285. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13286. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13287. */
  13288. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13289. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13290. this._currentRenderTarget = null;
  13291. // If MSAA, we need to bitblt back to main texture
  13292. var gl = this._gl;
  13293. if (textures[0]._MSAAFramebuffer) {
  13294. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13295. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13296. var attachments = textures[0]._attachments;
  13297. if (!attachments) {
  13298. attachments = new Array(textures.length);
  13299. textures[0]._attachments = attachments;
  13300. }
  13301. for (var i = 0; i < textures.length; i++) {
  13302. var texture = textures[i];
  13303. for (var j = 0; j < attachments.length; j++) {
  13304. attachments[j] = gl.NONE;
  13305. }
  13306. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13307. gl.readBuffer(attachments[i]);
  13308. gl.drawBuffers(attachments);
  13309. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13310. }
  13311. for (var i = 0; i < attachments.length; i++) {
  13312. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13313. }
  13314. gl.drawBuffers(attachments);
  13315. }
  13316. for (var i = 0; i < textures.length; i++) {
  13317. var texture = textures[i];
  13318. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13319. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13320. gl.generateMipmap(gl.TEXTURE_2D);
  13321. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13322. }
  13323. }
  13324. if (onBeforeUnbind) {
  13325. if (textures[0]._MSAAFramebuffer) {
  13326. // Bind the correct framebuffer
  13327. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13328. }
  13329. onBeforeUnbind();
  13330. }
  13331. this.bindUnboundFramebuffer(null);
  13332. };
  13333. /**
  13334. * Force the mipmap generation for the given render target texture
  13335. * @param texture defines the render target texture to use
  13336. */
  13337. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13338. if (texture.generateMipMaps) {
  13339. var gl = this._gl;
  13340. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13341. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13342. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13343. }
  13344. };
  13345. /**
  13346. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13347. */
  13348. Engine.prototype.flushFramebuffer = function () {
  13349. this._gl.flush();
  13350. };
  13351. /**
  13352. * Unbind the current render target and bind the default framebuffer
  13353. */
  13354. Engine.prototype.restoreDefaultFramebuffer = function () {
  13355. if (this._currentRenderTarget) {
  13356. this.unBindFramebuffer(this._currentRenderTarget);
  13357. }
  13358. else {
  13359. this.bindUnboundFramebuffer(null);
  13360. }
  13361. if (this._cachedViewport) {
  13362. this.setViewport(this._cachedViewport);
  13363. }
  13364. this.wipeCaches();
  13365. };
  13366. // UBOs
  13367. /**
  13368. * Create an uniform buffer
  13369. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13370. * @param elements defines the content of the uniform buffer
  13371. * @returns the webGL uniform buffer
  13372. */
  13373. Engine.prototype.createUniformBuffer = function (elements) {
  13374. var ubo = this._gl.createBuffer();
  13375. if (!ubo) {
  13376. throw new Error("Unable to create uniform buffer");
  13377. }
  13378. this.bindUniformBuffer(ubo);
  13379. if (elements instanceof Float32Array) {
  13380. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13381. }
  13382. else {
  13383. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13384. }
  13385. this.bindUniformBuffer(null);
  13386. ubo.references = 1;
  13387. return ubo;
  13388. };
  13389. /**
  13390. * Create a dynamic uniform buffer
  13391. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13392. * @param elements defines the content of the uniform buffer
  13393. * @returns the webGL uniform buffer
  13394. */
  13395. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13396. var ubo = this._gl.createBuffer();
  13397. if (!ubo) {
  13398. throw new Error("Unable to create dynamic uniform buffer");
  13399. }
  13400. this.bindUniformBuffer(ubo);
  13401. if (elements instanceof Float32Array) {
  13402. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13403. }
  13404. else {
  13405. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13406. }
  13407. this.bindUniformBuffer(null);
  13408. ubo.references = 1;
  13409. return ubo;
  13410. };
  13411. /**
  13412. * Update an existing uniform buffer
  13413. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13414. * @param uniformBuffer defines the target uniform buffer
  13415. * @param elements defines the content to update
  13416. * @param offset defines the offset in the uniform buffer where update should start
  13417. * @param count defines the size of the data to update
  13418. */
  13419. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13420. this.bindUniformBuffer(uniformBuffer);
  13421. if (offset === undefined) {
  13422. offset = 0;
  13423. }
  13424. if (count === undefined) {
  13425. if (elements instanceof Float32Array) {
  13426. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13427. }
  13428. else {
  13429. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13430. }
  13431. }
  13432. else {
  13433. if (elements instanceof Float32Array) {
  13434. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13435. }
  13436. else {
  13437. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13438. }
  13439. }
  13440. this.bindUniformBuffer(null);
  13441. };
  13442. // VBOs
  13443. Engine.prototype._resetVertexBufferBinding = function () {
  13444. this.bindArrayBuffer(null);
  13445. this._cachedVertexBuffers = null;
  13446. };
  13447. /**
  13448. * Creates a vertex buffer
  13449. * @param data the data for the vertex buffer
  13450. * @returns the new WebGL static buffer
  13451. */
  13452. Engine.prototype.createVertexBuffer = function (data) {
  13453. var vbo = this._gl.createBuffer();
  13454. if (!vbo) {
  13455. throw new Error("Unable to create vertex buffer");
  13456. }
  13457. this.bindArrayBuffer(vbo);
  13458. if (data instanceof Array) {
  13459. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13460. }
  13461. else {
  13462. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13463. }
  13464. this._resetVertexBufferBinding();
  13465. vbo.references = 1;
  13466. return vbo;
  13467. };
  13468. /**
  13469. * Creates a dynamic vertex buffer
  13470. * @param data the data for the dynamic vertex buffer
  13471. * @returns the new WebGL dynamic buffer
  13472. */
  13473. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13474. var vbo = this._gl.createBuffer();
  13475. if (!vbo) {
  13476. throw new Error("Unable to create dynamic vertex buffer");
  13477. }
  13478. this.bindArrayBuffer(vbo);
  13479. if (data instanceof Array) {
  13480. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13481. }
  13482. else {
  13483. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13484. }
  13485. this._resetVertexBufferBinding();
  13486. vbo.references = 1;
  13487. return vbo;
  13488. };
  13489. /**
  13490. * Update a dynamic index buffer
  13491. * @param indexBuffer defines the target index buffer
  13492. * @param indices defines the data to update
  13493. * @param offset defines the offset in the target index buffer where update should start
  13494. */
  13495. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13496. if (offset === void 0) { offset = 0; }
  13497. // Force cache update
  13498. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13499. this.bindIndexBuffer(indexBuffer);
  13500. var arrayBuffer;
  13501. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13502. arrayBuffer = indices;
  13503. }
  13504. else {
  13505. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13506. }
  13507. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13508. this._resetIndexBufferBinding();
  13509. };
  13510. /**
  13511. * Updates a dynamic vertex buffer.
  13512. * @param vertexBuffer the vertex buffer to update
  13513. * @param data the data used to update the vertex buffer
  13514. * @param byteOffset the byte offset of the data
  13515. * @param byteLength the byte length of the data
  13516. */
  13517. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13518. this.bindArrayBuffer(vertexBuffer);
  13519. if (byteOffset === undefined) {
  13520. byteOffset = 0;
  13521. }
  13522. if (byteLength === undefined) {
  13523. if (data instanceof Array) {
  13524. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13525. }
  13526. else {
  13527. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13528. }
  13529. }
  13530. else {
  13531. if (data instanceof Array) {
  13532. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13533. }
  13534. else {
  13535. if (data instanceof ArrayBuffer) {
  13536. data = new Uint8Array(data, byteOffset, byteLength);
  13537. }
  13538. else {
  13539. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13540. }
  13541. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13542. }
  13543. }
  13544. this._resetVertexBufferBinding();
  13545. };
  13546. Engine.prototype._resetIndexBufferBinding = function () {
  13547. this.bindIndexBuffer(null);
  13548. this._cachedIndexBuffer = null;
  13549. };
  13550. /**
  13551. * Creates a new index buffer
  13552. * @param indices defines the content of the index buffer
  13553. * @param updatable defines if the index buffer must be updatable
  13554. * @returns a new webGL buffer
  13555. */
  13556. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13557. var vbo = this._gl.createBuffer();
  13558. if (!vbo) {
  13559. throw new Error("Unable to create index buffer");
  13560. }
  13561. this.bindIndexBuffer(vbo);
  13562. // Check for 32 bits indices
  13563. var arrayBuffer;
  13564. var need32Bits = false;
  13565. if (indices instanceof Uint16Array) {
  13566. arrayBuffer = indices;
  13567. }
  13568. else {
  13569. //check 32 bit support
  13570. if (this._caps.uintIndices) {
  13571. if (indices instanceof Uint32Array) {
  13572. arrayBuffer = indices;
  13573. need32Bits = true;
  13574. }
  13575. else {
  13576. //number[] or Int32Array, check if 32 bit is necessary
  13577. for (var index = 0; index < indices.length; index++) {
  13578. if (indices[index] > 65535) {
  13579. need32Bits = true;
  13580. break;
  13581. }
  13582. }
  13583. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13584. }
  13585. }
  13586. else {
  13587. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13588. arrayBuffer = new Uint16Array(indices);
  13589. }
  13590. }
  13591. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13592. this._resetIndexBufferBinding();
  13593. vbo.references = 1;
  13594. vbo.is32Bits = need32Bits;
  13595. return vbo;
  13596. };
  13597. /**
  13598. * Bind a webGL buffer to the webGL context
  13599. * @param buffer defines the buffer to bind
  13600. */
  13601. Engine.prototype.bindArrayBuffer = function (buffer) {
  13602. if (!this._vaoRecordInProgress) {
  13603. this._unbindVertexArrayObject();
  13604. }
  13605. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13606. };
  13607. /**
  13608. * Bind an uniform buffer to the current webGL context
  13609. * @param buffer defines the buffer to bind
  13610. */
  13611. Engine.prototype.bindUniformBuffer = function (buffer) {
  13612. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13613. };
  13614. /**
  13615. * Bind a buffer to the current webGL context at a given location
  13616. * @param buffer defines the buffer to bind
  13617. * @param location defines the index where to bind the buffer
  13618. */
  13619. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13620. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13621. };
  13622. /**
  13623. * Bind a specific block at a given index in a specific shader program
  13624. * @param shaderProgram defines the shader program
  13625. * @param blockName defines the block name
  13626. * @param index defines the index where to bind the block
  13627. */
  13628. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13629. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13630. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13631. };
  13632. ;
  13633. Engine.prototype.bindIndexBuffer = function (buffer) {
  13634. if (!this._vaoRecordInProgress) {
  13635. this._unbindVertexArrayObject();
  13636. }
  13637. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13638. };
  13639. Engine.prototype.bindBuffer = function (buffer, target) {
  13640. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13641. this._gl.bindBuffer(target, buffer);
  13642. this._currentBoundBuffer[target] = buffer;
  13643. }
  13644. };
  13645. /**
  13646. * update the bound buffer with the given data
  13647. * @param data defines the data to update
  13648. */
  13649. Engine.prototype.updateArrayBuffer = function (data) {
  13650. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13651. };
  13652. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13653. var pointer = this._currentBufferPointers[indx];
  13654. var changed = false;
  13655. if (!pointer.active) {
  13656. changed = true;
  13657. pointer.active = true;
  13658. pointer.index = indx;
  13659. pointer.size = size;
  13660. pointer.type = type;
  13661. pointer.normalized = normalized;
  13662. pointer.stride = stride;
  13663. pointer.offset = offset;
  13664. pointer.buffer = buffer;
  13665. }
  13666. else {
  13667. if (pointer.buffer !== buffer) {
  13668. pointer.buffer = buffer;
  13669. changed = true;
  13670. }
  13671. if (pointer.size !== size) {
  13672. pointer.size = size;
  13673. changed = true;
  13674. }
  13675. if (pointer.type !== type) {
  13676. pointer.type = type;
  13677. changed = true;
  13678. }
  13679. if (pointer.normalized !== normalized) {
  13680. pointer.normalized = normalized;
  13681. changed = true;
  13682. }
  13683. if (pointer.stride !== stride) {
  13684. pointer.stride = stride;
  13685. changed = true;
  13686. }
  13687. if (pointer.offset !== offset) {
  13688. pointer.offset = offset;
  13689. changed = true;
  13690. }
  13691. }
  13692. if (changed || this._vaoRecordInProgress) {
  13693. this.bindArrayBuffer(buffer);
  13694. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13695. }
  13696. };
  13697. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13698. if (indexBuffer == null) {
  13699. return;
  13700. }
  13701. if (this._cachedIndexBuffer !== indexBuffer) {
  13702. this._cachedIndexBuffer = indexBuffer;
  13703. this.bindIndexBuffer(indexBuffer);
  13704. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13705. }
  13706. };
  13707. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13708. var attributes = effect.getAttributesNames();
  13709. if (!this._vaoRecordInProgress) {
  13710. this._unbindVertexArrayObject();
  13711. }
  13712. this.unbindAllAttributes();
  13713. for (var index = 0; index < attributes.length; index++) {
  13714. var order = effect.getAttributeLocation(index);
  13715. if (order >= 0) {
  13716. var vertexBuffer = vertexBuffers[attributes[index]];
  13717. if (!vertexBuffer) {
  13718. continue;
  13719. }
  13720. this._gl.enableVertexAttribArray(order);
  13721. if (!this._vaoRecordInProgress) {
  13722. this._vertexAttribArraysEnabled[order] = true;
  13723. }
  13724. var buffer = vertexBuffer.getBuffer();
  13725. if (buffer) {
  13726. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13727. if (vertexBuffer.getIsInstanced()) {
  13728. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13729. if (!this._vaoRecordInProgress) {
  13730. this._currentInstanceLocations.push(order);
  13731. this._currentInstanceBuffers.push(buffer);
  13732. }
  13733. }
  13734. }
  13735. }
  13736. }
  13737. };
  13738. /**
  13739. * Records a vertex array object
  13740. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13741. * @param vertexBuffers defines the list of vertex buffers to store
  13742. * @param indexBuffer defines the index buffer to store
  13743. * @param effect defines the effect to store
  13744. * @returns the new vertex array object
  13745. */
  13746. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13747. var vao = this._gl.createVertexArray();
  13748. this._vaoRecordInProgress = true;
  13749. this._gl.bindVertexArray(vao);
  13750. this._mustWipeVertexAttributes = true;
  13751. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13752. this.bindIndexBuffer(indexBuffer);
  13753. this._vaoRecordInProgress = false;
  13754. this._gl.bindVertexArray(null);
  13755. return vao;
  13756. };
  13757. /**
  13758. * Bind a specific vertex array object
  13759. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13760. * @param vertexArrayObject defines the vertex array object to bind
  13761. * @param indexBuffer defines the index buffer to bind
  13762. */
  13763. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13764. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13765. this._cachedVertexArrayObject = vertexArrayObject;
  13766. this._gl.bindVertexArray(vertexArrayObject);
  13767. this._cachedVertexBuffers = null;
  13768. this._cachedIndexBuffer = null;
  13769. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13770. this._mustWipeVertexAttributes = true;
  13771. }
  13772. };
  13773. /**
  13774. * Bind webGl buffers directly to the webGL context
  13775. * @param vertexBuffer defines the vertex buffer to bind
  13776. * @param indexBuffer defines the index buffer to bind
  13777. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13778. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13779. * @param effect defines the effect associated with the vertex buffer
  13780. */
  13781. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13782. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13783. this._cachedVertexBuffers = vertexBuffer;
  13784. this._cachedEffectForVertexBuffers = effect;
  13785. var attributesCount = effect.getAttributesCount();
  13786. this._unbindVertexArrayObject();
  13787. this.unbindAllAttributes();
  13788. var offset = 0;
  13789. for (var index = 0; index < attributesCount; index++) {
  13790. if (index < vertexDeclaration.length) {
  13791. var order = effect.getAttributeLocation(index);
  13792. if (order >= 0) {
  13793. this._gl.enableVertexAttribArray(order);
  13794. this._vertexAttribArraysEnabled[order] = true;
  13795. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13796. }
  13797. offset += vertexDeclaration[index] * 4;
  13798. }
  13799. }
  13800. }
  13801. this._bindIndexBufferWithCache(indexBuffer);
  13802. };
  13803. Engine.prototype._unbindVertexArrayObject = function () {
  13804. if (!this._cachedVertexArrayObject) {
  13805. return;
  13806. }
  13807. this._cachedVertexArrayObject = null;
  13808. this._gl.bindVertexArray(null);
  13809. };
  13810. /**
  13811. * Bind a list of vertex buffers to the webGL context
  13812. * @param vertexBuffers defines the list of vertex buffers to bind
  13813. * @param indexBuffer defines the index buffer to bind
  13814. * @param effect defines the effect associated with the vertex buffers
  13815. */
  13816. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13817. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13818. this._cachedVertexBuffers = vertexBuffers;
  13819. this._cachedEffectForVertexBuffers = effect;
  13820. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13821. }
  13822. this._bindIndexBufferWithCache(indexBuffer);
  13823. };
  13824. /**
  13825. * Unbind all instance attributes
  13826. */
  13827. Engine.prototype.unbindInstanceAttributes = function () {
  13828. var boundBuffer;
  13829. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13830. var instancesBuffer = this._currentInstanceBuffers[i];
  13831. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13832. boundBuffer = instancesBuffer;
  13833. this.bindArrayBuffer(instancesBuffer);
  13834. }
  13835. var offsetLocation = this._currentInstanceLocations[i];
  13836. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13837. }
  13838. this._currentInstanceBuffers.length = 0;
  13839. this._currentInstanceLocations.length = 0;
  13840. };
  13841. /**
  13842. * Release and free the memory of a vertex array object
  13843. * @param vao defines the vertex array object to delete
  13844. */
  13845. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13846. this._gl.deleteVertexArray(vao);
  13847. };
  13848. /** @hidden */
  13849. Engine.prototype._releaseBuffer = function (buffer) {
  13850. buffer.references--;
  13851. if (buffer.references === 0) {
  13852. this._gl.deleteBuffer(buffer);
  13853. return true;
  13854. }
  13855. return false;
  13856. };
  13857. /**
  13858. * Creates a webGL buffer to use with instanciation
  13859. * @param capacity defines the size of the buffer
  13860. * @returns the webGL buffer
  13861. */
  13862. Engine.prototype.createInstancesBuffer = function (capacity) {
  13863. var buffer = this._gl.createBuffer();
  13864. if (!buffer) {
  13865. throw new Error("Unable to create instance buffer");
  13866. }
  13867. buffer.capacity = capacity;
  13868. this.bindArrayBuffer(buffer);
  13869. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13870. return buffer;
  13871. };
  13872. /**
  13873. * Delete a webGL buffer used with instanciation
  13874. * @param buffer defines the webGL buffer to delete
  13875. */
  13876. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13877. this._gl.deleteBuffer(buffer);
  13878. };
  13879. /**
  13880. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13881. * @param instancesBuffer defines the webGL buffer to update and bind
  13882. * @param data defines the data to store in the buffer
  13883. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13884. */
  13885. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13886. this.bindArrayBuffer(instancesBuffer);
  13887. if (data) {
  13888. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13889. }
  13890. if (offsetLocations[0].index !== undefined) {
  13891. var stride = 0;
  13892. for (var i = 0; i < offsetLocations.length; i++) {
  13893. var ai = offsetLocations[i];
  13894. stride += ai.attributeSize * 4;
  13895. }
  13896. for (var i = 0; i < offsetLocations.length; i++) {
  13897. var ai = offsetLocations[i];
  13898. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13899. this._gl.enableVertexAttribArray(ai.index);
  13900. this._vertexAttribArraysEnabled[ai.index] = true;
  13901. }
  13902. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13903. this._gl.vertexAttribDivisor(ai.index, 1);
  13904. this._currentInstanceLocations.push(ai.index);
  13905. this._currentInstanceBuffers.push(instancesBuffer);
  13906. }
  13907. }
  13908. else {
  13909. for (var index = 0; index < 4; index++) {
  13910. var offsetLocation = offsetLocations[index];
  13911. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13912. this._gl.enableVertexAttribArray(offsetLocation);
  13913. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13914. }
  13915. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13916. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13917. this._currentInstanceLocations.push(offsetLocation);
  13918. this._currentInstanceBuffers.push(instancesBuffer);
  13919. }
  13920. }
  13921. };
  13922. /**
  13923. * Apply all cached states (depth, culling, stencil and alpha)
  13924. */
  13925. Engine.prototype.applyStates = function () {
  13926. this._depthCullingState.apply(this._gl);
  13927. this._stencilState.apply(this._gl);
  13928. this._alphaState.apply(this._gl);
  13929. };
  13930. /**
  13931. * Send a draw order
  13932. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13933. * @param indexStart defines the starting index
  13934. * @param indexCount defines the number of index to draw
  13935. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13936. */
  13937. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13938. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13939. };
  13940. /**
  13941. * Draw a list of points
  13942. * @param verticesStart defines the index of first vertex to draw
  13943. * @param verticesCount defines the count of vertices to draw
  13944. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13945. */
  13946. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13947. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13948. };
  13949. /**
  13950. * Draw a list of unindexed primitives
  13951. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13952. * @param verticesStart defines the index of first vertex to draw
  13953. * @param verticesCount defines the count of vertices to draw
  13954. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13955. */
  13956. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13957. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13958. };
  13959. /**
  13960. * Draw a list of indexed primitives
  13961. * @param fillMode defines the primitive to use
  13962. * @param indexStart defines the starting index
  13963. * @param indexCount defines the number of index to draw
  13964. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13965. */
  13966. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13967. // Apply states
  13968. this.applyStates();
  13969. this._drawCalls.addCount(1, false);
  13970. // Render
  13971. var drawMode = this._drawMode(fillMode);
  13972. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13973. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13974. if (instancesCount) {
  13975. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13976. }
  13977. else {
  13978. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13979. }
  13980. };
  13981. /**
  13982. * Draw a list of unindexed primitives
  13983. * @param fillMode defines the primitive to use
  13984. * @param verticesStart defines the index of first vertex to draw
  13985. * @param verticesCount defines the count of vertices to draw
  13986. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13987. */
  13988. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13989. // Apply states
  13990. this.applyStates();
  13991. this._drawCalls.addCount(1, false);
  13992. var drawMode = this._drawMode(fillMode);
  13993. if (instancesCount) {
  13994. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13995. }
  13996. else {
  13997. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13998. }
  13999. };
  14000. Engine.prototype._drawMode = function (fillMode) {
  14001. switch (fillMode) {
  14002. // Triangle views
  14003. case BABYLON.Material.TriangleFillMode:
  14004. return this._gl.TRIANGLES;
  14005. case BABYLON.Material.PointFillMode:
  14006. return this._gl.POINTS;
  14007. case BABYLON.Material.WireFrameFillMode:
  14008. return this._gl.LINES;
  14009. // Draw modes
  14010. case BABYLON.Material.PointListDrawMode:
  14011. return this._gl.POINTS;
  14012. case BABYLON.Material.LineListDrawMode:
  14013. return this._gl.LINES;
  14014. case BABYLON.Material.LineLoopDrawMode:
  14015. return this._gl.LINE_LOOP;
  14016. case BABYLON.Material.LineStripDrawMode:
  14017. return this._gl.LINE_STRIP;
  14018. case BABYLON.Material.TriangleStripDrawMode:
  14019. return this._gl.TRIANGLE_STRIP;
  14020. case BABYLON.Material.TriangleFanDrawMode:
  14021. return this._gl.TRIANGLE_FAN;
  14022. default:
  14023. return this._gl.TRIANGLES;
  14024. }
  14025. };
  14026. // Shaders
  14027. /** @hidden */
  14028. Engine.prototype._releaseEffect = function (effect) {
  14029. if (this._compiledEffects[effect._key]) {
  14030. delete this._compiledEffects[effect._key];
  14031. this._deleteProgram(effect.getProgram());
  14032. }
  14033. };
  14034. /** @hidden */
  14035. Engine.prototype._deleteProgram = function (program) {
  14036. if (program) {
  14037. program.__SPECTOR_rebuildProgram = null;
  14038. if (program.transformFeedback) {
  14039. this.deleteTransformFeedback(program.transformFeedback);
  14040. program.transformFeedback = null;
  14041. }
  14042. this._gl.deleteProgram(program);
  14043. }
  14044. };
  14045. /**
  14046. * Create a new effect (used to store vertex/fragment shaders)
  14047. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14048. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14049. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14050. * @param samplers defines an array of string used to represent textures
  14051. * @param defines defines the string containing the defines to use to compile the shaders
  14052. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14053. * @param onCompiled defines a function to call when the effect creation is successful
  14054. * @param onError defines a function to call when the effect creation has failed
  14055. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14056. * @returns the new Effect
  14057. */
  14058. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14059. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14060. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14061. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14062. if (this._compiledEffects[name]) {
  14063. var compiledEffect = this._compiledEffects[name];
  14064. if (onCompiled && compiledEffect.isReady()) {
  14065. onCompiled(compiledEffect);
  14066. }
  14067. return compiledEffect;
  14068. }
  14069. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14070. effect._key = name;
  14071. this._compiledEffects[name] = effect;
  14072. return effect;
  14073. };
  14074. /**
  14075. * Create an effect to use with particle systems.
  14076. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14077. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14078. * @param uniformsNames defines a list of attribute names
  14079. * @param samplers defines an array of string used to represent textures
  14080. * @param defines defines the string containing the defines to use to compile the shaders
  14081. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14082. * @param onCompiled defines a function to call when the effect creation is successful
  14083. * @param onError defines a function to call when the effect creation has failed
  14084. * @returns the new Effect
  14085. */
  14086. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14087. if (uniformsNames === void 0) { uniformsNames = []; }
  14088. if (samplers === void 0) { samplers = []; }
  14089. if (defines === void 0) { defines = ""; }
  14090. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14091. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14092. defines += "\n#define BILLBOARD\n";
  14093. return this.createEffect({
  14094. vertex: "particles",
  14095. fragmentElement: fragmentName
  14096. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14097. };
  14098. /**
  14099. * Directly creates a webGL program
  14100. * @param vertexCode defines the vertex shader code to use
  14101. * @param fragmentCode defines the fragment shader code to use
  14102. * @param context defines the webGL context to use (if not set, the current one will be used)
  14103. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14104. * @returns the new webGL program
  14105. */
  14106. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14107. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14108. context = context || this._gl;
  14109. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14110. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14111. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14112. };
  14113. /**
  14114. * Creates a webGL program
  14115. * @param vertexCode defines the vertex shader code to use
  14116. * @param fragmentCode defines the fragment shader code to use
  14117. * @param defines defines the string containing the defines to use to compile the shaders
  14118. * @param context defines the webGL context to use (if not set, the current one will be used)
  14119. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14120. * @returns the new webGL program
  14121. */
  14122. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14123. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14124. context = context || this._gl;
  14125. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14126. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14127. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14128. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14129. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14130. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14131. return program;
  14132. };
  14133. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14134. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14135. var shaderProgram = context.createProgram();
  14136. if (!shaderProgram) {
  14137. throw new Error("Unable to create program");
  14138. }
  14139. context.attachShader(shaderProgram, vertexShader);
  14140. context.attachShader(shaderProgram, fragmentShader);
  14141. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14142. var transformFeedback = this.createTransformFeedback();
  14143. this.bindTransformFeedback(transformFeedback);
  14144. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14145. shaderProgram.transformFeedback = transformFeedback;
  14146. }
  14147. context.linkProgram(shaderProgram);
  14148. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14149. this.bindTransformFeedback(null);
  14150. }
  14151. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14152. if (!linked) {
  14153. context.validateProgram(shaderProgram);
  14154. var error = context.getProgramInfoLog(shaderProgram);
  14155. if (error) {
  14156. throw new Error(error);
  14157. }
  14158. }
  14159. context.deleteShader(vertexShader);
  14160. context.deleteShader(fragmentShader);
  14161. return shaderProgram;
  14162. };
  14163. /**
  14164. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14165. * @param shaderProgram defines the webGL program to use
  14166. * @param uniformsNames defines the list of uniform names
  14167. * @returns an array of webGL uniform locations
  14168. */
  14169. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14170. var results = new Array();
  14171. for (var index = 0; index < uniformsNames.length; index++) {
  14172. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14173. }
  14174. return results;
  14175. };
  14176. /**
  14177. * Gets the lsit of active attributes for a given webGL program
  14178. * @param shaderProgram defines the webGL program to use
  14179. * @param attributesNames defines the list of attribute names to get
  14180. * @returns an array of indices indicating the offset of each attribute
  14181. */
  14182. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14183. var results = [];
  14184. for (var index = 0; index < attributesNames.length; index++) {
  14185. try {
  14186. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14187. }
  14188. catch (e) {
  14189. results.push(-1);
  14190. }
  14191. }
  14192. return results;
  14193. };
  14194. /**
  14195. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14196. * @param effect defines the effect to activate
  14197. */
  14198. Engine.prototype.enableEffect = function (effect) {
  14199. if (!effect) {
  14200. return;
  14201. }
  14202. // Use program
  14203. this.bindSamplers(effect);
  14204. this._currentEffect = effect;
  14205. if (effect.onBind) {
  14206. effect.onBind(effect);
  14207. }
  14208. effect.onBindObservable.notifyObservers(effect);
  14209. };
  14210. /**
  14211. * Set the value of an uniform to an array of int32
  14212. * @param uniform defines the webGL uniform location where to store the value
  14213. * @param array defines the array of int32 to store
  14214. */
  14215. Engine.prototype.setIntArray = function (uniform, array) {
  14216. if (!uniform)
  14217. return;
  14218. this._gl.uniform1iv(uniform, array);
  14219. };
  14220. /**
  14221. * Set the value of an uniform to an array of int32 (stored as vec2)
  14222. * @param uniform defines the webGL uniform location where to store the value
  14223. * @param array defines the array of int32 to store
  14224. */
  14225. Engine.prototype.setIntArray2 = function (uniform, array) {
  14226. if (!uniform || array.length % 2 !== 0)
  14227. return;
  14228. this._gl.uniform2iv(uniform, array);
  14229. };
  14230. /**
  14231. * Set the value of an uniform to an array of int32 (stored as vec3)
  14232. * @param uniform defines the webGL uniform location where to store the value
  14233. * @param array defines the array of int32 to store
  14234. */
  14235. Engine.prototype.setIntArray3 = function (uniform, array) {
  14236. if (!uniform || array.length % 3 !== 0)
  14237. return;
  14238. this._gl.uniform3iv(uniform, array);
  14239. };
  14240. /**
  14241. * Set the value of an uniform to an array of int32 (stored as vec4)
  14242. * @param uniform defines the webGL uniform location where to store the value
  14243. * @param array defines the array of int32 to store
  14244. */
  14245. Engine.prototype.setIntArray4 = function (uniform, array) {
  14246. if (!uniform || array.length % 4 !== 0)
  14247. return;
  14248. this._gl.uniform4iv(uniform, array);
  14249. };
  14250. /**
  14251. * Set the value of an uniform to an array of float32
  14252. * @param uniform defines the webGL uniform location where to store the value
  14253. * @param array defines the array of float32 to store
  14254. */
  14255. Engine.prototype.setFloatArray = function (uniform, array) {
  14256. if (!uniform)
  14257. return;
  14258. this._gl.uniform1fv(uniform, array);
  14259. };
  14260. /**
  14261. * Set the value of an uniform to an array of float32 (stored as vec2)
  14262. * @param uniform defines the webGL uniform location where to store the value
  14263. * @param array defines the array of float32 to store
  14264. */
  14265. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14266. if (!uniform || array.length % 2 !== 0)
  14267. return;
  14268. this._gl.uniform2fv(uniform, array);
  14269. };
  14270. /**
  14271. * Set the value of an uniform to an array of float32 (stored as vec3)
  14272. * @param uniform defines the webGL uniform location where to store the value
  14273. * @param array defines the array of float32 to store
  14274. */
  14275. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14276. if (!uniform || array.length % 3 !== 0)
  14277. return;
  14278. this._gl.uniform3fv(uniform, array);
  14279. };
  14280. /**
  14281. * Set the value of an uniform to an array of float32 (stored as vec4)
  14282. * @param uniform defines the webGL uniform location where to store the value
  14283. * @param array defines the array of float32 to store
  14284. */
  14285. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14286. if (!uniform || array.length % 4 !== 0)
  14287. return;
  14288. this._gl.uniform4fv(uniform, array);
  14289. };
  14290. /**
  14291. * Set the value of an uniform to an array of number
  14292. * @param uniform defines the webGL uniform location where to store the value
  14293. * @param array defines the array of number to store
  14294. */
  14295. Engine.prototype.setArray = function (uniform, array) {
  14296. if (!uniform)
  14297. return;
  14298. this._gl.uniform1fv(uniform, array);
  14299. };
  14300. /**
  14301. * Set the value of an uniform to an array of number (stored as vec2)
  14302. * @param uniform defines the webGL uniform location where to store the value
  14303. * @param array defines the array of number to store
  14304. */
  14305. Engine.prototype.setArray2 = function (uniform, array) {
  14306. if (!uniform || array.length % 2 !== 0)
  14307. return;
  14308. this._gl.uniform2fv(uniform, array);
  14309. };
  14310. /**
  14311. * Set the value of an uniform to an array of number (stored as vec3)
  14312. * @param uniform defines the webGL uniform location where to store the value
  14313. * @param array defines the array of number to store
  14314. */
  14315. Engine.prototype.setArray3 = function (uniform, array) {
  14316. if (!uniform || array.length % 3 !== 0)
  14317. return;
  14318. this._gl.uniform3fv(uniform, array);
  14319. };
  14320. /**
  14321. * Set the value of an uniform to an array of number (stored as vec4)
  14322. * @param uniform defines the webGL uniform location where to store the value
  14323. * @param array defines the array of number to store
  14324. */
  14325. Engine.prototype.setArray4 = function (uniform, array) {
  14326. if (!uniform || array.length % 4 !== 0)
  14327. return;
  14328. this._gl.uniform4fv(uniform, array);
  14329. };
  14330. /**
  14331. * Set the value of an uniform to an array of float32 (stored as matrices)
  14332. * @param uniform defines the webGL uniform location where to store the value
  14333. * @param matrices defines the array of float32 to store
  14334. */
  14335. Engine.prototype.setMatrices = function (uniform, matrices) {
  14336. if (!uniform)
  14337. return;
  14338. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14339. };
  14340. /**
  14341. * Set the value of an uniform to a matrix
  14342. * @param uniform defines the webGL uniform location where to store the value
  14343. * @param matrix defines the matrix to store
  14344. */
  14345. Engine.prototype.setMatrix = function (uniform, matrix) {
  14346. if (!uniform)
  14347. return;
  14348. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14349. };
  14350. /**
  14351. * Set the value of an uniform to a matrix (3x3)
  14352. * @param uniform defines the webGL uniform location where to store the value
  14353. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14354. */
  14355. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14356. if (!uniform)
  14357. return;
  14358. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14359. };
  14360. /**
  14361. * Set the value of an uniform to a matrix (2x2)
  14362. * @param uniform defines the webGL uniform location where to store the value
  14363. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14364. */
  14365. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14366. if (!uniform)
  14367. return;
  14368. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14369. };
  14370. /**
  14371. * Set the value of an uniform to a number (int)
  14372. * @param uniform defines the webGL uniform location where to store the value
  14373. * @param value defines the int number to store
  14374. */
  14375. Engine.prototype.setInt = function (uniform, value) {
  14376. if (!uniform)
  14377. return;
  14378. this._gl.uniform1i(uniform, value);
  14379. };
  14380. /**
  14381. * Set the value of an uniform to a number (float)
  14382. * @param uniform defines the webGL uniform location where to store the value
  14383. * @param value defines the float number to store
  14384. */
  14385. Engine.prototype.setFloat = function (uniform, value) {
  14386. if (!uniform)
  14387. return;
  14388. this._gl.uniform1f(uniform, value);
  14389. };
  14390. /**
  14391. * Set the value of an uniform to a vec2
  14392. * @param uniform defines the webGL uniform location where to store the value
  14393. * @param x defines the 1st component of the value
  14394. * @param y defines the 2nd component of the value
  14395. */
  14396. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14397. if (!uniform)
  14398. return;
  14399. this._gl.uniform2f(uniform, x, y);
  14400. };
  14401. /**
  14402. * Set the value of an uniform to a vec3
  14403. * @param uniform defines the webGL uniform location where to store the value
  14404. * @param x defines the 1st component of the value
  14405. * @param y defines the 2nd component of the value
  14406. * @param z defines the 3rd component of the value
  14407. */
  14408. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14409. if (!uniform)
  14410. return;
  14411. this._gl.uniform3f(uniform, x, y, z);
  14412. };
  14413. /**
  14414. * Set the value of an uniform to a boolean
  14415. * @param uniform defines the webGL uniform location where to store the value
  14416. * @param bool defines the boolean to store
  14417. */
  14418. Engine.prototype.setBool = function (uniform, bool) {
  14419. if (!uniform)
  14420. return;
  14421. this._gl.uniform1i(uniform, bool);
  14422. };
  14423. /**
  14424. * Set the value of an uniform to a vec4
  14425. * @param uniform defines the webGL uniform location where to store the value
  14426. * @param x defines the 1st component of the value
  14427. * @param y defines the 2nd component of the value
  14428. * @param z defines the 3rd component of the value
  14429. * @param w defines the 4th component of the value
  14430. */
  14431. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14432. if (!uniform)
  14433. return;
  14434. this._gl.uniform4f(uniform, x, y, z, w);
  14435. };
  14436. /**
  14437. * Set the value of an uniform to a Color3
  14438. * @param uniform defines the webGL uniform location where to store the value
  14439. * @param color3 defines the color to store
  14440. */
  14441. Engine.prototype.setColor3 = function (uniform, color3) {
  14442. if (!uniform)
  14443. return;
  14444. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14445. };
  14446. /**
  14447. * Set the value of an uniform to a Color3 and an alpha value
  14448. * @param uniform defines the webGL uniform location where to store the value
  14449. * @param color3 defines the color to store
  14450. * @param alpha defines the alpha component to store
  14451. */
  14452. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14453. if (!uniform)
  14454. return;
  14455. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14456. };
  14457. /**
  14458. * Sets a Color4 on a uniform variable
  14459. * @param uniform defines the uniform location
  14460. * @param color4 defines the value to be set
  14461. */
  14462. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14463. if (!uniform)
  14464. return;
  14465. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14466. };
  14467. // States
  14468. /**
  14469. * Set various states to the webGL context
  14470. * @param culling defines backface culling state
  14471. * @param zOffset defines the value to apply to zOffset (0 by default)
  14472. * @param force defines if states must be applied even if cache is up to date
  14473. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14474. */
  14475. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14476. if (zOffset === void 0) { zOffset = 0; }
  14477. if (reverseSide === void 0) { reverseSide = false; }
  14478. // Culling
  14479. if (this._depthCullingState.cull !== culling || force) {
  14480. this._depthCullingState.cull = culling;
  14481. }
  14482. // Cull face
  14483. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14484. if (this._depthCullingState.cullFace !== cullFace || force) {
  14485. this._depthCullingState.cullFace = cullFace;
  14486. }
  14487. // Z offset
  14488. this.setZOffset(zOffset);
  14489. // Front face
  14490. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14491. if (this._depthCullingState.frontFace !== frontFace || force) {
  14492. this._depthCullingState.frontFace = frontFace;
  14493. }
  14494. };
  14495. /**
  14496. * Set the z offset to apply to current rendering
  14497. * @param value defines the offset to apply
  14498. */
  14499. Engine.prototype.setZOffset = function (value) {
  14500. this._depthCullingState.zOffset = value;
  14501. };
  14502. /**
  14503. * Gets the current value of the zOffset
  14504. * @returns the current zOffset state
  14505. */
  14506. Engine.prototype.getZOffset = function () {
  14507. return this._depthCullingState.zOffset;
  14508. };
  14509. /**
  14510. * Enable or disable depth buffering
  14511. * @param enable defines the state to set
  14512. */
  14513. Engine.prototype.setDepthBuffer = function (enable) {
  14514. this._depthCullingState.depthTest = enable;
  14515. };
  14516. /**
  14517. * Gets a boolean indicating if depth writing is enabled
  14518. * @returns the current depth writing state
  14519. */
  14520. Engine.prototype.getDepthWrite = function () {
  14521. return this._depthCullingState.depthMask;
  14522. };
  14523. /**
  14524. * Enable or disable depth writing
  14525. * @param enable defines the state to set
  14526. */
  14527. Engine.prototype.setDepthWrite = function (enable) {
  14528. this._depthCullingState.depthMask = enable;
  14529. };
  14530. /**
  14531. * Enable or disable color writing
  14532. * @param enable defines the state to set
  14533. */
  14534. Engine.prototype.setColorWrite = function (enable) {
  14535. this._gl.colorMask(enable, enable, enable, enable);
  14536. this._colorWrite = enable;
  14537. };
  14538. /**
  14539. * Gets a boolean indicating if color writing is enabled
  14540. * @returns the current color writing state
  14541. */
  14542. Engine.prototype.getColorWrite = function () {
  14543. return this._colorWrite;
  14544. };
  14545. /**
  14546. * Sets alpha constants used by some alpha blending modes
  14547. * @param r defines the red component
  14548. * @param g defines the green component
  14549. * @param b defines the blue component
  14550. * @param a defines the alpha component
  14551. */
  14552. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14553. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14554. };
  14555. /**
  14556. * Sets the current alpha mode
  14557. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14558. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14559. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14560. */
  14561. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14562. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14563. if (this._alphaMode === mode) {
  14564. return;
  14565. }
  14566. switch (mode) {
  14567. case Engine.ALPHA_DISABLE:
  14568. this._alphaState.alphaBlend = false;
  14569. break;
  14570. case Engine.ALPHA_PREMULTIPLIED:
  14571. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14572. this._alphaState.alphaBlend = true;
  14573. break;
  14574. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14575. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14576. this._alphaState.alphaBlend = true;
  14577. break;
  14578. case Engine.ALPHA_COMBINE:
  14579. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14580. this._alphaState.alphaBlend = true;
  14581. break;
  14582. case Engine.ALPHA_ONEONE:
  14583. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14584. this._alphaState.alphaBlend = true;
  14585. break;
  14586. case Engine.ALPHA_ADD:
  14587. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14588. this._alphaState.alphaBlend = true;
  14589. break;
  14590. case Engine.ALPHA_SUBTRACT:
  14591. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14592. this._alphaState.alphaBlend = true;
  14593. break;
  14594. case Engine.ALPHA_MULTIPLY:
  14595. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14596. this._alphaState.alphaBlend = true;
  14597. break;
  14598. case Engine.ALPHA_MAXIMIZED:
  14599. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14600. this._alphaState.alphaBlend = true;
  14601. break;
  14602. case Engine.ALPHA_INTERPOLATE:
  14603. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14604. this._alphaState.alphaBlend = true;
  14605. break;
  14606. case Engine.ALPHA_SCREENMODE:
  14607. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14608. this._alphaState.alphaBlend = true;
  14609. break;
  14610. }
  14611. if (!noDepthWriteChange) {
  14612. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14613. }
  14614. this._alphaMode = mode;
  14615. };
  14616. /**
  14617. * Gets the current alpha mode
  14618. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14619. * @returns the current alpha mode
  14620. */
  14621. Engine.prototype.getAlphaMode = function () {
  14622. return this._alphaMode;
  14623. };
  14624. // Textures
  14625. /**
  14626. * Clears the list of texture accessible through engine.
  14627. * This can help preventing texture load conflict due to name collision.
  14628. */
  14629. Engine.prototype.clearInternalTexturesCache = function () {
  14630. this._internalTexturesCache = [];
  14631. };
  14632. /**
  14633. * Force the entire cache to be cleared
  14634. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14635. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14636. */
  14637. Engine.prototype.wipeCaches = function (bruteForce) {
  14638. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14639. return;
  14640. }
  14641. this._currentEffect = null;
  14642. this._unpackFlipYCached = null;
  14643. this._viewportCached.x = 0;
  14644. this._viewportCached.y = 0;
  14645. this._viewportCached.z = 0;
  14646. this._viewportCached.w = 0;
  14647. if (bruteForce) {
  14648. this.resetTextureCache();
  14649. this._currentProgram = null;
  14650. this._stencilState.reset();
  14651. this._depthCullingState.reset();
  14652. this.setDepthFunctionToLessOrEqual();
  14653. this._alphaState.reset();
  14654. }
  14655. this._resetVertexBufferBinding();
  14656. this._cachedIndexBuffer = null;
  14657. this._cachedEffectForVertexBuffers = null;
  14658. this._unbindVertexArrayObject();
  14659. this.bindIndexBuffer(null);
  14660. };
  14661. /**
  14662. * Set the compressed texture format to use, based on the formats you have, and the formats
  14663. * supported by the hardware / browser.
  14664. *
  14665. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14666. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14667. * to API arguments needed to compressed textures. This puts the burden on the container
  14668. * generator to house the arcane code for determining these for current & future formats.
  14669. *
  14670. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14671. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14672. *
  14673. * Note: The result of this call is not taken into account when a texture is base64.
  14674. *
  14675. * @param formatsAvailable defines the list of those format families you have created
  14676. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14677. *
  14678. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14679. * @returns The extension selected.
  14680. */
  14681. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14682. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14683. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14684. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14685. return this._textureFormatInUse = this._texturesSupported[i];
  14686. }
  14687. }
  14688. }
  14689. // actively set format to nothing, to allow this to be called more than once
  14690. // and possibly fail the 2nd time
  14691. this._textureFormatInUse = null;
  14692. return null;
  14693. };
  14694. /** @hidden */
  14695. Engine.prototype._createTexture = function () {
  14696. var texture = this._gl.createTexture();
  14697. if (!texture) {
  14698. throw new Error("Unable to create texture");
  14699. }
  14700. return texture;
  14701. };
  14702. /**
  14703. * Usually called from BABYLON.Texture.ts.
  14704. * Passed information to create a WebGLTexture
  14705. * @param urlArg defines a value which contains one of the following:
  14706. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14707. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14708. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14709. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14710. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14711. * @param scene needed for loading to the correct scene
  14712. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14713. * @param onLoad optional callback to be called upon successful completion
  14714. * @param onError optional callback to be called upon failure
  14715. * @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
  14716. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14717. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14718. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14719. */
  14720. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14721. var _this = this;
  14722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14723. if (onLoad === void 0) { onLoad = null; }
  14724. if (onError === void 0) { onError = null; }
  14725. if (buffer === void 0) { buffer = null; }
  14726. if (fallback === void 0) { fallback = null; }
  14727. if (format === void 0) { format = null; }
  14728. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14729. var fromData = url.substr(0, 5) === "data:";
  14730. var fromBlob = url.substr(0, 5) === "blob:";
  14731. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14732. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14733. // establish the file extension, if possible
  14734. var lastDot = url.lastIndexOf('.');
  14735. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14736. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14737. var isTGA = (extension.indexOf(".tga") === 0);
  14738. // determine if a ktx file should be substituted
  14739. var isKTX = false;
  14740. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14741. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14742. isKTX = true;
  14743. }
  14744. if (scene) {
  14745. scene._addPendingData(texture);
  14746. }
  14747. texture.url = url;
  14748. texture.generateMipMaps = !noMipmap;
  14749. texture.samplingMode = samplingMode;
  14750. texture.invertY = invertY;
  14751. if (!this._doNotHandleContextLost) {
  14752. // Keep a link to the buffer only if we plan to handle context lost
  14753. texture._buffer = buffer;
  14754. }
  14755. var onLoadObserver = null;
  14756. if (onLoad && !fallback) {
  14757. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14758. }
  14759. if (!fallback)
  14760. this._internalTexturesCache.push(texture);
  14761. var onerror = function (message, exception) {
  14762. if (scene) {
  14763. scene._removePendingData(texture);
  14764. }
  14765. if (onLoadObserver && !isKTX) {
  14766. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14767. texture.onLoadedObservable.remove(onLoadObserver);
  14768. }
  14769. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14770. if (isKTX) {
  14771. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14772. }
  14773. else if (BABYLON.Tools.UseFallbackTexture) {
  14774. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14775. }
  14776. if (onError) {
  14777. onError(message || "Unknown error", exception);
  14778. }
  14779. };
  14780. var callback = null;
  14781. // processing for non-image formats
  14782. if (isKTX || isTGA || isDDS) {
  14783. if (isKTX) {
  14784. callback = function (data) {
  14785. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14786. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14787. ktx.uploadLevels(_this._gl, !noMipmap);
  14788. return false;
  14789. }, samplingMode);
  14790. };
  14791. }
  14792. else if (isTGA) {
  14793. callback = function (arrayBuffer) {
  14794. var data = new Uint8Array(arrayBuffer);
  14795. var header = BABYLON.TGATools.GetTGAHeader(data);
  14796. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14797. BABYLON.TGATools.UploadContent(_this._gl, data);
  14798. return false;
  14799. }, samplingMode);
  14800. };
  14801. }
  14802. else if (isDDS) {
  14803. callback = function (data) {
  14804. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14805. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14806. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14807. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14808. return false;
  14809. }, samplingMode);
  14810. };
  14811. }
  14812. if (!buffer) {
  14813. this._loadFile(url, function (data) {
  14814. if (callback) {
  14815. callback(data);
  14816. }
  14817. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14818. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14819. });
  14820. }
  14821. else {
  14822. if (callback) {
  14823. callback(buffer);
  14824. }
  14825. }
  14826. // image format processing
  14827. }
  14828. else {
  14829. var onload = function (img) {
  14830. if (fromBlob && !_this._doNotHandleContextLost) {
  14831. // We need to store the image if we need to rebuild the texture
  14832. // in case of a webgl context lost
  14833. texture._buffer = img;
  14834. }
  14835. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14836. var gl = _this._gl;
  14837. var isPot = (img.width === potWidth && img.height === potHeight);
  14838. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14839. if (isPot) {
  14840. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14841. return false;
  14842. }
  14843. var maxTextureSize = _this._caps.maxTextureSize;
  14844. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14845. _this._prepareWorkingCanvas();
  14846. if (!_this._workingCanvas || !_this._workingContext) {
  14847. return false;
  14848. }
  14849. _this._workingCanvas.width = potWidth;
  14850. _this._workingCanvas.height = potHeight;
  14851. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14852. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14853. texture.width = potWidth;
  14854. texture.height = potHeight;
  14855. return false;
  14856. }
  14857. else {
  14858. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14859. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14860. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14861. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14862. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14863. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14864. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14866. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14867. _this._releaseTexture(source_1);
  14868. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14869. continuationCallback();
  14870. });
  14871. }
  14872. return true;
  14873. }, samplingMode);
  14874. };
  14875. if (!fromData || isBase64) {
  14876. if (buffer instanceof HTMLImageElement) {
  14877. onload(buffer);
  14878. }
  14879. else {
  14880. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14881. }
  14882. }
  14883. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14884. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14885. }
  14886. else {
  14887. onload(buffer);
  14888. }
  14889. }
  14890. return texture;
  14891. };
  14892. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14893. var _this = this;
  14894. var rtt = this.createRenderTargetTexture({
  14895. width: destination.width,
  14896. height: destination.height,
  14897. }, {
  14898. generateMipMaps: false,
  14899. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14900. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14901. generateDepthBuffer: false,
  14902. generateStencilBuffer: false
  14903. });
  14904. if (!this._rescalePostProcess) {
  14905. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14906. }
  14907. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14908. _this._rescalePostProcess.onApply = function (effect) {
  14909. effect._bindTexture("textureSampler", source);
  14910. };
  14911. var hostingScene = scene;
  14912. if (!hostingScene) {
  14913. hostingScene = _this.scenes[_this.scenes.length - 1];
  14914. }
  14915. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14916. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14917. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14918. _this.unBindFramebuffer(rtt);
  14919. _this._releaseTexture(rtt);
  14920. if (onComplete) {
  14921. onComplete();
  14922. }
  14923. });
  14924. };
  14925. /**
  14926. * Update a raw texture
  14927. * @param texture defines the texture to update
  14928. * @param data defines the data to store in the texture
  14929. * @param format defines the format of the data
  14930. * @param invertY defines if data must be stored with Y axis inverted
  14931. * @param compression defines the compression used (null by default)
  14932. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14933. */
  14934. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14935. if (compression === void 0) { compression = null; }
  14936. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14937. if (!texture) {
  14938. return;
  14939. }
  14940. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14941. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14942. // babylon's internalFormat but gl's texImage2D format
  14943. var internalFormat = this._getInternalFormat(format);
  14944. var textureType = this._getWebGLTextureType(type);
  14945. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14946. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14947. if (!this._doNotHandleContextLost) {
  14948. texture._bufferView = data;
  14949. texture.format = format;
  14950. texture.type = type;
  14951. texture.invertY = invertY;
  14952. texture._compression = compression;
  14953. }
  14954. if (texture.width % 4 !== 0) {
  14955. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14956. }
  14957. if (compression && data) {
  14958. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14959. }
  14960. else {
  14961. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14962. }
  14963. if (texture.generateMipMaps) {
  14964. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14965. }
  14966. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14967. // this.resetTextureCache();
  14968. texture.isReady = true;
  14969. };
  14970. /**
  14971. * Creates a raw texture
  14972. * @param data defines the data to store in the texture
  14973. * @param width defines the width of the texture
  14974. * @param height defines the height of the texture
  14975. * @param format defines the format of the data
  14976. * @param generateMipMaps defines if the engine should generate the mip levels
  14977. * @param invertY defines if data must be stored with Y axis inverted
  14978. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14979. * @param compression defines the compression used (null by default)
  14980. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14981. * @returns the raw texture inside an InternalTexture
  14982. */
  14983. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14984. if (compression === void 0) { compression = null; }
  14985. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14986. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14987. texture.baseWidth = width;
  14988. texture.baseHeight = height;
  14989. texture.width = width;
  14990. texture.height = height;
  14991. texture.format = format;
  14992. texture.generateMipMaps = generateMipMaps;
  14993. texture.samplingMode = samplingMode;
  14994. texture.invertY = invertY;
  14995. texture._compression = compression;
  14996. texture.type = type;
  14997. if (!this._doNotHandleContextLost) {
  14998. texture._bufferView = data;
  14999. }
  15000. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15001. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15002. // Filters
  15003. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15004. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15005. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15006. if (generateMipMaps) {
  15007. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15008. }
  15009. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15010. this._internalTexturesCache.push(texture);
  15011. return texture;
  15012. };
  15013. /** @hidden */
  15014. Engine.prototype._unpackFlipY = function (value) {
  15015. if (this._unpackFlipYCached !== value) {
  15016. this._unpackFlipYCached = value;
  15017. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15018. }
  15019. };
  15020. /**
  15021. * Creates a dynamic texture
  15022. * @param width defines the width of the texture
  15023. * @param height defines the height of the texture
  15024. * @param generateMipMaps defines if the engine should generate the mip levels
  15025. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15026. * @returns the dynamic texture inside an InternalTexture
  15027. */
  15028. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15029. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15030. texture.baseWidth = width;
  15031. texture.baseHeight = height;
  15032. if (generateMipMaps) {
  15033. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15034. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15035. }
  15036. // this.resetTextureCache();
  15037. texture.width = width;
  15038. texture.height = height;
  15039. texture.isReady = false;
  15040. texture.generateMipMaps = generateMipMaps;
  15041. texture.samplingMode = samplingMode;
  15042. this.updateTextureSamplingMode(samplingMode, texture);
  15043. this._internalTexturesCache.push(texture);
  15044. return texture;
  15045. };
  15046. /**
  15047. * Update the sampling mode of a given texture
  15048. * @param samplingMode defines the required sampling mode
  15049. * @param texture defines the texture to update
  15050. */
  15051. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15052. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  15053. if (texture.isCube) {
  15054. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15055. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15056. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15057. }
  15058. else if (texture.is3D) {
  15059. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15060. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15061. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15062. }
  15063. else {
  15064. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15065. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15066. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15067. }
  15068. texture.samplingMode = samplingMode;
  15069. };
  15070. /**
  15071. * Update the content of a dynamic texture
  15072. * @param texture defines the texture to update
  15073. * @param canvas defines the canvas containing the source
  15074. * @param invertY defines if data must be stored with Y axis inverted
  15075. * @param premulAlpha defines if alpha is stored as premultiplied
  15076. * @param format defines the format of the data
  15077. */
  15078. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15079. if (premulAlpha === void 0) { premulAlpha = false; }
  15080. if (!texture) {
  15081. return;
  15082. }
  15083. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15084. this._unpackFlipY(invertY);
  15085. if (premulAlpha) {
  15086. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15087. }
  15088. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15089. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15090. if (texture.generateMipMaps) {
  15091. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15092. }
  15093. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15094. if (premulAlpha) {
  15095. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15096. }
  15097. texture.isReady = true;
  15098. };
  15099. /**
  15100. * Update a video texture
  15101. * @param texture defines the texture to update
  15102. * @param video defines the video element to use
  15103. * @param invertY defines if data must be stored with Y axis inverted
  15104. */
  15105. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15106. if (!texture || texture._isDisabled) {
  15107. return;
  15108. }
  15109. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15110. this._unpackFlipY(!invertY); // Video are upside down by default
  15111. try {
  15112. // Testing video texture support
  15113. if (this._videoTextureSupported === undefined) {
  15114. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15115. if (this._gl.getError() !== 0) {
  15116. this._videoTextureSupported = false;
  15117. }
  15118. else {
  15119. this._videoTextureSupported = true;
  15120. }
  15121. }
  15122. // Copy video through the current working canvas if video texture is not supported
  15123. if (!this._videoTextureSupported) {
  15124. if (!texture._workingCanvas) {
  15125. texture._workingCanvas = document.createElement("canvas");
  15126. var context = texture._workingCanvas.getContext("2d");
  15127. if (!context) {
  15128. throw new Error("Unable to get 2d context");
  15129. }
  15130. texture._workingContext = context;
  15131. texture._workingCanvas.width = texture.width;
  15132. texture._workingCanvas.height = texture.height;
  15133. }
  15134. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15135. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15136. }
  15137. else {
  15138. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15139. }
  15140. if (texture.generateMipMaps) {
  15141. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15142. }
  15143. if (!wasPreviouslyBound) {
  15144. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15145. }
  15146. // this.resetTextureCache();
  15147. texture.isReady = true;
  15148. }
  15149. catch (ex) {
  15150. // Something unexpected
  15151. // Let's disable the texture
  15152. texture._isDisabled = true;
  15153. }
  15154. };
  15155. /**
  15156. * Updates a depth texture Comparison Mode and Function.
  15157. * If the comparison Function is equal to 0, the mode will be set to none.
  15158. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15159. * @param texture The texture to set the comparison function for
  15160. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15161. */
  15162. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15163. if (this.webGLVersion === 1) {
  15164. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15165. return;
  15166. }
  15167. var gl = this._gl;
  15168. if (texture.isCube) {
  15169. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15170. if (comparisonFunction === 0) {
  15171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15172. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15173. }
  15174. else {
  15175. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15176. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15177. }
  15178. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15179. }
  15180. else {
  15181. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15182. if (comparisonFunction === 0) {
  15183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15185. }
  15186. else {
  15187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15189. }
  15190. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15191. }
  15192. texture._comparisonFunction = comparisonFunction;
  15193. };
  15194. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15195. var width = size.width || size;
  15196. var height = size.height || size;
  15197. internalTexture.baseWidth = width;
  15198. internalTexture.baseHeight = height;
  15199. internalTexture.width = width;
  15200. internalTexture.height = height;
  15201. internalTexture.isReady = true;
  15202. internalTexture.samples = 1;
  15203. internalTexture.generateMipMaps = false;
  15204. internalTexture._generateDepthBuffer = true;
  15205. internalTexture._generateStencilBuffer = generateStencil;
  15206. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15207. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15208. internalTexture._comparisonFunction = comparisonFunction;
  15209. var gl = this._gl;
  15210. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15211. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15212. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15213. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15214. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15215. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15216. if (comparisonFunction === 0) {
  15217. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15218. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15219. }
  15220. else {
  15221. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15222. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15223. }
  15224. };
  15225. /**
  15226. * Creates a depth stencil texture.
  15227. * This is only available in WebGL 2 or with the depth texture extension available.
  15228. * @param size The size of face edge in the texture.
  15229. * @param options The options defining the texture.
  15230. * @returns The texture
  15231. */
  15232. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15233. if (options.isCube) {
  15234. var width = size.width || size;
  15235. return this._createDepthStencilCubeTexture(width, options);
  15236. }
  15237. else {
  15238. return this._createDepthStencilTexture(size, options);
  15239. }
  15240. };
  15241. /**
  15242. * Creates a depth stencil texture.
  15243. * This is only available in WebGL 2 or with the depth texture extension available.
  15244. * @param size The size of face edge in the texture.
  15245. * @param options The options defining the texture.
  15246. * @returns The texture
  15247. */
  15248. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15249. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15250. if (!this._caps.depthTextureExtension) {
  15251. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15252. return internalTexture;
  15253. }
  15254. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15255. var gl = this._gl;
  15256. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15257. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15258. if (this.webGLVersion > 1) {
  15259. if (internalOptions.generateStencil) {
  15260. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15261. }
  15262. else {
  15263. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15264. }
  15265. }
  15266. else {
  15267. if (internalOptions.generateStencil) {
  15268. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15269. }
  15270. else {
  15271. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15272. }
  15273. }
  15274. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15275. return internalTexture;
  15276. };
  15277. /**
  15278. * Creates a depth stencil cube texture.
  15279. * This is only available in WebGL 2.
  15280. * @param size The size of face edge in the cube texture.
  15281. * @param options The options defining the cube texture.
  15282. * @returns The cube texture
  15283. */
  15284. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15285. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15286. internalTexture.isCube = true;
  15287. if (this.webGLVersion === 1) {
  15288. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15289. return internalTexture;
  15290. }
  15291. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15292. var gl = this._gl;
  15293. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15294. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15295. // Create the depth/stencil buffer
  15296. for (var face = 0; face < 6; face++) {
  15297. if (internalOptions.generateStencil) {
  15298. 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);
  15299. }
  15300. else {
  15301. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15302. }
  15303. }
  15304. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15305. return internalTexture;
  15306. };
  15307. /**
  15308. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15309. * @param renderTarget The render target to set the frame buffer for
  15310. */
  15311. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15312. // Create the framebuffer
  15313. var internalTexture = renderTarget.getInternalTexture();
  15314. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15315. return;
  15316. }
  15317. var gl = this._gl;
  15318. var depthStencilTexture = renderTarget.depthStencilTexture;
  15319. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15320. if (depthStencilTexture.isCube) {
  15321. if (depthStencilTexture._generateStencilBuffer) {
  15322. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15323. }
  15324. else {
  15325. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15326. }
  15327. }
  15328. else {
  15329. if (depthStencilTexture._generateStencilBuffer) {
  15330. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15331. }
  15332. else {
  15333. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15334. }
  15335. }
  15336. this.bindUnboundFramebuffer(null);
  15337. };
  15338. /**
  15339. * Creates a new render target texture
  15340. * @param size defines the size of the texture
  15341. * @param options defines the options used to create the texture
  15342. * @returns a new render target texture stored in an InternalTexture
  15343. */
  15344. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15345. var fullOptions = new RenderTargetCreationOptions();
  15346. if (options !== undefined && typeof options === "object") {
  15347. fullOptions.generateMipMaps = options.generateMipMaps;
  15348. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15349. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15350. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15351. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15352. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15353. }
  15354. else {
  15355. fullOptions.generateMipMaps = options;
  15356. fullOptions.generateDepthBuffer = true;
  15357. fullOptions.generateStencilBuffer = false;
  15358. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15359. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15360. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15361. }
  15362. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15363. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15364. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15365. }
  15366. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15367. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15368. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15369. }
  15370. var gl = this._gl;
  15371. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15372. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15373. var width = size.width || size;
  15374. var height = size.height || size;
  15375. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15376. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15377. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15378. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15379. }
  15380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15381. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15382. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15383. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15384. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15385. // Create the framebuffer
  15386. var currentFrameBuffer = this._currentFramebuffer;
  15387. var framebuffer = gl.createFramebuffer();
  15388. this.bindUnboundFramebuffer(framebuffer);
  15389. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15390. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15391. if (fullOptions.generateMipMaps) {
  15392. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15393. }
  15394. // Unbind
  15395. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15396. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15397. this.bindUnboundFramebuffer(currentFrameBuffer);
  15398. texture._framebuffer = framebuffer;
  15399. texture.baseWidth = width;
  15400. texture.baseHeight = height;
  15401. texture.width = width;
  15402. texture.height = height;
  15403. texture.isReady = true;
  15404. texture.samples = 1;
  15405. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15406. texture.samplingMode = fullOptions.samplingMode;
  15407. texture.type = fullOptions.type;
  15408. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15409. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15410. // this.resetTextureCache();
  15411. this._internalTexturesCache.push(texture);
  15412. return texture;
  15413. };
  15414. /**
  15415. * Create a multi render target texture
  15416. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15417. * @param size defines the size of the texture
  15418. * @param options defines the creation options
  15419. * @returns the cube texture as an InternalTexture
  15420. */
  15421. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15422. var generateMipMaps = false;
  15423. var generateDepthBuffer = true;
  15424. var generateStencilBuffer = false;
  15425. var generateDepthTexture = false;
  15426. var textureCount = 1;
  15427. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15428. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15429. var types = new Array();
  15430. var samplingModes = new Array();
  15431. if (options !== undefined) {
  15432. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15433. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15434. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15435. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15436. textureCount = options.textureCount || 1;
  15437. if (options.types) {
  15438. types = options.types;
  15439. }
  15440. if (options.samplingModes) {
  15441. samplingModes = options.samplingModes;
  15442. }
  15443. }
  15444. var gl = this._gl;
  15445. // Create the framebuffer
  15446. var framebuffer = gl.createFramebuffer();
  15447. this.bindUnboundFramebuffer(framebuffer);
  15448. var width = size.width || size;
  15449. var height = size.height || size;
  15450. var textures = [];
  15451. var attachments = [];
  15452. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15453. for (var i = 0; i < textureCount; i++) {
  15454. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15455. var type = types[i] || defaultType;
  15456. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15457. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15458. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15459. }
  15460. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15461. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15462. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15463. }
  15464. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15465. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15466. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15467. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15468. }
  15469. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15470. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15471. textures.push(texture);
  15472. attachments.push(attachment);
  15473. gl.activeTexture(gl["TEXTURE" + i]);
  15474. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15475. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15476. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15478. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15479. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15480. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15481. if (generateMipMaps) {
  15482. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15483. }
  15484. // Unbind
  15485. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15486. texture._framebuffer = framebuffer;
  15487. texture._depthStencilBuffer = depthStencilBuffer;
  15488. texture.baseWidth = width;
  15489. texture.baseHeight = height;
  15490. texture.width = width;
  15491. texture.height = height;
  15492. texture.isReady = true;
  15493. texture.samples = 1;
  15494. texture.generateMipMaps = generateMipMaps;
  15495. texture.samplingMode = samplingMode;
  15496. texture.type = type;
  15497. texture._generateDepthBuffer = generateDepthBuffer;
  15498. texture._generateStencilBuffer = generateStencilBuffer;
  15499. texture._attachments = attachments;
  15500. this._internalTexturesCache.push(texture);
  15501. }
  15502. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15503. // Depth texture
  15504. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15505. gl.activeTexture(gl.TEXTURE0);
  15506. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15510. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15511. 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);
  15512. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15513. depthTexture._framebuffer = framebuffer;
  15514. depthTexture.baseWidth = width;
  15515. depthTexture.baseHeight = height;
  15516. depthTexture.width = width;
  15517. depthTexture.height = height;
  15518. depthTexture.isReady = true;
  15519. depthTexture.samples = 1;
  15520. depthTexture.generateMipMaps = generateMipMaps;
  15521. depthTexture.samplingMode = gl.NEAREST;
  15522. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15523. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15524. textures.push(depthTexture);
  15525. this._internalTexturesCache.push(depthTexture);
  15526. }
  15527. gl.drawBuffers(attachments);
  15528. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15529. this.bindUnboundFramebuffer(null);
  15530. this.resetTextureCache();
  15531. return textures;
  15532. };
  15533. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15534. if (samples === void 0) { samples = 1; }
  15535. var depthStencilBuffer = null;
  15536. var gl = this._gl;
  15537. // Create the depth/stencil buffer
  15538. if (generateStencilBuffer) {
  15539. depthStencilBuffer = gl.createRenderbuffer();
  15540. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15541. if (samples > 1) {
  15542. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15543. }
  15544. else {
  15545. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15546. }
  15547. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15548. }
  15549. else if (generateDepthBuffer) {
  15550. depthStencilBuffer = gl.createRenderbuffer();
  15551. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15552. if (samples > 1) {
  15553. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15554. }
  15555. else {
  15556. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15557. }
  15558. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15559. }
  15560. return depthStencilBuffer;
  15561. };
  15562. /**
  15563. * Updates the sample count of a render target texture
  15564. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15565. * @param texture defines the texture to update
  15566. * @param samples defines the sample count to set
  15567. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15568. */
  15569. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15570. if (this.webGLVersion < 2 || !texture) {
  15571. return 1;
  15572. }
  15573. if (texture.samples === samples) {
  15574. return samples;
  15575. }
  15576. var gl = this._gl;
  15577. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15578. // Dispose previous render buffers
  15579. if (texture._depthStencilBuffer) {
  15580. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15581. texture._depthStencilBuffer = null;
  15582. }
  15583. if (texture._MSAAFramebuffer) {
  15584. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15585. texture._MSAAFramebuffer = null;
  15586. }
  15587. if (texture._MSAARenderBuffer) {
  15588. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15589. texture._MSAARenderBuffer = null;
  15590. }
  15591. if (samples > 1) {
  15592. var framebuffer = gl.createFramebuffer();
  15593. if (!framebuffer) {
  15594. throw new Error("Unable to create multi sampled framebuffer");
  15595. }
  15596. texture._MSAAFramebuffer = framebuffer;
  15597. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15598. var colorRenderbuffer = gl.createRenderbuffer();
  15599. if (!colorRenderbuffer) {
  15600. throw new Error("Unable to create multi sampled framebuffer");
  15601. }
  15602. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15603. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15604. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15605. texture._MSAARenderBuffer = colorRenderbuffer;
  15606. }
  15607. else {
  15608. this.bindUnboundFramebuffer(texture._framebuffer);
  15609. }
  15610. texture.samples = samples;
  15611. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15612. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15613. this.bindUnboundFramebuffer(null);
  15614. return samples;
  15615. };
  15616. /**
  15617. * Update the sample count for a given multiple render target texture
  15618. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15619. * @param textures defines the textures to update
  15620. * @param samples defines the sample count to set
  15621. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15622. */
  15623. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15624. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15625. return 1;
  15626. }
  15627. if (textures[0].samples === samples) {
  15628. return samples;
  15629. }
  15630. var gl = this._gl;
  15631. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15632. // Dispose previous render buffers
  15633. if (textures[0]._depthStencilBuffer) {
  15634. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15635. textures[0]._depthStencilBuffer = null;
  15636. }
  15637. if (textures[0]._MSAAFramebuffer) {
  15638. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15639. textures[0]._MSAAFramebuffer = null;
  15640. }
  15641. for (var i = 0; i < textures.length; i++) {
  15642. if (textures[i]._MSAARenderBuffer) {
  15643. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15644. textures[i]._MSAARenderBuffer = null;
  15645. }
  15646. }
  15647. if (samples > 1) {
  15648. var framebuffer = gl.createFramebuffer();
  15649. if (!framebuffer) {
  15650. throw new Error("Unable to create multi sampled framebuffer");
  15651. }
  15652. this.bindUnboundFramebuffer(framebuffer);
  15653. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15654. var attachments = [];
  15655. for (var i = 0; i < textures.length; i++) {
  15656. var texture = textures[i];
  15657. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15658. var colorRenderbuffer = gl.createRenderbuffer();
  15659. if (!colorRenderbuffer) {
  15660. throw new Error("Unable to create multi sampled framebuffer");
  15661. }
  15662. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15663. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15664. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15665. texture._MSAAFramebuffer = framebuffer;
  15666. texture._MSAARenderBuffer = colorRenderbuffer;
  15667. texture.samples = samples;
  15668. texture._depthStencilBuffer = depthStencilBuffer;
  15669. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15670. attachments.push(attachment);
  15671. }
  15672. gl.drawBuffers(attachments);
  15673. }
  15674. else {
  15675. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15676. }
  15677. this.bindUnboundFramebuffer(null);
  15678. return samples;
  15679. };
  15680. /** @hidden */
  15681. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15682. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15683. };
  15684. /** @hidden */
  15685. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15686. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15687. };
  15688. /** @hidden */
  15689. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15690. var gl = this._gl;
  15691. var textureType = this._getWebGLTextureType(texture.type);
  15692. var format = this._getInternalFormat(texture.format);
  15693. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15694. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15695. this._bindTextureDirectly(bindTarget, texture, true);
  15696. this._unpackFlipY(texture.invertY);
  15697. var target = gl.TEXTURE_2D;
  15698. if (texture.isCube) {
  15699. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15700. }
  15701. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15702. this._bindTextureDirectly(bindTarget, null, true);
  15703. };
  15704. /**
  15705. * Creates a new render target cube texture
  15706. * @param size defines the size of the texture
  15707. * @param options defines the options used to create the texture
  15708. * @returns a new render target cube texture stored in an InternalTexture
  15709. */
  15710. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15711. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15712. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15713. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15714. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15715. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15716. }
  15717. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15718. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15719. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15720. }
  15721. var gl = this._gl;
  15722. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15723. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15724. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15725. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15726. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15727. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15728. }
  15729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15732. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15733. for (var face = 0; face < 6; face++) {
  15734. 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);
  15735. }
  15736. // Create the framebuffer
  15737. var framebuffer = gl.createFramebuffer();
  15738. this.bindUnboundFramebuffer(framebuffer);
  15739. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15740. // MipMaps
  15741. if (fullOptions.generateMipMaps) {
  15742. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15743. }
  15744. // Unbind
  15745. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15746. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15747. this.bindUnboundFramebuffer(null);
  15748. texture._framebuffer = framebuffer;
  15749. texture.width = size;
  15750. texture.height = size;
  15751. texture.isReady = true;
  15752. texture.isCube = true;
  15753. texture.samples = 1;
  15754. texture.generateMipMaps = fullOptions.generateMipMaps;
  15755. texture.samplingMode = fullOptions.samplingMode;
  15756. texture.type = fullOptions.type;
  15757. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15758. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15759. this._internalTexturesCache.push(texture);
  15760. return texture;
  15761. };
  15762. /**
  15763. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15764. * @param rootUrl defines the url where the file to load is located
  15765. * @param scene defines the current scene
  15766. * @param lodScale defines scale to apply to the mip map selection
  15767. * @param lodOffset defines offset to apply to the mip map selection
  15768. * @param onLoad defines an optional callback raised when the texture is loaded
  15769. * @param onError defines an optional callback raised if there is an issue to load the texture
  15770. * @param format defines the format of the data
  15771. * @param forcedExtension defines the extension to use to pick the right loader
  15772. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15773. * @returns the cube texture as an InternalTexture
  15774. */
  15775. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15776. var _this = this;
  15777. if (onLoad === void 0) { onLoad = null; }
  15778. if (onError === void 0) { onError = null; }
  15779. if (forcedExtension === void 0) { forcedExtension = null; }
  15780. if (createPolynomials === void 0) { createPolynomials = true; }
  15781. var callback = function (loadData) {
  15782. if (!loadData) {
  15783. if (onLoad) {
  15784. onLoad(null);
  15785. }
  15786. return;
  15787. }
  15788. var texture = loadData.texture;
  15789. if (!createPolynomials) {
  15790. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15791. }
  15792. else if (loadData.info.sphericalPolynomial) {
  15793. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15794. }
  15795. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15796. if (_this._caps.textureLOD) {
  15797. // Do not add extra process if texture lod is supported.
  15798. if (onLoad) {
  15799. onLoad(texture);
  15800. }
  15801. return;
  15802. }
  15803. var mipSlices = 3;
  15804. var gl = _this._gl;
  15805. var width = loadData.width;
  15806. if (!width) {
  15807. return;
  15808. }
  15809. var textures = [];
  15810. for (var i = 0; i < mipSlices; i++) {
  15811. //compute LOD from even spacing in smoothness (matching shader calculation)
  15812. var smoothness = i / (mipSlices - 1);
  15813. var roughness = 1 - smoothness;
  15814. var minLODIndex = lodOffset; // roughness = 0
  15815. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15816. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15817. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15818. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15819. glTextureFromLod.isCube = true;
  15820. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15825. if (loadData.isDDS) {
  15826. var info = loadData.info;
  15827. var data = loadData.data;
  15828. _this._unpackFlipY(info.isCompressed);
  15829. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15830. }
  15831. else {
  15832. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15833. }
  15834. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15835. // Wrap in a base texture for easy binding.
  15836. var lodTexture = new BABYLON.BaseTexture(scene);
  15837. lodTexture.isCube = true;
  15838. lodTexture._texture = glTextureFromLod;
  15839. glTextureFromLod.isReady = true;
  15840. textures.push(lodTexture);
  15841. }
  15842. texture._lodTextureHigh = textures[2];
  15843. texture._lodTextureMid = textures[1];
  15844. texture._lodTextureLow = textures[0];
  15845. if (onLoad) {
  15846. onLoad(texture);
  15847. }
  15848. };
  15849. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15850. };
  15851. /**
  15852. * Creates a cube texture
  15853. * @param rootUrl defines the url where the files to load is located
  15854. * @param scene defines the current scene
  15855. * @param files defines the list of files to load (1 per face)
  15856. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15857. * @param onLoad defines an optional callback raised when the texture is loaded
  15858. * @param onError defines an optional callback raised if there is an issue to load the texture
  15859. * @param format defines the format of the data
  15860. * @param forcedExtension defines the extension to use to pick the right loader
  15861. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15862. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15863. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15864. * @returns the cube texture as an InternalTexture
  15865. */
  15866. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15867. var _this = this;
  15868. if (onLoad === void 0) { onLoad = null; }
  15869. if (onError === void 0) { onError = null; }
  15870. if (forcedExtension === void 0) { forcedExtension = null; }
  15871. if (createPolynomials === void 0) { createPolynomials = false; }
  15872. if (lodScale === void 0) { lodScale = 0; }
  15873. if (lodOffset === void 0) { lodOffset = 0; }
  15874. var gl = this._gl;
  15875. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15876. texture.isCube = true;
  15877. texture.url = rootUrl;
  15878. texture.generateMipMaps = !noMipmap;
  15879. texture._lodGenerationScale = lodScale;
  15880. texture._lodGenerationOffset = lodOffset;
  15881. if (!this._doNotHandleContextLost) {
  15882. texture._extension = forcedExtension;
  15883. texture._files = files;
  15884. }
  15885. var isKTX = false;
  15886. var isDDS = false;
  15887. var isEnv = false;
  15888. var lastDot = rootUrl.lastIndexOf('.');
  15889. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15890. if (this._textureFormatInUse) {
  15891. extension = this._textureFormatInUse;
  15892. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15893. isKTX = true;
  15894. }
  15895. else {
  15896. isDDS = (extension === ".dds");
  15897. isEnv = (extension === ".env");
  15898. }
  15899. var onerror = function (request, exception) {
  15900. if (onError && request) {
  15901. onError(request.status + " " + request.statusText, exception);
  15902. }
  15903. };
  15904. if (isKTX) {
  15905. this._loadFile(rootUrl, function (data) {
  15906. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15907. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15908. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15909. _this._unpackFlipY(true);
  15910. ktx.uploadLevels(_this._gl, !noMipmap);
  15911. _this.setCubeMapTextureParams(gl, loadMipmap);
  15912. texture.width = ktx.pixelWidth;
  15913. texture.height = ktx.pixelHeight;
  15914. texture.isReady = true;
  15915. }, undefined, undefined, true, onerror);
  15916. }
  15917. else if (isEnv) {
  15918. this._loadFile(rootUrl, function (data) {
  15919. data = data;
  15920. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15921. if (info) {
  15922. texture.width = info.width;
  15923. texture.height = info.width;
  15924. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15925. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15926. texture.isReady = true;
  15927. if (onLoad) {
  15928. onLoad();
  15929. }
  15930. });
  15931. }
  15932. else if (onError) {
  15933. onError("Can not parse the environment file", null);
  15934. }
  15935. }, undefined, undefined, true, onerror);
  15936. }
  15937. else if (isDDS) {
  15938. if (files && files.length === 6) {
  15939. this._cascadeLoadFiles(scene, function (imgs) {
  15940. var info;
  15941. var loadMipmap = false;
  15942. var width = 0;
  15943. for (var index = 0; index < imgs.length; index++) {
  15944. var data = imgs[index];
  15945. info = BABYLON.DDSTools.GetDDSInfo(data);
  15946. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15947. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15948. _this._unpackFlipY(info.isCompressed);
  15949. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15950. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15951. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15952. }
  15953. texture.width = info.width;
  15954. texture.height = info.height;
  15955. texture.type = info.textureType;
  15956. width = info.width;
  15957. }
  15958. _this.setCubeMapTextureParams(gl, loadMipmap);
  15959. texture.isReady = true;
  15960. if (onLoad) {
  15961. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15962. }
  15963. }, files, onError);
  15964. }
  15965. else {
  15966. this._loadFile(rootUrl, function (data) {
  15967. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15968. if (createPolynomials) {
  15969. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15970. }
  15971. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15972. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15973. _this._unpackFlipY(info.isCompressed);
  15974. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15975. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15976. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15977. }
  15978. _this.setCubeMapTextureParams(gl, loadMipmap);
  15979. texture.width = info.width;
  15980. texture.height = info.height;
  15981. texture.isReady = true;
  15982. texture.type = info.textureType;
  15983. if (onLoad) {
  15984. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15985. }
  15986. }, undefined, undefined, true, onerror);
  15987. }
  15988. }
  15989. else {
  15990. if (!files) {
  15991. throw new Error("Cannot load cubemap because files were not defined");
  15992. }
  15993. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15994. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15995. var height = width;
  15996. _this._prepareWorkingCanvas();
  15997. if (!_this._workingCanvas || !_this._workingContext) {
  15998. return;
  15999. }
  16000. _this._workingCanvas.width = width;
  16001. _this._workingCanvas.height = height;
  16002. var faces = [
  16003. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16004. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16005. ];
  16006. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16007. _this._unpackFlipY(false);
  16008. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16009. for (var index = 0; index < faces.length; index++) {
  16010. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16011. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16012. }
  16013. if (!noMipmap) {
  16014. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16015. }
  16016. _this.setCubeMapTextureParams(gl, !noMipmap);
  16017. texture.width = width;
  16018. texture.height = height;
  16019. texture.isReady = true;
  16020. if (format) {
  16021. texture.format = format;
  16022. }
  16023. texture.onLoadedObservable.notifyObservers(texture);
  16024. texture.onLoadedObservable.clear();
  16025. if (onLoad) {
  16026. onLoad();
  16027. }
  16028. }, files, onError);
  16029. }
  16030. this._internalTexturesCache.push(texture);
  16031. return texture;
  16032. };
  16033. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  16034. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16038. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16039. // this.resetTextureCache();
  16040. };
  16041. /**
  16042. * Update a raw cube texture
  16043. * @param texture defines the texture to udpdate
  16044. * @param data defines the data to store
  16045. * @param format defines the data format
  16046. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16047. * @param invertY defines if data must be stored with Y axis inverted
  16048. * @param compression defines the compression used (null by default)
  16049. * @param level defines which level of the texture to update
  16050. */
  16051. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16052. if (compression === void 0) { compression = null; }
  16053. if (level === void 0) { level = 0; }
  16054. texture._bufferViewArray = data;
  16055. texture.format = format;
  16056. texture.type = type;
  16057. texture.invertY = invertY;
  16058. texture._compression = compression;
  16059. var gl = this._gl;
  16060. var textureType = this._getWebGLTextureType(type);
  16061. var internalFormat = this._getInternalFormat(format);
  16062. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16063. var needConversion = false;
  16064. if (internalFormat === gl.RGB) {
  16065. internalFormat = gl.RGBA;
  16066. needConversion = true;
  16067. }
  16068. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16069. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16070. if (texture.width % 4 !== 0) {
  16071. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16072. }
  16073. // Data are known to be in +X +Y +Z -X -Y -Z
  16074. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16075. var faceData = data[faceIndex];
  16076. if (compression) {
  16077. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16078. }
  16079. else {
  16080. if (needConversion) {
  16081. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16082. }
  16083. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16084. }
  16085. }
  16086. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16087. if (isPot && texture.generateMipMaps && level === 0) {
  16088. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16089. }
  16090. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16091. // this.resetTextureCache();
  16092. texture.isReady = true;
  16093. };
  16094. /**
  16095. * Creates a new raw cube texture
  16096. * @param data defines the array of data to use to create each face
  16097. * @param size defines the size of the textures
  16098. * @param format defines the format of the data
  16099. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16100. * @param generateMipMaps defines if the engine should generate the mip levels
  16101. * @param invertY defines if data must be stored with Y axis inverted
  16102. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16103. * @param compression defines the compression used (null by default)
  16104. * @returns the cube texture as an InternalTexture
  16105. */
  16106. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16107. if (compression === void 0) { compression = null; }
  16108. var gl = this._gl;
  16109. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16110. texture.isCube = true;
  16111. texture.generateMipMaps = generateMipMaps;
  16112. texture.format = format;
  16113. texture.type = type;
  16114. if (!this._doNotHandleContextLost) {
  16115. texture._bufferViewArray = data;
  16116. }
  16117. var textureType = this._getWebGLTextureType(type);
  16118. var internalFormat = this._getInternalFormat(format);
  16119. if (internalFormat === gl.RGB) {
  16120. internalFormat = gl.RGBA;
  16121. }
  16122. var width = size;
  16123. var height = width;
  16124. texture.width = width;
  16125. texture.height = height;
  16126. // Double check on POT to generate Mips.
  16127. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16128. if (!isPot) {
  16129. generateMipMaps = false;
  16130. }
  16131. // Upload data if needed. The texture won't be ready until then.
  16132. if (data) {
  16133. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16134. }
  16135. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16136. // Filters
  16137. if (data && generateMipMaps) {
  16138. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16139. }
  16140. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16141. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16142. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16143. }
  16144. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16145. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16146. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16147. }
  16148. else {
  16149. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16152. }
  16153. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16154. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16155. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16156. return texture;
  16157. };
  16158. /**
  16159. * Creates a new raw cube texture from a specified url
  16160. * @param url defines the url where the data is located
  16161. * @param scene defines the current scene
  16162. * @param size defines the size of the textures
  16163. * @param format defines the format of the data
  16164. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16165. * @param noMipmap defines if the engine should avoid generating the mip levels
  16166. * @param callback defines a callback used to extract texture data from loaded data
  16167. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16168. * @param onLoad defines a callback called when texture is loaded
  16169. * @param onError defines a callback called if there is an error
  16170. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16171. * @param invertY defines if data must be stored with Y axis inverted
  16172. * @returns the cube texture as an InternalTexture
  16173. */
  16174. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16175. var _this = this;
  16176. if (onLoad === void 0) { onLoad = null; }
  16177. if (onError === void 0) { onError = null; }
  16178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16179. if (invertY === void 0) { invertY = false; }
  16180. var gl = this._gl;
  16181. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16182. scene._addPendingData(texture);
  16183. texture.url = url;
  16184. this._internalTexturesCache.push(texture);
  16185. var onerror = function (request, exception) {
  16186. scene._removePendingData(texture);
  16187. if (onError && request) {
  16188. onError(request.status + " " + request.statusText, exception);
  16189. }
  16190. };
  16191. var internalCallback = function (data) {
  16192. var width = texture.width;
  16193. var faceDataArrays = callback(data);
  16194. if (!faceDataArrays) {
  16195. return;
  16196. }
  16197. if (mipmapGenerator) {
  16198. var textureType = _this._getWebGLTextureType(type);
  16199. var internalFormat = _this._getInternalFormat(format);
  16200. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16201. var needConversion = false;
  16202. if (internalFormat === gl.RGB) {
  16203. internalFormat = gl.RGBA;
  16204. needConversion = true;
  16205. }
  16206. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16207. _this._unpackFlipY(false);
  16208. var mipData = mipmapGenerator(faceDataArrays);
  16209. for (var level = 0; level < mipData.length; level++) {
  16210. var mipSize = width >> level;
  16211. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16212. var mipFaceData = mipData[level][faceIndex];
  16213. if (needConversion) {
  16214. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16215. }
  16216. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16217. }
  16218. }
  16219. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16220. }
  16221. else {
  16222. texture.generateMipMaps = !noMipmap;
  16223. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16224. }
  16225. texture.isReady = true;
  16226. // this.resetTextureCache();
  16227. scene._removePendingData(texture);
  16228. if (onLoad) {
  16229. onLoad();
  16230. }
  16231. };
  16232. this._loadFile(url, function (data) {
  16233. internalCallback(data);
  16234. }, undefined, scene.database, true, onerror);
  16235. return texture;
  16236. };
  16237. ;
  16238. /**
  16239. * Update a raw 3D texture
  16240. * @param texture defines the texture to update
  16241. * @param data defines the data to store
  16242. * @param format defines the data format
  16243. * @param invertY defines if data must be stored with Y axis inverted
  16244. * @param compression defines the used compression (can be null)
  16245. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16246. */
  16247. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16248. if (compression === void 0) { compression = null; }
  16249. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16250. var internalType = this._getWebGLTextureType(textureType);
  16251. var internalFormat = this._getInternalFormat(format);
  16252. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16253. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16254. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16255. if (!this._doNotHandleContextLost) {
  16256. texture._bufferView = data;
  16257. texture.format = format;
  16258. texture.invertY = invertY;
  16259. texture._compression = compression;
  16260. }
  16261. if (texture.width % 4 !== 0) {
  16262. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16263. }
  16264. if (compression && data) {
  16265. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16266. }
  16267. else {
  16268. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16269. }
  16270. if (texture.generateMipMaps) {
  16271. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16272. }
  16273. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16274. // this.resetTextureCache();
  16275. texture.isReady = true;
  16276. };
  16277. /**
  16278. * Creates a new raw 3D texture
  16279. * @param data defines the data used to create the texture
  16280. * @param width defines the width of the texture
  16281. * @param height defines the height of the texture
  16282. * @param depth defines the depth of the texture
  16283. * @param format defines the format of the texture
  16284. * @param generateMipMaps defines if the engine must generate mip levels
  16285. * @param invertY defines if data must be stored with Y axis inverted
  16286. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16287. * @param compression defines the compressed used (can be null)
  16288. * @param textureType defines the compressed used (can be null)
  16289. * @returns a new raw 3D texture (stored in an InternalTexture)
  16290. */
  16291. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16292. if (compression === void 0) { compression = null; }
  16293. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16294. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16295. texture.baseWidth = width;
  16296. texture.baseHeight = height;
  16297. texture.baseDepth = depth;
  16298. texture.width = width;
  16299. texture.height = height;
  16300. texture.depth = depth;
  16301. texture.format = format;
  16302. texture.type = textureType;
  16303. texture.generateMipMaps = generateMipMaps;
  16304. texture.samplingMode = samplingMode;
  16305. texture.is3D = true;
  16306. if (!this._doNotHandleContextLost) {
  16307. texture._bufferView = data;
  16308. }
  16309. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16310. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16311. // Filters
  16312. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16313. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16314. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16315. if (generateMipMaps) {
  16316. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16317. }
  16318. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16319. this._internalTexturesCache.push(texture);
  16320. return texture;
  16321. };
  16322. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16323. var gl = this._gl;
  16324. if (!gl) {
  16325. return;
  16326. }
  16327. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16328. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16329. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16330. if (!noMipmap && !isCompressed) {
  16331. gl.generateMipmap(gl.TEXTURE_2D);
  16332. }
  16333. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16334. // this.resetTextureCache();
  16335. if (scene) {
  16336. scene._removePendingData(texture);
  16337. }
  16338. texture.onLoadedObservable.notifyObservers(texture);
  16339. texture.onLoadedObservable.clear();
  16340. };
  16341. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16342. var _this = this;
  16343. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16344. var maxTextureSize = this.getCaps().maxTextureSize;
  16345. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16346. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16347. var gl = this._gl;
  16348. if (!gl) {
  16349. return;
  16350. }
  16351. if (!texture._webGLTexture) {
  16352. // this.resetTextureCache();
  16353. if (scene) {
  16354. scene._removePendingData(texture);
  16355. }
  16356. return;
  16357. }
  16358. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16359. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16360. texture.baseWidth = width;
  16361. texture.baseHeight = height;
  16362. texture.width = potWidth;
  16363. texture.height = potHeight;
  16364. texture.isReady = true;
  16365. if (processFunction(potWidth, potHeight, function () {
  16366. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16367. })) {
  16368. // Returning as texture needs extra async steps
  16369. return;
  16370. }
  16371. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16372. };
  16373. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16374. // Create new RGBA data container.
  16375. var rgbaData;
  16376. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16377. rgbaData = new Float32Array(width * height * 4);
  16378. }
  16379. else {
  16380. rgbaData = new Uint32Array(width * height * 4);
  16381. }
  16382. // Convert each pixel.
  16383. for (var x = 0; x < width; x++) {
  16384. for (var y = 0; y < height; y++) {
  16385. var index = (y * width + x) * 3;
  16386. var newIndex = (y * width + x) * 4;
  16387. // Map Old Value to new value.
  16388. rgbaData[newIndex + 0] = rgbData[index + 0];
  16389. rgbaData[newIndex + 1] = rgbData[index + 1];
  16390. rgbaData[newIndex + 2] = rgbData[index + 2];
  16391. // Add fully opaque alpha channel.
  16392. rgbaData[newIndex + 3] = 1;
  16393. }
  16394. }
  16395. return rgbaData;
  16396. };
  16397. /** @hidden */
  16398. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16399. var gl = this._gl;
  16400. if (texture._framebuffer) {
  16401. gl.deleteFramebuffer(texture._framebuffer);
  16402. texture._framebuffer = null;
  16403. }
  16404. if (texture._depthStencilBuffer) {
  16405. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16406. texture._depthStencilBuffer = null;
  16407. }
  16408. if (texture._MSAAFramebuffer) {
  16409. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16410. texture._MSAAFramebuffer = null;
  16411. }
  16412. if (texture._MSAARenderBuffer) {
  16413. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16414. texture._MSAARenderBuffer = null;
  16415. }
  16416. };
  16417. /** @hidden */
  16418. Engine.prototype._releaseTexture = function (texture) {
  16419. var gl = this._gl;
  16420. this._releaseFramebufferObjects(texture);
  16421. gl.deleteTexture(texture._webGLTexture);
  16422. // Unbind channels
  16423. this.unbindAllTextures();
  16424. var index = this._internalTexturesCache.indexOf(texture);
  16425. if (index !== -1) {
  16426. this._internalTexturesCache.splice(index, 1);
  16427. }
  16428. // Integrated fixed lod samplers.
  16429. if (texture._lodTextureHigh) {
  16430. texture._lodTextureHigh.dispose();
  16431. }
  16432. if (texture._lodTextureMid) {
  16433. texture._lodTextureMid.dispose();
  16434. }
  16435. if (texture._lodTextureLow) {
  16436. texture._lodTextureLow.dispose();
  16437. }
  16438. // Set output texture of post process to null if the texture has been released/disposed
  16439. this.scenes.forEach(function (scene) {
  16440. scene.postProcesses.forEach(function (postProcess) {
  16441. if (postProcess._outputTexture == texture) {
  16442. postProcess._outputTexture = null;
  16443. }
  16444. });
  16445. scene.cameras.forEach(function (camera) {
  16446. camera._postProcesses.forEach(function (postProcess) {
  16447. if (postProcess) {
  16448. if (postProcess._outputTexture == texture) {
  16449. postProcess._outputTexture = null;
  16450. }
  16451. }
  16452. });
  16453. });
  16454. });
  16455. };
  16456. Engine.prototype.setProgram = function (program) {
  16457. if (this._currentProgram !== program) {
  16458. this._gl.useProgram(program);
  16459. this._currentProgram = program;
  16460. }
  16461. };
  16462. /**
  16463. * Binds an effect to the webGL context
  16464. * @param effect defines the effect to bind
  16465. */
  16466. Engine.prototype.bindSamplers = function (effect) {
  16467. this.setProgram(effect.getProgram());
  16468. var samplers = effect.getSamplers();
  16469. for (var index = 0; index < samplers.length; index++) {
  16470. var uniform = effect.getUniform(samplers[index]);
  16471. if (uniform) {
  16472. this._boundUniforms[index] = uniform;
  16473. }
  16474. }
  16475. this._currentEffect = null;
  16476. };
  16477. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16478. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16479. return;
  16480. }
  16481. // Remove
  16482. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16483. // Bind last to it
  16484. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16485. // Bind to dummy
  16486. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16487. };
  16488. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16489. if (!internalTexture) {
  16490. return -1;
  16491. }
  16492. internalTexture._initialSlot = channel;
  16493. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16494. if (channel !== internalTexture._designatedSlot) {
  16495. this._textureCollisions.addCount(1, false);
  16496. }
  16497. }
  16498. else {
  16499. if (channel !== internalTexture._designatedSlot) {
  16500. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16501. return internalTexture._designatedSlot;
  16502. }
  16503. else {
  16504. // No slot for this texture, let's pick a new one (if we find a free slot)
  16505. if (this._nextFreeTextureSlots.length) {
  16506. return this._nextFreeTextureSlots[0];
  16507. }
  16508. // We need to recycle the oldest bound texture, sorry.
  16509. this._textureCollisions.addCount(1, false);
  16510. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16511. }
  16512. }
  16513. }
  16514. return channel;
  16515. };
  16516. Engine.prototype._linkTrackers = function (previous, next) {
  16517. previous.next = next;
  16518. next.previous = previous;
  16519. };
  16520. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16521. var currentSlot = internalTexture._designatedSlot;
  16522. if (currentSlot === -1) {
  16523. return -1;
  16524. }
  16525. internalTexture._designatedSlot = -1;
  16526. if (this.disableTextureBindingOptimization) {
  16527. return -1;
  16528. }
  16529. // Remove from bound list
  16530. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16531. // Free the slot
  16532. this._boundTexturesCache[currentSlot] = null;
  16533. this._nextFreeTextureSlots.push(currentSlot);
  16534. return currentSlot;
  16535. };
  16536. Engine.prototype._activateCurrentTexture = function () {
  16537. if (this._currentTextureChannel !== this._activeChannel) {
  16538. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16539. this._currentTextureChannel = this._activeChannel;
  16540. }
  16541. };
  16542. /** @hidden */
  16543. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16544. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16545. if (force === void 0) { force = false; }
  16546. var wasPreviouslyBound = false;
  16547. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16548. this._activeChannel = texture._designatedSlot;
  16549. }
  16550. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16551. var isTextureForRendering = texture && texture._initialSlot > -1;
  16552. if (currentTextureBound !== texture || force) {
  16553. if (currentTextureBound) {
  16554. this._removeDesignatedSlot(currentTextureBound);
  16555. }
  16556. this._activateCurrentTexture();
  16557. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16558. this._boundTexturesCache[this._activeChannel] = texture;
  16559. if (texture) {
  16560. if (!this.disableTextureBindingOptimization) {
  16561. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16562. if (slotIndex > -1) {
  16563. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16564. }
  16565. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16566. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16567. }
  16568. texture._designatedSlot = this._activeChannel;
  16569. }
  16570. }
  16571. else if (forTextureDataUpdate) {
  16572. wasPreviouslyBound = true;
  16573. this._activateCurrentTexture();
  16574. }
  16575. if (isTextureForRendering && !forTextureDataUpdate) {
  16576. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16577. }
  16578. return wasPreviouslyBound;
  16579. };
  16580. /** @hidden */
  16581. Engine.prototype._bindTexture = function (channel, texture) {
  16582. if (channel < 0) {
  16583. return;
  16584. }
  16585. if (texture) {
  16586. channel = this._getCorrectTextureChannel(channel, texture);
  16587. }
  16588. this._activeChannel = channel;
  16589. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16590. };
  16591. /**
  16592. * Sets a texture to the webGL context from a postprocess
  16593. * @param channel defines the channel to use
  16594. * @param postProcess defines the source postprocess
  16595. */
  16596. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16597. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16598. };
  16599. /**
  16600. * Binds the output of the passed in post process to the texture channel specified
  16601. * @param channel The channel the texture should be bound to
  16602. * @param postProcess The post process which's output should be bound
  16603. */
  16604. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16605. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16606. };
  16607. /**
  16608. * Unbind all textures from the webGL context
  16609. */
  16610. Engine.prototype.unbindAllTextures = function () {
  16611. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16612. this._activeChannel = channel;
  16613. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16614. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16615. if (this.webGLVersion > 1) {
  16616. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16617. }
  16618. }
  16619. };
  16620. /**
  16621. * Sets a texture to the according uniform.
  16622. * @param channel The texture channel
  16623. * @param uniform The uniform to set
  16624. * @param texture The texture to apply
  16625. */
  16626. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16627. if (channel < 0) {
  16628. return;
  16629. }
  16630. if (uniform) {
  16631. this._boundUniforms[channel] = uniform;
  16632. }
  16633. this._setTexture(channel, texture);
  16634. };
  16635. /**
  16636. * Sets a depth stencil texture from a render target to the according uniform.
  16637. * @param channel The texture channel
  16638. * @param uniform The uniform to set
  16639. * @param texture The render target texture containing the depth stencil texture to apply
  16640. */
  16641. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16642. if (channel < 0) {
  16643. return;
  16644. }
  16645. if (uniform) {
  16646. this._boundUniforms[channel] = uniform;
  16647. }
  16648. if (!texture || !texture.depthStencilTexture) {
  16649. this._setTexture(channel, null);
  16650. }
  16651. else {
  16652. this._setTexture(channel, texture, false, true);
  16653. }
  16654. };
  16655. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16656. var uniform = this._boundUniforms[sourceSlot];
  16657. if (uniform._currentState === destination) {
  16658. return;
  16659. }
  16660. this._gl.uniform1i(uniform, destination);
  16661. uniform._currentState = destination;
  16662. };
  16663. Engine.prototype._getTextureWrapMode = function (mode) {
  16664. switch (mode) {
  16665. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16666. return this._gl.REPEAT;
  16667. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16668. return this._gl.CLAMP_TO_EDGE;
  16669. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16670. return this._gl.MIRRORED_REPEAT;
  16671. }
  16672. return this._gl.REPEAT;
  16673. };
  16674. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16675. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16676. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16677. // Not ready?
  16678. if (!texture) {
  16679. if (this._boundTexturesCache[channel] != null) {
  16680. this._activeChannel = channel;
  16681. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16683. if (this.webGLVersion > 1) {
  16684. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16685. }
  16686. }
  16687. return false;
  16688. }
  16689. // Video
  16690. if (texture.video) {
  16691. this._activeChannel = channel;
  16692. texture.update();
  16693. }
  16694. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16695. texture.delayLoad();
  16696. return false;
  16697. }
  16698. var internalTexture;
  16699. if (depthStencilTexture) {
  16700. internalTexture = texture.depthStencilTexture;
  16701. }
  16702. else if (texture.isReady()) {
  16703. internalTexture = texture.getInternalTexture();
  16704. }
  16705. else if (texture.isCube) {
  16706. internalTexture = this.emptyCubeTexture;
  16707. }
  16708. else if (texture.is3D) {
  16709. internalTexture = this.emptyTexture3D;
  16710. }
  16711. else {
  16712. internalTexture = this.emptyTexture;
  16713. }
  16714. if (!isPartOfTextureArray) {
  16715. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16716. }
  16717. var needToBind = true;
  16718. if (this._boundTexturesCache[channel] === internalTexture) {
  16719. this._moveBoundTextureOnTop(internalTexture);
  16720. if (!isPartOfTextureArray) {
  16721. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16722. }
  16723. needToBind = false;
  16724. }
  16725. this._activeChannel = channel;
  16726. if (internalTexture && internalTexture.is3D) {
  16727. if (needToBind) {
  16728. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16729. }
  16730. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16731. internalTexture._cachedWrapU = texture.wrapU;
  16732. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16733. }
  16734. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16735. internalTexture._cachedWrapV = texture.wrapV;
  16736. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16737. }
  16738. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16739. internalTexture._cachedWrapR = texture.wrapR;
  16740. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16741. }
  16742. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16743. }
  16744. else if (internalTexture && internalTexture.isCube) {
  16745. if (needToBind) {
  16746. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16747. }
  16748. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16749. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16750. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16751. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16752. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16753. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16754. }
  16755. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16756. }
  16757. else {
  16758. if (needToBind) {
  16759. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16760. }
  16761. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16762. internalTexture._cachedWrapU = texture.wrapU;
  16763. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16764. }
  16765. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16766. internalTexture._cachedWrapV = texture.wrapV;
  16767. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16768. }
  16769. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16770. }
  16771. return true;
  16772. };
  16773. /**
  16774. * Sets an array of texture to the webGL context
  16775. * @param channel defines the channel where the texture array must be set
  16776. * @param uniform defines the associated uniform location
  16777. * @param textures defines the array of textures to bind
  16778. */
  16779. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16780. if (channel < 0 || !uniform) {
  16781. return;
  16782. }
  16783. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16784. this._textureUnits = new Int32Array(textures.length);
  16785. }
  16786. for (var i = 0; i < textures.length; i++) {
  16787. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16788. }
  16789. this._gl.uniform1iv(uniform, this._textureUnits);
  16790. for (var index = 0; index < textures.length; index++) {
  16791. this._setTexture(this._textureUnits[index], textures[index], true);
  16792. }
  16793. };
  16794. /** @hidden */
  16795. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16796. var internalTexture = texture.getInternalTexture();
  16797. if (!internalTexture) {
  16798. return;
  16799. }
  16800. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16801. var value = texture.anisotropicFilteringLevel;
  16802. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16803. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16804. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16805. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16806. }
  16807. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16808. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16809. internalTexture._cachedAnisotropicFilteringLevel = value;
  16810. }
  16811. };
  16812. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16813. this._bindTextureDirectly(target, texture, true, true);
  16814. this._gl.texParameterf(target, parameter, value);
  16815. };
  16816. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16817. if (texture) {
  16818. this._bindTextureDirectly(target, texture, true, true);
  16819. }
  16820. this._gl.texParameteri(target, parameter, value);
  16821. };
  16822. /**
  16823. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16824. * @param x defines the x coordinate of the rectangle where pixels must be read
  16825. * @param y defines the y coordinate of the rectangle where pixels must be read
  16826. * @param width defines the width of the rectangle where pixels must be read
  16827. * @param height defines the height of the rectangle where pixels must be read
  16828. * @returns a Uint8Array containing RGBA colors
  16829. */
  16830. Engine.prototype.readPixels = function (x, y, width, height) {
  16831. var data = new Uint8Array(height * width * 4);
  16832. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16833. return data;
  16834. };
  16835. /**
  16836. * Add an externaly attached data from its key.
  16837. * This method call will fail and return false, if such key already exists.
  16838. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16839. * @param key the unique key that identifies the data
  16840. * @param data the data object to associate to the key for this Engine instance
  16841. * @return true if no such key were already present and the data was added successfully, false otherwise
  16842. */
  16843. Engine.prototype.addExternalData = function (key, data) {
  16844. if (!this._externalData) {
  16845. this._externalData = new BABYLON.StringDictionary();
  16846. }
  16847. return this._externalData.add(key, data);
  16848. };
  16849. /**
  16850. * Get an externaly attached data from its key
  16851. * @param key the unique key that identifies the data
  16852. * @return the associated data, if present (can be null), or undefined if not present
  16853. */
  16854. Engine.prototype.getExternalData = function (key) {
  16855. if (!this._externalData) {
  16856. this._externalData = new BABYLON.StringDictionary();
  16857. }
  16858. return this._externalData.get(key);
  16859. };
  16860. /**
  16861. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16862. * @param key the unique key that identifies the data
  16863. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16864. * @return the associated data, can be null if the factory returned null.
  16865. */
  16866. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16867. if (!this._externalData) {
  16868. this._externalData = new BABYLON.StringDictionary();
  16869. }
  16870. return this._externalData.getOrAddWithFactory(key, factory);
  16871. };
  16872. /**
  16873. * Remove an externaly attached data from the Engine instance
  16874. * @param key the unique key that identifies the data
  16875. * @return true if the data was successfully removed, false if it doesn't exist
  16876. */
  16877. Engine.prototype.removeExternalData = function (key) {
  16878. if (!this._externalData) {
  16879. this._externalData = new BABYLON.StringDictionary();
  16880. }
  16881. return this._externalData.remove(key);
  16882. };
  16883. /**
  16884. * Unbind all vertex attributes from the webGL context
  16885. */
  16886. Engine.prototype.unbindAllAttributes = function () {
  16887. if (this._mustWipeVertexAttributes) {
  16888. this._mustWipeVertexAttributes = false;
  16889. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16890. this._gl.disableVertexAttribArray(i);
  16891. this._vertexAttribArraysEnabled[i] = false;
  16892. this._currentBufferPointers[i].active = false;
  16893. }
  16894. return;
  16895. }
  16896. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16897. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16898. continue;
  16899. }
  16900. this._gl.disableVertexAttribArray(i);
  16901. this._vertexAttribArraysEnabled[i] = false;
  16902. this._currentBufferPointers[i].active = false;
  16903. }
  16904. };
  16905. /**
  16906. * 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
  16907. */
  16908. Engine.prototype.releaseEffects = function () {
  16909. for (var name in this._compiledEffects) {
  16910. this._deleteProgram(this._compiledEffects[name]._program);
  16911. }
  16912. this._compiledEffects = {};
  16913. };
  16914. /**
  16915. * Dispose and release all associated resources
  16916. */
  16917. Engine.prototype.dispose = function () {
  16918. this.hideLoadingUI();
  16919. this.stopRenderLoop();
  16920. // Release postProcesses
  16921. while (this.postProcesses.length) {
  16922. this.postProcesses[0].dispose();
  16923. }
  16924. // Empty texture
  16925. if (this._emptyTexture) {
  16926. this._releaseTexture(this._emptyTexture);
  16927. this._emptyTexture = null;
  16928. }
  16929. if (this._emptyCubeTexture) {
  16930. this._releaseTexture(this._emptyCubeTexture);
  16931. this._emptyCubeTexture = null;
  16932. }
  16933. // Rescale PP
  16934. if (this._rescalePostProcess) {
  16935. this._rescalePostProcess.dispose();
  16936. }
  16937. // Release scenes
  16938. while (this.scenes.length) {
  16939. this.scenes[0].dispose();
  16940. }
  16941. // Release audio engine
  16942. if (Engine.audioEngine) {
  16943. Engine.audioEngine.dispose();
  16944. }
  16945. // Release effects
  16946. this.releaseEffects();
  16947. // Unbind
  16948. this.unbindAllAttributes();
  16949. this._boundUniforms = [];
  16950. if (this._dummyFramebuffer) {
  16951. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16952. }
  16953. //WebVR
  16954. this.disableVR();
  16955. // Events
  16956. if (BABYLON.Tools.IsWindowObjectExist()) {
  16957. window.removeEventListener("blur", this._onBlur);
  16958. window.removeEventListener("focus", this._onFocus);
  16959. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16960. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16961. if (this._renderingCanvas) {
  16962. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16963. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16964. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16965. if (!this._doNotHandleContextLost) {
  16966. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16967. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16968. }
  16969. }
  16970. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16971. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16972. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16973. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16974. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16975. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16976. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16977. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16978. if (this._onVrDisplayConnect) {
  16979. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16980. if (this._onVrDisplayDisconnect) {
  16981. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16982. }
  16983. if (this._onVrDisplayPresentChange) {
  16984. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16985. }
  16986. this._onVrDisplayConnect = null;
  16987. this._onVrDisplayDisconnect = null;
  16988. }
  16989. }
  16990. // Remove from Instances
  16991. var index = Engine.Instances.indexOf(this);
  16992. if (index >= 0) {
  16993. Engine.Instances.splice(index, 1);
  16994. }
  16995. this._workingCanvas = null;
  16996. this._workingContext = null;
  16997. this._currentBufferPointers = [];
  16998. this._renderingCanvas = null;
  16999. this._currentProgram = null;
  17000. this._bindedRenderFunction = null;
  17001. this.onResizeObservable.clear();
  17002. this.onCanvasBlurObservable.clear();
  17003. this.onCanvasFocusObservable.clear();
  17004. this.onCanvasPointerOutObservable.clear();
  17005. this.onBeginFrameObservable.clear();
  17006. this.onEndFrameObservable.clear();
  17007. BABYLON.Effect.ResetCache();
  17008. // Abort active requests
  17009. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17010. var request = _a[_i];
  17011. request.abort();
  17012. }
  17013. };
  17014. // Loading screen
  17015. /**
  17016. * Display the loading screen
  17017. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17018. */
  17019. Engine.prototype.displayLoadingUI = function () {
  17020. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17021. return;
  17022. }
  17023. var loadingScreen = this.loadingScreen;
  17024. if (loadingScreen) {
  17025. loadingScreen.displayLoadingUI();
  17026. }
  17027. };
  17028. /**
  17029. * Hide the loading screen
  17030. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17031. */
  17032. Engine.prototype.hideLoadingUI = function () {
  17033. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17034. return;
  17035. }
  17036. var loadingScreen = this.loadingScreen;
  17037. if (loadingScreen) {
  17038. loadingScreen.hideLoadingUI();
  17039. }
  17040. };
  17041. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17042. /**
  17043. * Gets the current loading screen object
  17044. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17045. */
  17046. get: function () {
  17047. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17048. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17049. return this._loadingScreen;
  17050. },
  17051. /**
  17052. * Sets the current loading screen object
  17053. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17054. */
  17055. set: function (loadingScreen) {
  17056. this._loadingScreen = loadingScreen;
  17057. },
  17058. enumerable: true,
  17059. configurable: true
  17060. });
  17061. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17062. /**
  17063. * Sets the current loading screen text
  17064. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17065. */
  17066. set: function (text) {
  17067. this.loadingScreen.loadingUIText = text;
  17068. },
  17069. enumerable: true,
  17070. configurable: true
  17071. });
  17072. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17073. /**
  17074. * Sets the current loading screen background color
  17075. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17076. */
  17077. set: function (color) {
  17078. this.loadingScreen.loadingUIBackgroundColor = color;
  17079. },
  17080. enumerable: true,
  17081. configurable: true
  17082. });
  17083. /**
  17084. * Attach a new callback raised when context lost event is fired
  17085. * @param callback defines the callback to call
  17086. */
  17087. Engine.prototype.attachContextLostEvent = function (callback) {
  17088. if (this._renderingCanvas) {
  17089. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17090. }
  17091. };
  17092. /**
  17093. * Attach a new callback raised when context restored event is fired
  17094. * @param callback defines the callback to call
  17095. */
  17096. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17097. if (this._renderingCanvas) {
  17098. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17099. }
  17100. };
  17101. /**
  17102. * Gets the source code of the vertex shader associated with a specific webGL program
  17103. * @param program defines the program to use
  17104. * @returns a string containing the source code of the vertex shader associated with the program
  17105. */
  17106. Engine.prototype.getVertexShaderSource = function (program) {
  17107. var shaders = this._gl.getAttachedShaders(program);
  17108. if (!shaders) {
  17109. return null;
  17110. }
  17111. return this._gl.getShaderSource(shaders[0]);
  17112. };
  17113. /**
  17114. * Gets the source code of the fragment shader associated with a specific webGL program
  17115. * @param program defines the program to use
  17116. * @returns a string containing the source code of the fragment shader associated with the program
  17117. */
  17118. Engine.prototype.getFragmentShaderSource = function (program) {
  17119. var shaders = this._gl.getAttachedShaders(program);
  17120. if (!shaders) {
  17121. return null;
  17122. }
  17123. return this._gl.getShaderSource(shaders[1]);
  17124. };
  17125. /**
  17126. * Get the current error code of the webGL context
  17127. * @returns the error code
  17128. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17129. */
  17130. Engine.prototype.getError = function () {
  17131. return this._gl.getError();
  17132. };
  17133. // FPS
  17134. /**
  17135. * Gets the current framerate
  17136. * @returns a number representing the framerate
  17137. */
  17138. Engine.prototype.getFps = function () {
  17139. return this._fps;
  17140. };
  17141. /**
  17142. * Gets the time spent between current and previous frame
  17143. * @returns a number representing the delta time in ms
  17144. */
  17145. Engine.prototype.getDeltaTime = function () {
  17146. return this._deltaTime;
  17147. };
  17148. Engine.prototype._measureFps = function () {
  17149. this._performanceMonitor.sampleFrame();
  17150. this._fps = this._performanceMonitor.averageFPS;
  17151. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17152. };
  17153. /** @hidden */
  17154. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17155. if (faceIndex === void 0) { faceIndex = -1; }
  17156. if (level === void 0) { level = 0; }
  17157. var gl = this._gl;
  17158. if (!this._dummyFramebuffer) {
  17159. var dummy = gl.createFramebuffer();
  17160. if (!dummy) {
  17161. throw new Error("Unable to create dummy framebuffer");
  17162. }
  17163. this._dummyFramebuffer = dummy;
  17164. }
  17165. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17166. if (faceIndex > -1) {
  17167. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17168. }
  17169. else {
  17170. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17171. }
  17172. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17173. var buffer;
  17174. switch (readType) {
  17175. case gl.UNSIGNED_BYTE:
  17176. buffer = new Uint8Array(4 * width * height);
  17177. readType = gl.UNSIGNED_BYTE;
  17178. break;
  17179. default:
  17180. buffer = new Float32Array(4 * width * height);
  17181. readType = gl.FLOAT;
  17182. break;
  17183. }
  17184. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17185. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17186. return buffer;
  17187. };
  17188. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17189. if (this._webGLVersion > 1) {
  17190. return this._caps.colorBufferFloat;
  17191. }
  17192. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17193. };
  17194. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17195. if (this._webGLVersion > 1) {
  17196. return this._caps.colorBufferFloat;
  17197. }
  17198. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17199. };
  17200. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17201. Engine.prototype._canRenderToFramebuffer = function (type) {
  17202. var gl = this._gl;
  17203. //clear existing errors
  17204. while (gl.getError() !== gl.NO_ERROR) { }
  17205. var successful = true;
  17206. var texture = gl.createTexture();
  17207. gl.bindTexture(gl.TEXTURE_2D, texture);
  17208. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17211. var fb = gl.createFramebuffer();
  17212. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17213. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17214. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17215. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17216. successful = successful && (gl.getError() === gl.NO_ERROR);
  17217. //try render by clearing frame buffer's color buffer
  17218. if (successful) {
  17219. gl.clear(gl.COLOR_BUFFER_BIT);
  17220. successful = successful && (gl.getError() === gl.NO_ERROR);
  17221. }
  17222. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17223. if (successful) {
  17224. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17225. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17226. var readFormat = gl.RGBA;
  17227. var readType = gl.UNSIGNED_BYTE;
  17228. var buffer = new Uint8Array(4);
  17229. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17230. successful = successful && (gl.getError() === gl.NO_ERROR);
  17231. }
  17232. //clean up
  17233. gl.deleteTexture(texture);
  17234. gl.deleteFramebuffer(fb);
  17235. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17236. //clear accumulated errors
  17237. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17238. return successful;
  17239. };
  17240. /** @hidden */
  17241. Engine.prototype._getWebGLTextureType = function (type) {
  17242. if (type === Engine.TEXTURETYPE_FLOAT) {
  17243. return this._gl.FLOAT;
  17244. }
  17245. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17246. // Add Half Float Constant.
  17247. return this._gl.HALF_FLOAT_OES;
  17248. }
  17249. return this._gl.UNSIGNED_BYTE;
  17250. };
  17251. ;
  17252. Engine.prototype._getInternalFormat = function (format) {
  17253. var internalFormat = this._gl.RGBA;
  17254. switch (format) {
  17255. case Engine.TEXTUREFORMAT_ALPHA:
  17256. internalFormat = this._gl.ALPHA;
  17257. break;
  17258. case Engine.TEXTUREFORMAT_LUMINANCE:
  17259. internalFormat = this._gl.LUMINANCE;
  17260. break;
  17261. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17262. internalFormat = this._gl.LUMINANCE_ALPHA;
  17263. break;
  17264. case Engine.TEXTUREFORMAT_RGB:
  17265. internalFormat = this._gl.RGB;
  17266. break;
  17267. case Engine.TEXTUREFORMAT_RGBA:
  17268. internalFormat = this._gl.RGBA;
  17269. break;
  17270. case Engine.TEXTUREFORMAT_R:
  17271. internalFormat = this._gl.RED;
  17272. break;
  17273. case Engine.TEXTUREFORMAT_RG:
  17274. internalFormat = this._gl.RG;
  17275. break;
  17276. }
  17277. return internalFormat;
  17278. };
  17279. /** @hidden */
  17280. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17281. if (this._webGLVersion === 1) {
  17282. if (format !== undefined) {
  17283. switch (format) {
  17284. case Engine.TEXTUREFORMAT_LUMINANCE:
  17285. return this._gl.LUMINANCE;
  17286. case Engine.TEXTUREFORMAT_ALPHA:
  17287. return this._gl.ALPHA;
  17288. }
  17289. }
  17290. return this._gl.RGBA;
  17291. }
  17292. if (type === Engine.TEXTURETYPE_FLOAT) {
  17293. if (format !== undefined) {
  17294. switch (format) {
  17295. case Engine.TEXTUREFORMAT_R:
  17296. return this._gl.R32F;
  17297. case Engine.TEXTUREFORMAT_RG:
  17298. return this._gl.RG32F;
  17299. case Engine.TEXTUREFORMAT_RGB:
  17300. return this._gl.RGB32F;
  17301. }
  17302. }
  17303. return this._gl.RGBA32F;
  17304. }
  17305. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17306. if (format) {
  17307. switch (format) {
  17308. case Engine.TEXTUREFORMAT_R:
  17309. return this._gl.R16F;
  17310. case Engine.TEXTUREFORMAT_RG:
  17311. return this._gl.RG16F;
  17312. case Engine.TEXTUREFORMAT_RGB:
  17313. return this._gl.RGB16F;
  17314. }
  17315. }
  17316. return this._gl.RGBA16F;
  17317. }
  17318. if (format !== undefined) {
  17319. switch (format) {
  17320. case Engine.TEXTUREFORMAT_LUMINANCE:
  17321. return this._gl.LUMINANCE;
  17322. case Engine.TEXTUREFORMAT_RGB:
  17323. return this._gl.RGB;
  17324. case Engine.TEXTUREFORMAT_R:
  17325. return this._gl.R8;
  17326. case Engine.TEXTUREFORMAT_RG:
  17327. return this._gl.RG8;
  17328. case Engine.TEXTUREFORMAT_ALPHA:
  17329. return this._gl.ALPHA;
  17330. }
  17331. }
  17332. return this._gl.RGBA;
  17333. };
  17334. ;
  17335. /** @hidden */
  17336. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17337. if (type === Engine.TEXTURETYPE_FLOAT) {
  17338. return this._gl.RGBA32F;
  17339. }
  17340. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17341. return this._gl.RGBA16F;
  17342. }
  17343. return this._gl.RGBA8;
  17344. };
  17345. ;
  17346. /**
  17347. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17348. * @return the new query
  17349. */
  17350. Engine.prototype.createQuery = function () {
  17351. return this._gl.createQuery();
  17352. };
  17353. /**
  17354. * Delete and release a webGL query
  17355. * @param query defines the query to delete
  17356. * @return the current engine
  17357. */
  17358. Engine.prototype.deleteQuery = function (query) {
  17359. this._gl.deleteQuery(query);
  17360. return this;
  17361. };
  17362. /**
  17363. * Check if a given query has resolved and got its value
  17364. * @param query defines the query to check
  17365. * @returns true if the query got its value
  17366. */
  17367. Engine.prototype.isQueryResultAvailable = function (query) {
  17368. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17369. };
  17370. /**
  17371. * Gets the value of a given query
  17372. * @param query defines the query to check
  17373. * @returns the value of the query
  17374. */
  17375. Engine.prototype.getQueryResult = function (query) {
  17376. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17377. };
  17378. /**
  17379. * Initiates an occlusion query
  17380. * @param algorithmType defines the algorithm to use
  17381. * @param query defines the query to use
  17382. * @returns the current engine
  17383. * @see http://doc.babylonjs.com/features/occlusionquery
  17384. */
  17385. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17386. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17387. this._gl.beginQuery(glAlgorithm, query);
  17388. return this;
  17389. };
  17390. /**
  17391. * Ends an occlusion query
  17392. * @see http://doc.babylonjs.com/features/occlusionquery
  17393. * @param algorithmType defines the algorithm to use
  17394. * @returns the current engine
  17395. */
  17396. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17397. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17398. this._gl.endQuery(glAlgorithm);
  17399. return this;
  17400. };
  17401. /* Time queries */
  17402. Engine.prototype._createTimeQuery = function () {
  17403. var timerQuery = this._caps.timerQuery;
  17404. if (timerQuery.createQueryEXT) {
  17405. return timerQuery.createQueryEXT();
  17406. }
  17407. return this.createQuery();
  17408. };
  17409. Engine.prototype._deleteTimeQuery = function (query) {
  17410. var timerQuery = this._caps.timerQuery;
  17411. if (timerQuery.deleteQueryEXT) {
  17412. timerQuery.deleteQueryEXT(query);
  17413. return;
  17414. }
  17415. this.deleteQuery(query);
  17416. };
  17417. Engine.prototype._getTimeQueryResult = function (query) {
  17418. var timerQuery = this._caps.timerQuery;
  17419. if (timerQuery.getQueryObjectEXT) {
  17420. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17421. }
  17422. return this.getQueryResult(query);
  17423. };
  17424. Engine.prototype._getTimeQueryAvailability = function (query) {
  17425. var timerQuery = this._caps.timerQuery;
  17426. if (timerQuery.getQueryObjectEXT) {
  17427. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17428. }
  17429. return this.isQueryResultAvailable(query);
  17430. };
  17431. /**
  17432. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17433. * Please note that only one query can be issued at a time
  17434. * @returns a time token used to track the time span
  17435. */
  17436. Engine.prototype.startTimeQuery = function () {
  17437. var timerQuery = this._caps.timerQuery;
  17438. if (!timerQuery) {
  17439. return null;
  17440. }
  17441. var token = new BABYLON._TimeToken();
  17442. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17443. if (this._caps.canUseTimestampForTimerQuery) {
  17444. token._startTimeQuery = this._createTimeQuery();
  17445. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17446. }
  17447. else {
  17448. if (this._currentNonTimestampToken) {
  17449. return this._currentNonTimestampToken;
  17450. }
  17451. token._timeElapsedQuery = this._createTimeQuery();
  17452. if (timerQuery.beginQueryEXT) {
  17453. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17454. }
  17455. else {
  17456. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17457. }
  17458. this._currentNonTimestampToken = token;
  17459. }
  17460. return token;
  17461. };
  17462. /**
  17463. * Ends a time query
  17464. * @param token defines the token used to measure the time span
  17465. * @returns the time spent (in ns)
  17466. */
  17467. Engine.prototype.endTimeQuery = function (token) {
  17468. var timerQuery = this._caps.timerQuery;
  17469. if (!timerQuery || !token) {
  17470. return -1;
  17471. }
  17472. if (this._caps.canUseTimestampForTimerQuery) {
  17473. if (!token._startTimeQuery) {
  17474. return -1;
  17475. }
  17476. if (!token._endTimeQuery) {
  17477. token._endTimeQuery = this._createTimeQuery();
  17478. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17479. }
  17480. }
  17481. else if (!token._timeElapsedQueryEnded) {
  17482. if (!token._timeElapsedQuery) {
  17483. return -1;
  17484. }
  17485. if (timerQuery.endQueryEXT) {
  17486. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17487. }
  17488. else {
  17489. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17490. }
  17491. token._timeElapsedQueryEnded = true;
  17492. }
  17493. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17494. var available = false;
  17495. if (token._endTimeQuery) {
  17496. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17497. }
  17498. else if (token._timeElapsedQuery) {
  17499. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17500. }
  17501. if (available && !disjoint) {
  17502. var result = 0;
  17503. if (this._caps.canUseTimestampForTimerQuery) {
  17504. if (!token._startTimeQuery || !token._endTimeQuery) {
  17505. return -1;
  17506. }
  17507. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17508. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17509. result = timeEnd - timeStart;
  17510. this._deleteTimeQuery(token._startTimeQuery);
  17511. this._deleteTimeQuery(token._endTimeQuery);
  17512. token._startTimeQuery = null;
  17513. token._endTimeQuery = null;
  17514. }
  17515. else {
  17516. if (!token._timeElapsedQuery) {
  17517. return -1;
  17518. }
  17519. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17520. this._deleteTimeQuery(token._timeElapsedQuery);
  17521. token._timeElapsedQuery = null;
  17522. token._timeElapsedQueryEnded = false;
  17523. this._currentNonTimestampToken = null;
  17524. }
  17525. return result;
  17526. }
  17527. return -1;
  17528. };
  17529. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17530. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17531. };
  17532. // Transform feedback
  17533. /**
  17534. * Creates a webGL transform feedback object
  17535. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17536. * @returns the webGL transform feedback object
  17537. */
  17538. Engine.prototype.createTransformFeedback = function () {
  17539. return this._gl.createTransformFeedback();
  17540. };
  17541. /**
  17542. * Delete a webGL transform feedback object
  17543. * @param value defines the webGL transform feedback object to delete
  17544. */
  17545. Engine.prototype.deleteTransformFeedback = function (value) {
  17546. this._gl.deleteTransformFeedback(value);
  17547. };
  17548. /**
  17549. * Bind a webGL transform feedback object to the webgl context
  17550. * @param value defines the webGL transform feedback object to bind
  17551. */
  17552. Engine.prototype.bindTransformFeedback = function (value) {
  17553. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17554. };
  17555. /**
  17556. * Begins a transform feedback operation
  17557. * @param usePoints defines if points or triangles must be used
  17558. */
  17559. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17560. if (usePoints === void 0) { usePoints = true; }
  17561. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17562. };
  17563. /**
  17564. * Ends a transform feedback operation
  17565. */
  17566. Engine.prototype.endTransformFeedback = function () {
  17567. this._gl.endTransformFeedback();
  17568. };
  17569. /**
  17570. * Specify the varyings to use with transform feedback
  17571. * @param program defines the associated webGL program
  17572. * @param value defines the list of strings representing the varying names
  17573. */
  17574. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17575. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17576. };
  17577. /**
  17578. * Bind a webGL buffer for a transform feedback operation
  17579. * @param value defines the webGL buffer to bind
  17580. */
  17581. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17582. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17583. };
  17584. /** @hidden */
  17585. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17586. var _this = this;
  17587. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17588. this._activeRequests.push(request);
  17589. request.onCompleteObservable.add(function (request) {
  17590. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17591. });
  17592. return request;
  17593. };
  17594. /** @hidden */
  17595. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17596. var _this = this;
  17597. return new Promise(function (resolve, reject) {
  17598. _this._loadFile(url, function (data) {
  17599. resolve(data);
  17600. }, undefined, database, useArrayBuffer, function (request, exception) {
  17601. reject(exception);
  17602. });
  17603. });
  17604. };
  17605. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17606. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17607. var onload = function (data) {
  17608. loadedFiles[index] = data;
  17609. loadedFiles._internalCount++;
  17610. if (loadedFiles._internalCount === 6) {
  17611. onfinish(loadedFiles);
  17612. }
  17613. };
  17614. var onerror = function (request, exception) {
  17615. if (onErrorCallBack && request) {
  17616. onErrorCallBack(request.status + " " + request.statusText, exception);
  17617. }
  17618. };
  17619. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17620. };
  17621. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17622. if (onError === void 0) { onError = null; }
  17623. var loadedFiles = [];
  17624. loadedFiles._internalCount = 0;
  17625. for (var index = 0; index < 6; index++) {
  17626. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17627. }
  17628. };
  17629. // Statics
  17630. /**
  17631. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17632. * @returns true if the engine can be created
  17633. * @ignorenaming
  17634. */
  17635. Engine.isSupported = function () {
  17636. try {
  17637. var tempcanvas = document.createElement("canvas");
  17638. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17639. return gl != null && !!window.WebGLRenderingContext;
  17640. }
  17641. catch (e) {
  17642. return false;
  17643. }
  17644. };
  17645. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17646. Engine.ExceptionList = [
  17647. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17648. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17649. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17650. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17651. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17652. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17653. ];
  17654. /** Gets the list of created engines */
  17655. Engine.Instances = new Array();
  17656. // Const statics
  17657. Engine._ALPHA_DISABLE = 0;
  17658. Engine._ALPHA_ADD = 1;
  17659. Engine._ALPHA_COMBINE = 2;
  17660. Engine._ALPHA_SUBTRACT = 3;
  17661. Engine._ALPHA_MULTIPLY = 4;
  17662. Engine._ALPHA_MAXIMIZED = 5;
  17663. Engine._ALPHA_ONEONE = 6;
  17664. Engine._ALPHA_PREMULTIPLIED = 7;
  17665. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17666. Engine._ALPHA_INTERPOLATE = 9;
  17667. Engine._ALPHA_SCREENMODE = 10;
  17668. Engine._DELAYLOADSTATE_NONE = 0;
  17669. Engine._DELAYLOADSTATE_LOADED = 1;
  17670. Engine._DELAYLOADSTATE_LOADING = 2;
  17671. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17672. Engine._TEXTUREFORMAT_ALPHA = 0;
  17673. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17674. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17675. Engine._TEXTUREFORMAT_RGB = 4;
  17676. Engine._TEXTUREFORMAT_RGBA = 5;
  17677. Engine._TEXTUREFORMAT_R = 6;
  17678. Engine._TEXTUREFORMAT_RG = 7;
  17679. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17680. Engine._TEXTURETYPE_FLOAT = 1;
  17681. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17682. // Depht or Stencil test Constants.
  17683. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17684. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17685. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17686. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17687. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17688. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17689. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17690. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17691. // Stencil Actions Constants.
  17692. Engine._KEEP = 0x1E00;
  17693. Engine._REPLACE = 0x1E01;
  17694. Engine._INCR = 0x1E02;
  17695. Engine._DECR = 0x1E03;
  17696. Engine._INVERT = 0x150A;
  17697. Engine._INCR_WRAP = 0x8507;
  17698. Engine._DECR_WRAP = 0x8508;
  17699. // Texture rescaling mode
  17700. Engine._SCALEMODE_FLOOR = 1;
  17701. Engine._SCALEMODE_NEAREST = 2;
  17702. Engine._SCALEMODE_CEILING = 3;
  17703. // Updatable statics so stick with vars here
  17704. /**
  17705. * Gets or sets the epsilon value used by collision engine
  17706. */
  17707. Engine.CollisionsEpsilon = 0.001;
  17708. /**
  17709. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17710. */
  17711. Engine.CodeRepository = "src/";
  17712. /**
  17713. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17714. */
  17715. Engine.ShadersRepository = "src/Shaders/";
  17716. return Engine;
  17717. }());
  17718. BABYLON.Engine = Engine;
  17719. })(BABYLON || (BABYLON = {}));
  17720. //# sourceMappingURL=babylon.engine.js.map
  17721. var BABYLON;
  17722. (function (BABYLON) {
  17723. /**
  17724. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17725. */
  17726. var Node = /** @class */ (function () {
  17727. /**
  17728. * Creates a new Node
  17729. * @param {string} name - the name and id to be given to this node
  17730. * @param {BABYLON.Scene} the scene this node will be added to
  17731. */
  17732. function Node(name, scene) {
  17733. if (scene === void 0) { scene = null; }
  17734. /**
  17735. * Gets or sets a string used to store user defined state for the node
  17736. */
  17737. this.state = "";
  17738. /**
  17739. * Gets or sets an object used to store user defined information for the node
  17740. */
  17741. this.metadata = null;
  17742. /**
  17743. * Gets or sets a boolean used to define if the node must be serialized
  17744. */
  17745. this.doNotSerialize = false;
  17746. /** @hidden */
  17747. this._isDisposed = false;
  17748. /**
  17749. * Gets a list of Animations associated with the node
  17750. */
  17751. this.animations = new Array();
  17752. this._ranges = {};
  17753. this._isEnabled = true;
  17754. this._isReady = true;
  17755. /** @hidden */
  17756. this._currentRenderId = -1;
  17757. this._parentRenderId = -1;
  17758. this._childRenderId = -1;
  17759. this._animationPropertiesOverride = null;
  17760. /**
  17761. * An event triggered when the mesh is disposed
  17762. */
  17763. this.onDisposeObservable = new BABYLON.Observable();
  17764. // Behaviors
  17765. this._behaviors = new Array();
  17766. this.name = name;
  17767. this.id = name;
  17768. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17769. this.uniqueId = this._scene.getUniqueId();
  17770. this._initCache();
  17771. }
  17772. /**
  17773. * Gets a boolean indicating if the node has been disposed
  17774. * @returns true if the node was disposed
  17775. */
  17776. Node.prototype.isDisposed = function () {
  17777. return this._isDisposed;
  17778. };
  17779. Object.defineProperty(Node.prototype, "parent", {
  17780. get: function () {
  17781. return this._parentNode;
  17782. },
  17783. /**
  17784. * Gets or sets the parent of the node
  17785. */
  17786. set: function (parent) {
  17787. if (this._parentNode === parent) {
  17788. return;
  17789. }
  17790. // Remove self from list of children of parent
  17791. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17792. var index = this._parentNode._children.indexOf(this);
  17793. if (index !== -1) {
  17794. this._parentNode._children.splice(index, 1);
  17795. }
  17796. }
  17797. // Store new parent
  17798. this._parentNode = parent;
  17799. // Add as child to new parent
  17800. if (this._parentNode) {
  17801. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17802. this._parentNode._children = new Array();
  17803. }
  17804. this._parentNode._children.push(this);
  17805. }
  17806. },
  17807. enumerable: true,
  17808. configurable: true
  17809. });
  17810. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17811. /**
  17812. * Gets or sets the animation properties override
  17813. */
  17814. get: function () {
  17815. if (!this._animationPropertiesOverride) {
  17816. return this._scene.animationPropertiesOverride;
  17817. }
  17818. return this._animationPropertiesOverride;
  17819. },
  17820. set: function (value) {
  17821. this._animationPropertiesOverride = value;
  17822. },
  17823. enumerable: true,
  17824. configurable: true
  17825. });
  17826. /**
  17827. * Gets a string idenfifying the name of the class
  17828. * @returns "Node" string
  17829. */
  17830. Node.prototype.getClassName = function () {
  17831. return "Node";
  17832. };
  17833. Object.defineProperty(Node.prototype, "onDispose", {
  17834. /**
  17835. * Sets a callback that will be raised when the node will be disposed
  17836. */
  17837. set: function (callback) {
  17838. if (this._onDisposeObserver) {
  17839. this.onDisposeObservable.remove(this._onDisposeObserver);
  17840. }
  17841. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. /**
  17847. * Gets the scene of the node
  17848. * @returns a {BABYLON.Scene}
  17849. */
  17850. Node.prototype.getScene = function () {
  17851. return this._scene;
  17852. };
  17853. /**
  17854. * Gets the engine of the node
  17855. * @returns a {BABYLON.Engine}
  17856. */
  17857. Node.prototype.getEngine = function () {
  17858. return this._scene.getEngine();
  17859. };
  17860. /**
  17861. * Attach a behavior to the node
  17862. * @see http://doc.babylonjs.com/features/behaviour
  17863. * @param behavior defines the behavior to attach
  17864. * @returns the current Node
  17865. */
  17866. Node.prototype.addBehavior = function (behavior) {
  17867. var _this = this;
  17868. var index = this._behaviors.indexOf(behavior);
  17869. if (index !== -1) {
  17870. return this;
  17871. }
  17872. behavior.init();
  17873. if (this._scene.isLoading) {
  17874. // We defer the attach when the scene will be loaded
  17875. this._scene.onDataLoadedObservable.addOnce(function () {
  17876. behavior.attach(_this);
  17877. });
  17878. }
  17879. else {
  17880. behavior.attach(this);
  17881. }
  17882. this._behaviors.push(behavior);
  17883. return this;
  17884. };
  17885. /**
  17886. * Remove an attached behavior
  17887. * @see http://doc.babylonjs.com/features/behaviour
  17888. * @param behavior defines the behavior to attach
  17889. * @returns the current Node
  17890. */
  17891. Node.prototype.removeBehavior = function (behavior) {
  17892. var index = this._behaviors.indexOf(behavior);
  17893. if (index === -1) {
  17894. return this;
  17895. }
  17896. this._behaviors[index].detach();
  17897. this._behaviors.splice(index, 1);
  17898. return this;
  17899. };
  17900. Object.defineProperty(Node.prototype, "behaviors", {
  17901. /**
  17902. * Gets the list of attached behaviors
  17903. * @see http://doc.babylonjs.com/features/behaviour
  17904. */
  17905. get: function () {
  17906. return this._behaviors;
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. /**
  17912. * Gets an attached behavior by name
  17913. * @param name defines the name of the behavior to look for
  17914. * @see http://doc.babylonjs.com/features/behaviour
  17915. * @returns null if behavior was not found else the requested behavior
  17916. */
  17917. Node.prototype.getBehaviorByName = function (name) {
  17918. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17919. var behavior = _a[_i];
  17920. if (behavior.name === name) {
  17921. return behavior;
  17922. }
  17923. }
  17924. return null;
  17925. };
  17926. /**
  17927. * Returns the world matrix of the node
  17928. * @returns a matrix containing the node's world matrix
  17929. */
  17930. Node.prototype.getWorldMatrix = function () {
  17931. return BABYLON.Matrix.Identity();
  17932. };
  17933. /** @hidden */
  17934. Node.prototype._getWorldMatrixDeterminant = function () {
  17935. return 1;
  17936. };
  17937. // override it in derived class if you add new variables to the cache
  17938. // and call the parent class method
  17939. /** @hidden */
  17940. Node.prototype._initCache = function () {
  17941. this._cache = {};
  17942. this._cache.parent = undefined;
  17943. };
  17944. /** @hidden */
  17945. Node.prototype.updateCache = function (force) {
  17946. if (!force && this.isSynchronized())
  17947. return;
  17948. this._cache.parent = this.parent;
  17949. this._updateCache();
  17950. };
  17951. // override it in derived class if you add new variables to the cache
  17952. // and call the parent class method if !ignoreParentClass
  17953. /** @hidden */
  17954. Node.prototype._updateCache = function (ignoreParentClass) {
  17955. };
  17956. // override it in derived class if you add new variables to the cache
  17957. /** @hidden */
  17958. Node.prototype._isSynchronized = function () {
  17959. return true;
  17960. };
  17961. /** @hidden */
  17962. Node.prototype._markSyncedWithParent = function () {
  17963. if (this.parent) {
  17964. this._parentRenderId = this.parent._childRenderId;
  17965. }
  17966. };
  17967. /** @hidden */
  17968. Node.prototype.isSynchronizedWithParent = function () {
  17969. if (!this.parent) {
  17970. return true;
  17971. }
  17972. if (this._parentRenderId !== this.parent._childRenderId) {
  17973. return false;
  17974. }
  17975. return this.parent.isSynchronized();
  17976. };
  17977. /** @hidden */
  17978. Node.prototype.isSynchronized = function (updateCache) {
  17979. var check = this.hasNewParent();
  17980. check = check || !this.isSynchronizedWithParent();
  17981. check = check || !this._isSynchronized();
  17982. if (updateCache)
  17983. this.updateCache(true);
  17984. return !check;
  17985. };
  17986. /** @hidden */
  17987. Node.prototype.hasNewParent = function (update) {
  17988. if (this._cache.parent === this.parent)
  17989. return false;
  17990. if (update)
  17991. this._cache.parent = this.parent;
  17992. return true;
  17993. };
  17994. /**
  17995. * Is this node ready to be used/rendered
  17996. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17997. * @return true if the node is ready
  17998. */
  17999. Node.prototype.isReady = function (completeCheck) {
  18000. if (completeCheck === void 0) { completeCheck = false; }
  18001. return this._isReady;
  18002. };
  18003. /**
  18004. * Is this node enabled?
  18005. * 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
  18006. * @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
  18007. * @return whether this node (and its parent) is enabled
  18008. */
  18009. Node.prototype.isEnabled = function (checkAncestors) {
  18010. if (checkAncestors === void 0) { checkAncestors = true; }
  18011. if (checkAncestors === false) {
  18012. return this._isEnabled;
  18013. }
  18014. if (this._isEnabled === false) {
  18015. return false;
  18016. }
  18017. if (this.parent !== undefined && this.parent !== null) {
  18018. return this.parent.isEnabled(checkAncestors);
  18019. }
  18020. return true;
  18021. };
  18022. /**
  18023. * Set the enabled state of this node
  18024. * @param value defines the new enabled state
  18025. */
  18026. Node.prototype.setEnabled = function (value) {
  18027. this._isEnabled = value;
  18028. };
  18029. /**
  18030. * Is this node a descendant of the given node?
  18031. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18032. * @param ancestor defines the parent node to inspect
  18033. * @returns a boolean indicating if this node is a descendant of the given node
  18034. */
  18035. Node.prototype.isDescendantOf = function (ancestor) {
  18036. if (this.parent) {
  18037. if (this.parent === ancestor) {
  18038. return true;
  18039. }
  18040. return this.parent.isDescendantOf(ancestor);
  18041. }
  18042. return false;
  18043. };
  18044. /** @hidden */
  18045. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18046. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18047. if (!this._children) {
  18048. return;
  18049. }
  18050. for (var index = 0; index < this._children.length; index++) {
  18051. var item = this._children[index];
  18052. if (!predicate || predicate(item)) {
  18053. results.push(item);
  18054. }
  18055. if (!directDescendantsOnly) {
  18056. item._getDescendants(results, false, predicate);
  18057. }
  18058. }
  18059. };
  18060. /**
  18061. * Will return all nodes that have this node as ascendant
  18062. * @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
  18063. * @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
  18064. * @return all children nodes of all types
  18065. */
  18066. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18067. var results = new Array();
  18068. this._getDescendants(results, directDescendantsOnly, predicate);
  18069. return results;
  18070. };
  18071. /**
  18072. * Get all child-meshes of this node
  18073. * @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
  18074. * @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
  18075. * @returns an array of {BABYLON.AbstractMesh}
  18076. */
  18077. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18078. var results = [];
  18079. this._getDescendants(results, directDescendantsOnly, function (node) {
  18080. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18081. });
  18082. return results;
  18083. };
  18084. /**
  18085. * Get all child-transformNodes of this node
  18086. * @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
  18087. * @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
  18088. * @returns an array of {BABYLON.TransformNode}
  18089. */
  18090. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18091. var results = [];
  18092. this._getDescendants(results, directDescendantsOnly, function (node) {
  18093. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18094. });
  18095. return results;
  18096. };
  18097. /**
  18098. * Get all direct children of this node
  18099. * @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
  18100. * @returns an array of {BABYLON.Node}
  18101. */
  18102. Node.prototype.getChildren = function (predicate) {
  18103. return this.getDescendants(true, predicate);
  18104. };
  18105. /** @hidden */
  18106. Node.prototype._setReady = function (state) {
  18107. if (state === this._isReady) {
  18108. return;
  18109. }
  18110. if (!state) {
  18111. this._isReady = false;
  18112. return;
  18113. }
  18114. if (this.onReady) {
  18115. this.onReady(this);
  18116. }
  18117. this._isReady = true;
  18118. };
  18119. /**
  18120. * Get an animation by name
  18121. * @param name defines the name of the animation to look for
  18122. * @returns null if not found else the requested animation
  18123. */
  18124. Node.prototype.getAnimationByName = function (name) {
  18125. for (var i = 0; i < this.animations.length; i++) {
  18126. var animation = this.animations[i];
  18127. if (animation.name === name) {
  18128. return animation;
  18129. }
  18130. }
  18131. return null;
  18132. };
  18133. /**
  18134. * Creates an animation range for this node
  18135. * @param name defines the name of the range
  18136. * @param from defines the starting key
  18137. * @param to defines the end key
  18138. */
  18139. Node.prototype.createAnimationRange = function (name, from, to) {
  18140. // check name not already in use
  18141. if (!this._ranges[name]) {
  18142. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18143. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18144. if (this.animations[i]) {
  18145. this.animations[i].createRange(name, from, to);
  18146. }
  18147. }
  18148. }
  18149. };
  18150. /**
  18151. * Delete a specific animation range
  18152. * @param name defines the name of the range to delete
  18153. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18154. */
  18155. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18156. if (deleteFrames === void 0) { deleteFrames = true; }
  18157. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18158. if (this.animations[i]) {
  18159. this.animations[i].deleteRange(name, deleteFrames);
  18160. }
  18161. }
  18162. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18163. };
  18164. /**
  18165. * Get an animation range by name
  18166. * @param name defines the name of the animation range to look for
  18167. * @returns null if not found else the requested animation range
  18168. */
  18169. Node.prototype.getAnimationRange = function (name) {
  18170. return this._ranges[name];
  18171. };
  18172. /**
  18173. * Will start the animation sequence
  18174. * @param name defines the range frames for animation sequence
  18175. * @param loop defines if the animation should loop (false by default)
  18176. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18177. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18178. * @returns the object created for this animation. If range does not exist, it will return null
  18179. */
  18180. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18181. var range = this.getAnimationRange(name);
  18182. if (!range) {
  18183. return null;
  18184. }
  18185. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18186. };
  18187. /**
  18188. * Serialize animation ranges into a JSON compatible object
  18189. * @returns serialization object
  18190. */
  18191. Node.prototype.serializeAnimationRanges = function () {
  18192. var serializationRanges = [];
  18193. for (var name in this._ranges) {
  18194. var localRange = this._ranges[name];
  18195. if (!localRange) {
  18196. continue;
  18197. }
  18198. var range = {};
  18199. range.name = name;
  18200. range.from = localRange.from;
  18201. range.to = localRange.to;
  18202. serializationRanges.push(range);
  18203. }
  18204. return serializationRanges;
  18205. };
  18206. /**
  18207. * Computes the world matrix of the node
  18208. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18209. * @returns the world matrix
  18210. */
  18211. Node.prototype.computeWorldMatrix = function (force) {
  18212. return BABYLON.Matrix.Identity();
  18213. };
  18214. /**
  18215. * Releases resources associated with this node.
  18216. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18217. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18218. */
  18219. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18220. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18221. if (!doNotRecurse) {
  18222. var nodes = this.getDescendants(true);
  18223. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18224. var node = nodes_1[_i];
  18225. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18226. }
  18227. }
  18228. else {
  18229. var transformNodes = this.getChildTransformNodes(true);
  18230. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18231. var transformNode = transformNodes_1[_a];
  18232. transformNode.parent = null;
  18233. transformNode.computeWorldMatrix(true);
  18234. }
  18235. }
  18236. this.parent = null;
  18237. // Callback
  18238. this.onDisposeObservable.notifyObservers(this);
  18239. this.onDisposeObservable.clear();
  18240. // Behaviors
  18241. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18242. var behavior = _c[_b];
  18243. behavior.detach();
  18244. }
  18245. this._behaviors = [];
  18246. this._isDisposed = true;
  18247. };
  18248. /**
  18249. * Parse animation range data from a serialization object and store them into a given node
  18250. * @param node defines where to store the animation ranges
  18251. * @param parsedNode defines the serialization object to read data from
  18252. * @param scene defines the hosting scene
  18253. */
  18254. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18255. if (parsedNode.ranges) {
  18256. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18257. var data = parsedNode.ranges[index];
  18258. node.createAnimationRange(data.name, data.from, data.to);
  18259. }
  18260. }
  18261. };
  18262. __decorate([
  18263. BABYLON.serialize()
  18264. ], Node.prototype, "name", void 0);
  18265. __decorate([
  18266. BABYLON.serialize()
  18267. ], Node.prototype, "id", void 0);
  18268. __decorate([
  18269. BABYLON.serialize()
  18270. ], Node.prototype, "uniqueId", void 0);
  18271. __decorate([
  18272. BABYLON.serialize()
  18273. ], Node.prototype, "state", void 0);
  18274. __decorate([
  18275. BABYLON.serialize()
  18276. ], Node.prototype, "metadata", void 0);
  18277. return Node;
  18278. }());
  18279. BABYLON.Node = Node;
  18280. })(BABYLON || (BABYLON = {}));
  18281. //# sourceMappingURL=babylon.node.js.map
  18282. var BABYLON;
  18283. (function (BABYLON) {
  18284. var BoundingSphere = /** @class */ (function () {
  18285. /**
  18286. * Creates a new bounding sphere
  18287. * @param min defines the minimum vector (in local space)
  18288. * @param max defines the maximum vector (in local space)
  18289. */
  18290. function BoundingSphere(min, max) {
  18291. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18292. this.reConstruct(min, max);
  18293. }
  18294. /**
  18295. * Recreates the entire bounding sphere from scratch
  18296. * @param min defines the new minimum vector (in local space)
  18297. * @param max defines the new maximum vector (in local space)
  18298. */
  18299. BoundingSphere.prototype.reConstruct = function (min, max) {
  18300. this.minimum = min.clone();
  18301. this.maximum = max.clone();
  18302. var distance = BABYLON.Vector3.Distance(min, max);
  18303. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18304. this.radius = distance * 0.5;
  18305. this.centerWorld = BABYLON.Vector3.Zero();
  18306. this._update(BABYLON.Matrix.Identity());
  18307. };
  18308. // Methods
  18309. BoundingSphere.prototype._update = function (world) {
  18310. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18311. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18312. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18313. };
  18314. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18315. for (var i = 0; i < 6; i++) {
  18316. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18317. return false;
  18318. }
  18319. return true;
  18320. };
  18321. BoundingSphere.prototype.intersectsPoint = function (point) {
  18322. var x = this.centerWorld.x - point.x;
  18323. var y = this.centerWorld.y - point.y;
  18324. var z = this.centerWorld.z - point.z;
  18325. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18326. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18327. return false;
  18328. return true;
  18329. };
  18330. // Statics
  18331. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18332. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18333. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18334. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18335. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18336. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18337. return false;
  18338. return true;
  18339. };
  18340. return BoundingSphere;
  18341. }());
  18342. BABYLON.BoundingSphere = BoundingSphere;
  18343. })(BABYLON || (BABYLON = {}));
  18344. //# sourceMappingURL=babylon.boundingSphere.js.map
  18345. var BABYLON;
  18346. (function (BABYLON) {
  18347. var BoundingBox = /** @class */ (function () {
  18348. /**
  18349. * Creates a new bounding box
  18350. * @param min defines the minimum vector (in local space)
  18351. * @param max defines the maximum vector (in local space)
  18352. */
  18353. function BoundingBox(min, max) {
  18354. this.vectorsWorld = new Array();
  18355. this.reConstruct(min, max);
  18356. }
  18357. // Methods
  18358. /**
  18359. * Recreates the entire bounding box from scratch
  18360. * @param min defines the new minimum vector (in local space)
  18361. * @param max defines the new maximum vector (in local space)
  18362. */
  18363. BoundingBox.prototype.reConstruct = function (min, max) {
  18364. this.minimum = min.clone();
  18365. this.maximum = max.clone();
  18366. // Bounding vectors
  18367. this.vectors = new Array();
  18368. this.vectors.push(this.minimum.clone());
  18369. this.vectors.push(this.maximum.clone());
  18370. this.vectors.push(this.minimum.clone());
  18371. this.vectors[2].x = this.maximum.x;
  18372. this.vectors.push(this.minimum.clone());
  18373. this.vectors[3].y = this.maximum.y;
  18374. this.vectors.push(this.minimum.clone());
  18375. this.vectors[4].z = this.maximum.z;
  18376. this.vectors.push(this.maximum.clone());
  18377. this.vectors[5].z = this.minimum.z;
  18378. this.vectors.push(this.maximum.clone());
  18379. this.vectors[6].x = this.minimum.x;
  18380. this.vectors.push(this.maximum.clone());
  18381. this.vectors[7].y = this.minimum.y;
  18382. // OBB
  18383. this.center = this.maximum.add(this.minimum).scale(0.5);
  18384. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18385. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18386. // World
  18387. for (var index = 0; index < this.vectors.length; index++) {
  18388. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18389. }
  18390. this.minimumWorld = BABYLON.Vector3.Zero();
  18391. this.maximumWorld = BABYLON.Vector3.Zero();
  18392. this.centerWorld = BABYLON.Vector3.Zero();
  18393. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18394. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18395. };
  18396. BoundingBox.prototype.getWorldMatrix = function () {
  18397. return this._worldMatrix;
  18398. };
  18399. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18400. this._worldMatrix.copyFrom(matrix);
  18401. return this;
  18402. };
  18403. BoundingBox.prototype._update = function (world) {
  18404. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18405. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18406. for (var index = 0; index < this.vectors.length; index++) {
  18407. var v = this.vectorsWorld[index];
  18408. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18409. if (v.x < this.minimumWorld.x)
  18410. this.minimumWorld.x = v.x;
  18411. if (v.y < this.minimumWorld.y)
  18412. this.minimumWorld.y = v.y;
  18413. if (v.z < this.minimumWorld.z)
  18414. this.minimumWorld.z = v.z;
  18415. if (v.x > this.maximumWorld.x)
  18416. this.maximumWorld.x = v.x;
  18417. if (v.y > this.maximumWorld.y)
  18418. this.maximumWorld.y = v.y;
  18419. if (v.z > this.maximumWorld.z)
  18420. this.maximumWorld.z = v.z;
  18421. }
  18422. // Extend
  18423. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18424. this.extendSizeWorld.scaleInPlace(0.5);
  18425. // OBB
  18426. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18427. this.centerWorld.scaleInPlace(0.5);
  18428. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18429. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18430. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18431. this._worldMatrix = world;
  18432. };
  18433. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18434. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18435. };
  18436. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18437. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18438. };
  18439. BoundingBox.prototype.intersectsPoint = function (point) {
  18440. var delta = -BABYLON.Epsilon;
  18441. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18442. return false;
  18443. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18444. return false;
  18445. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18446. return false;
  18447. return true;
  18448. };
  18449. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18450. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18451. };
  18452. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18453. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18454. return false;
  18455. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18456. return false;
  18457. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18458. return false;
  18459. return true;
  18460. };
  18461. // Statics
  18462. BoundingBox.Intersects = function (box0, box1) {
  18463. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18464. return false;
  18465. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18466. return false;
  18467. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18468. return false;
  18469. return true;
  18470. };
  18471. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18472. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18473. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18474. return (num <= (sphereRadius * sphereRadius));
  18475. };
  18476. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18477. for (var p = 0; p < 6; p++) {
  18478. for (var i = 0; i < 8; i++) {
  18479. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18480. return false;
  18481. }
  18482. }
  18483. }
  18484. return true;
  18485. };
  18486. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18487. for (var p = 0; p < 6; p++) {
  18488. var inCount = 8;
  18489. for (var i = 0; i < 8; i++) {
  18490. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18491. --inCount;
  18492. }
  18493. else {
  18494. break;
  18495. }
  18496. }
  18497. if (inCount === 0)
  18498. return false;
  18499. }
  18500. return true;
  18501. };
  18502. return BoundingBox;
  18503. }());
  18504. BABYLON.BoundingBox = BoundingBox;
  18505. })(BABYLON || (BABYLON = {}));
  18506. //# sourceMappingURL=babylon.boundingBox.js.map
  18507. var BABYLON;
  18508. (function (BABYLON) {
  18509. var computeBoxExtents = function (axis, box) {
  18510. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18511. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18512. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18513. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18514. var r = r0 + r1 + r2;
  18515. return {
  18516. min: p - r,
  18517. max: p + r
  18518. };
  18519. };
  18520. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18521. var axisOverlap = function (axis, box0, box1) {
  18522. var result0 = computeBoxExtents(axis, box0);
  18523. var result1 = computeBoxExtents(axis, box1);
  18524. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18525. };
  18526. var BoundingInfo = /** @class */ (function () {
  18527. function BoundingInfo(minimum, maximum) {
  18528. this.minimum = minimum;
  18529. this.maximum = maximum;
  18530. this._isLocked = false;
  18531. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18532. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18533. }
  18534. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18535. get: function () {
  18536. return this._isLocked;
  18537. },
  18538. set: function (value) {
  18539. this._isLocked = value;
  18540. },
  18541. enumerable: true,
  18542. configurable: true
  18543. });
  18544. // Methods
  18545. BoundingInfo.prototype.update = function (world) {
  18546. if (this._isLocked) {
  18547. return;
  18548. }
  18549. this.boundingBox._update(world);
  18550. this.boundingSphere._update(world);
  18551. };
  18552. /**
  18553. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18554. * @param center New center of the bounding info
  18555. * @param extend New extend of the bounding info
  18556. */
  18557. BoundingInfo.prototype.centerOn = function (center, extend) {
  18558. this.minimum = center.subtract(extend);
  18559. this.maximum = center.add(extend);
  18560. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18561. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18562. return this;
  18563. };
  18564. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18565. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18566. return false;
  18567. return this.boundingBox.isInFrustum(frustumPlanes);
  18568. };
  18569. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18570. /**
  18571. * Gets the world distance between the min and max points of the bounding box
  18572. */
  18573. get: function () {
  18574. var boundingBox = this.boundingBox;
  18575. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18576. return size.length();
  18577. },
  18578. enumerable: true,
  18579. configurable: true
  18580. });
  18581. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18582. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18583. };
  18584. BoundingInfo.prototype._checkCollision = function (collider) {
  18585. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18586. };
  18587. BoundingInfo.prototype.intersectsPoint = function (point) {
  18588. if (!this.boundingSphere.centerWorld) {
  18589. return false;
  18590. }
  18591. if (!this.boundingSphere.intersectsPoint(point)) {
  18592. return false;
  18593. }
  18594. if (!this.boundingBox.intersectsPoint(point)) {
  18595. return false;
  18596. }
  18597. return true;
  18598. };
  18599. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18600. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18601. return false;
  18602. }
  18603. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18604. return false;
  18605. }
  18606. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18607. return false;
  18608. }
  18609. if (!precise) {
  18610. return true;
  18611. }
  18612. var box0 = this.boundingBox;
  18613. var box1 = boundingInfo.boundingBox;
  18614. if (!axisOverlap(box0.directions[0], box0, box1))
  18615. return false;
  18616. if (!axisOverlap(box0.directions[1], box0, box1))
  18617. return false;
  18618. if (!axisOverlap(box0.directions[2], box0, box1))
  18619. return false;
  18620. if (!axisOverlap(box1.directions[0], box0, box1))
  18621. return false;
  18622. if (!axisOverlap(box1.directions[1], box0, box1))
  18623. return false;
  18624. if (!axisOverlap(box1.directions[2], box0, box1))
  18625. return false;
  18626. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18627. return false;
  18628. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18629. return false;
  18630. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18631. return false;
  18632. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18633. return false;
  18634. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18635. return false;
  18636. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18637. return false;
  18638. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18639. return false;
  18640. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18641. return false;
  18642. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18643. return false;
  18644. return true;
  18645. };
  18646. return BoundingInfo;
  18647. }());
  18648. BABYLON.BoundingInfo = BoundingInfo;
  18649. })(BABYLON || (BABYLON = {}));
  18650. //# sourceMappingURL=babylon.boundingInfo.js.map
  18651. var BABYLON;
  18652. (function (BABYLON) {
  18653. var TransformNode = /** @class */ (function (_super) {
  18654. __extends(TransformNode, _super);
  18655. function TransformNode(name, scene, isPure) {
  18656. if (scene === void 0) { scene = null; }
  18657. if (isPure === void 0) { isPure = true; }
  18658. var _this = _super.call(this, name, scene) || this;
  18659. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18660. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18661. _this._up = new BABYLON.Vector3(0, 1, 0);
  18662. _this._right = new BABYLON.Vector3(1, 0, 0);
  18663. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18664. // Properties
  18665. _this._rotation = BABYLON.Vector3.Zero();
  18666. _this._scaling = BABYLON.Vector3.One();
  18667. _this._isDirty = false;
  18668. /**
  18669. * Set the billboard mode. Default is 0.
  18670. *
  18671. * | Value | Type | Description |
  18672. * | --- | --- | --- |
  18673. * | 0 | BILLBOARDMODE_NONE | |
  18674. * | 1 | BILLBOARDMODE_X | |
  18675. * | 2 | BILLBOARDMODE_Y | |
  18676. * | 4 | BILLBOARDMODE_Z | |
  18677. * | 7 | BILLBOARDMODE_ALL | |
  18678. *
  18679. */
  18680. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18681. _this.scalingDeterminant = 1;
  18682. _this.infiniteDistance = false;
  18683. /**
  18684. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18685. * By default the system will update normals to compensate
  18686. */
  18687. _this.ignoreNonUniformScaling = false;
  18688. _this.position = BABYLON.Vector3.Zero();
  18689. _this._localWorld = BABYLON.Matrix.Zero();
  18690. _this._worldMatrix = BABYLON.Matrix.Zero();
  18691. _this._worldMatrixDeterminant = 0;
  18692. _this._absolutePosition = BABYLON.Vector3.Zero();
  18693. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18694. _this._postMultiplyPivotMatrix = false;
  18695. _this._isWorldMatrixFrozen = false;
  18696. /**
  18697. * An event triggered after the world matrix is updated
  18698. */
  18699. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18700. _this._nonUniformScaling = false;
  18701. if (isPure) {
  18702. _this.getScene().addTransformNode(_this);
  18703. }
  18704. return _this;
  18705. }
  18706. /**
  18707. * Gets a string idenfifying the name of the class
  18708. * @returns "TransformNode" string
  18709. */
  18710. TransformNode.prototype.getClassName = function () {
  18711. return "TransformNode";
  18712. };
  18713. Object.defineProperty(TransformNode.prototype, "rotation", {
  18714. /**
  18715. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18716. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18717. * Default : (0.0, 0.0, 0.0)
  18718. */
  18719. get: function () {
  18720. return this._rotation;
  18721. },
  18722. set: function (newRotation) {
  18723. this._rotation = newRotation;
  18724. },
  18725. enumerable: true,
  18726. configurable: true
  18727. });
  18728. Object.defineProperty(TransformNode.prototype, "scaling", {
  18729. /**
  18730. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18731. * Default : (1.0, 1.0, 1.0)
  18732. */
  18733. get: function () {
  18734. return this._scaling;
  18735. },
  18736. /**
  18737. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18738. * Default : (1.0, 1.0, 1.0)
  18739. */
  18740. set: function (newScaling) {
  18741. this._scaling = newScaling;
  18742. },
  18743. enumerable: true,
  18744. configurable: true
  18745. });
  18746. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18747. /**
  18748. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18749. * It's null by default.
  18750. * 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)
  18751. */
  18752. get: function () {
  18753. return this._rotationQuaternion;
  18754. },
  18755. set: function (quaternion) {
  18756. this._rotationQuaternion = quaternion;
  18757. //reset the rotation vector.
  18758. if (quaternion && this.rotation.length()) {
  18759. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18760. }
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(TransformNode.prototype, "forward", {
  18766. /**
  18767. * The forward direction of that transform in world space.
  18768. */
  18769. get: function () {
  18770. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18771. },
  18772. enumerable: true,
  18773. configurable: true
  18774. });
  18775. Object.defineProperty(TransformNode.prototype, "up", {
  18776. /**
  18777. * The up direction of that transform in world space.
  18778. */
  18779. get: function () {
  18780. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18781. },
  18782. enumerable: true,
  18783. configurable: true
  18784. });
  18785. Object.defineProperty(TransformNode.prototype, "right", {
  18786. /**
  18787. * The right direction of that transform in world space.
  18788. */
  18789. get: function () {
  18790. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18791. },
  18792. enumerable: true,
  18793. configurable: true
  18794. });
  18795. /**
  18796. * Returns the latest update of the World matrix
  18797. * Returns a Matrix.
  18798. */
  18799. TransformNode.prototype.getWorldMatrix = function () {
  18800. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18801. this.computeWorldMatrix();
  18802. }
  18803. return this._worldMatrix;
  18804. };
  18805. /** @hidden */
  18806. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18807. return this._worldMatrixDeterminant;
  18808. };
  18809. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18810. /**
  18811. * Returns directly the latest state of the mesh World matrix.
  18812. * A Matrix is returned.
  18813. */
  18814. get: function () {
  18815. return this._worldMatrix;
  18816. },
  18817. enumerable: true,
  18818. configurable: true
  18819. });
  18820. /**
  18821. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18822. * Returns the TransformNode.
  18823. */
  18824. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18825. this._poseMatrix.copyFrom(matrix);
  18826. return this;
  18827. };
  18828. /**
  18829. * Returns the mesh Pose matrix.
  18830. * Returned object : Matrix
  18831. */
  18832. TransformNode.prototype.getPoseMatrix = function () {
  18833. return this._poseMatrix;
  18834. };
  18835. TransformNode.prototype._isSynchronized = function () {
  18836. if (this._isDirty) {
  18837. return false;
  18838. }
  18839. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18840. return false;
  18841. if (this._cache.pivotMatrixUpdated) {
  18842. return false;
  18843. }
  18844. if (this.infiniteDistance) {
  18845. return false;
  18846. }
  18847. if (!this._cache.position.equals(this.position))
  18848. return false;
  18849. if (this.rotationQuaternion) {
  18850. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18851. return false;
  18852. }
  18853. if (!this._cache.rotation.equals(this.rotation))
  18854. return false;
  18855. if (!this._cache.scaling.equals(this.scaling))
  18856. return false;
  18857. return true;
  18858. };
  18859. TransformNode.prototype._initCache = function () {
  18860. _super.prototype._initCache.call(this);
  18861. this._cache.localMatrixUpdated = false;
  18862. this._cache.position = BABYLON.Vector3.Zero();
  18863. this._cache.scaling = BABYLON.Vector3.Zero();
  18864. this._cache.rotation = BABYLON.Vector3.Zero();
  18865. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18866. this._cache.billboardMode = -1;
  18867. };
  18868. TransformNode.prototype.markAsDirty = function (property) {
  18869. if (property === "rotation") {
  18870. this.rotationQuaternion = null;
  18871. }
  18872. this._currentRenderId = Number.MAX_VALUE;
  18873. this._isDirty = true;
  18874. return this;
  18875. };
  18876. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18877. /**
  18878. * Returns the current mesh absolute position.
  18879. * Retuns a Vector3.
  18880. */
  18881. get: function () {
  18882. return this._absolutePosition;
  18883. },
  18884. enumerable: true,
  18885. configurable: true
  18886. });
  18887. /**
  18888. * Sets a new matrix to apply before all other transformation
  18889. * @param matrix defines the transform matrix
  18890. * @returns the current TransformNode
  18891. */
  18892. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18893. return this.setPivotMatrix(matrix, false);
  18894. };
  18895. /**
  18896. * Sets a new pivot matrix to the current node
  18897. * @param matrix defines the new pivot matrix to use
  18898. * @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
  18899. * @returns the current TransformNode
  18900. */
  18901. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18902. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18903. this._pivotMatrix = matrix.clone();
  18904. this._cache.pivotMatrixUpdated = true;
  18905. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18906. if (this._postMultiplyPivotMatrix) {
  18907. if (!this._pivotMatrixInverse) {
  18908. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18909. }
  18910. else {
  18911. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18912. }
  18913. }
  18914. return this;
  18915. };
  18916. /**
  18917. * Returns the mesh pivot matrix.
  18918. * Default : Identity.
  18919. * A Matrix is returned.
  18920. */
  18921. TransformNode.prototype.getPivotMatrix = function () {
  18922. return this._pivotMatrix;
  18923. };
  18924. /**
  18925. * Prevents the World matrix to be computed any longer.
  18926. * Returns the TransformNode.
  18927. */
  18928. TransformNode.prototype.freezeWorldMatrix = function () {
  18929. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18930. this.computeWorldMatrix(true);
  18931. this._isWorldMatrixFrozen = true;
  18932. return this;
  18933. };
  18934. /**
  18935. * Allows back the World matrix computation.
  18936. * Returns the TransformNode.
  18937. */
  18938. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18939. this._isWorldMatrixFrozen = false;
  18940. this.computeWorldMatrix(true);
  18941. return this;
  18942. };
  18943. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18944. /**
  18945. * True if the World matrix has been frozen.
  18946. * Returns a boolean.
  18947. */
  18948. get: function () {
  18949. return this._isWorldMatrixFrozen;
  18950. },
  18951. enumerable: true,
  18952. configurable: true
  18953. });
  18954. /**
  18955. * Retuns the mesh absolute position in the World.
  18956. * Returns a Vector3.
  18957. */
  18958. TransformNode.prototype.getAbsolutePosition = function () {
  18959. this.computeWorldMatrix();
  18960. return this._absolutePosition;
  18961. };
  18962. /**
  18963. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18964. * Returns the TransformNode.
  18965. */
  18966. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18967. if (!absolutePosition) {
  18968. return this;
  18969. }
  18970. var absolutePositionX;
  18971. var absolutePositionY;
  18972. var absolutePositionZ;
  18973. if (absolutePosition.x === undefined) {
  18974. if (arguments.length < 3) {
  18975. return this;
  18976. }
  18977. absolutePositionX = arguments[0];
  18978. absolutePositionY = arguments[1];
  18979. absolutePositionZ = arguments[2];
  18980. }
  18981. else {
  18982. absolutePositionX = absolutePosition.x;
  18983. absolutePositionY = absolutePosition.y;
  18984. absolutePositionZ = absolutePosition.z;
  18985. }
  18986. if (this.parent) {
  18987. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18988. invertParentWorldMatrix.invert();
  18989. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18990. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18991. }
  18992. else {
  18993. this.position.x = absolutePositionX;
  18994. this.position.y = absolutePositionY;
  18995. this.position.z = absolutePositionZ;
  18996. }
  18997. return this;
  18998. };
  18999. /**
  19000. * Sets the mesh position in its local space.
  19001. * Returns the TransformNode.
  19002. */
  19003. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19004. this.computeWorldMatrix();
  19005. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19006. return this;
  19007. };
  19008. /**
  19009. * Returns the mesh position in the local space from the current World matrix values.
  19010. * Returns a new Vector3.
  19011. */
  19012. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19013. this.computeWorldMatrix();
  19014. var invLocalWorldMatrix = this._localWorld.clone();
  19015. invLocalWorldMatrix.invert();
  19016. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19017. };
  19018. /**
  19019. * Translates the mesh along the passed Vector3 in its local space.
  19020. * Returns the TransformNode.
  19021. */
  19022. TransformNode.prototype.locallyTranslate = function (vector3) {
  19023. this.computeWorldMatrix(true);
  19024. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19025. return this;
  19026. };
  19027. /**
  19028. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19029. * @param targetPoint the position (must be in same space as current mesh) to look at
  19030. * @param yawCor optional yaw (y-axis) correction in radians
  19031. * @param pitchCor optional pitch (x-axis) correction in radians
  19032. * @param rollCor optional roll (z-axis) correction in radians
  19033. * @param space the choosen space of the target
  19034. * @returns the TransformNode.
  19035. */
  19036. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19037. if (yawCor === void 0) { yawCor = 0; }
  19038. if (pitchCor === void 0) { pitchCor = 0; }
  19039. if (rollCor === void 0) { rollCor = 0; }
  19040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19041. var dv = TransformNode._lookAtVectorCache;
  19042. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19043. targetPoint.subtractToRef(pos, dv);
  19044. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19045. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19046. var pitch = Math.atan2(dv.y, len);
  19047. if (this.rotationQuaternion) {
  19048. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19049. }
  19050. else {
  19051. this.rotation.x = pitch + pitchCor;
  19052. this.rotation.y = yaw + yawCor;
  19053. this.rotation.z = rollCor;
  19054. }
  19055. return this;
  19056. };
  19057. /**
  19058. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19059. * This Vector3 is expressed in the World space.
  19060. */
  19061. TransformNode.prototype.getDirection = function (localAxis) {
  19062. var result = BABYLON.Vector3.Zero();
  19063. this.getDirectionToRef(localAxis, result);
  19064. return result;
  19065. };
  19066. /**
  19067. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19068. * localAxis is expressed in the mesh local space.
  19069. * result is computed in the Wordl space from the mesh World matrix.
  19070. * Returns the TransformNode.
  19071. */
  19072. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19073. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19074. return this;
  19075. };
  19076. /**
  19077. * Sets a new pivot point to the current node
  19078. * @param point defines the new pivot point to use
  19079. * @param space defines if the point is in world or local space (local by default)
  19080. * @returns the current TransformNode
  19081. */
  19082. TransformNode.prototype.setPivotPoint = function (point, space) {
  19083. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19084. if (this.getScene().getRenderId() == 0) {
  19085. this.computeWorldMatrix(true);
  19086. }
  19087. var wm = this.getWorldMatrix();
  19088. if (space == BABYLON.Space.WORLD) {
  19089. var tmat = BABYLON.Tmp.Matrix[0];
  19090. wm.invertToRef(tmat);
  19091. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19092. }
  19093. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19094. };
  19095. /**
  19096. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19097. */
  19098. TransformNode.prototype.getPivotPoint = function () {
  19099. var point = BABYLON.Vector3.Zero();
  19100. this.getPivotPointToRef(point);
  19101. return point;
  19102. };
  19103. /**
  19104. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19105. * Returns the TransformNode.
  19106. */
  19107. TransformNode.prototype.getPivotPointToRef = function (result) {
  19108. result.x = -this._pivotMatrix.m[12];
  19109. result.y = -this._pivotMatrix.m[13];
  19110. result.z = -this._pivotMatrix.m[14];
  19111. return this;
  19112. };
  19113. /**
  19114. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19115. */
  19116. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19117. var point = BABYLON.Vector3.Zero();
  19118. this.getAbsolutePivotPointToRef(point);
  19119. return point;
  19120. };
  19121. /**
  19122. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19123. * Returns the TransformNode.
  19124. */
  19125. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19126. result.x = this._pivotMatrix.m[12];
  19127. result.y = this._pivotMatrix.m[13];
  19128. result.z = this._pivotMatrix.m[14];
  19129. this.getPivotPointToRef(result);
  19130. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19131. return this;
  19132. };
  19133. /**
  19134. * Defines the passed node as the parent of the current node.
  19135. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19136. * Returns the TransformNode.
  19137. */
  19138. TransformNode.prototype.setParent = function (node) {
  19139. if (node === null && this.parent === null) {
  19140. return this;
  19141. }
  19142. if (node === null) {
  19143. var rotation = BABYLON.Tmp.Quaternion[0];
  19144. var position = BABYLON.Tmp.Vector3[0];
  19145. var scale = BABYLON.Tmp.Vector3[1];
  19146. if (this.parent && this.parent.computeWorldMatrix) {
  19147. this.parent.computeWorldMatrix(true);
  19148. }
  19149. this.computeWorldMatrix(true);
  19150. this.getWorldMatrix().decompose(scale, rotation, position);
  19151. if (this.rotationQuaternion) {
  19152. this.rotationQuaternion.copyFrom(rotation);
  19153. }
  19154. else {
  19155. rotation.toEulerAnglesToRef(this.rotation);
  19156. }
  19157. this.scaling.x = scale.x;
  19158. this.scaling.y = scale.y;
  19159. this.scaling.z = scale.z;
  19160. this.position.x = position.x;
  19161. this.position.y = position.y;
  19162. this.position.z = position.z;
  19163. }
  19164. else {
  19165. var rotation = BABYLON.Tmp.Quaternion[0];
  19166. var position = BABYLON.Tmp.Vector3[0];
  19167. var scale = BABYLON.Tmp.Vector3[1];
  19168. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19169. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19170. this.computeWorldMatrix(true);
  19171. node.computeWorldMatrix(true);
  19172. node.getWorldMatrix().invertToRef(invParentMatrix);
  19173. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19174. diffMatrix.decompose(scale, rotation, position);
  19175. if (this.rotationQuaternion) {
  19176. this.rotationQuaternion.copyFrom(rotation);
  19177. }
  19178. else {
  19179. rotation.toEulerAnglesToRef(this.rotation);
  19180. }
  19181. this.position.x = position.x;
  19182. this.position.y = position.y;
  19183. this.position.z = position.z;
  19184. this.scaling.x = scale.x;
  19185. this.scaling.y = scale.y;
  19186. this.scaling.z = scale.z;
  19187. }
  19188. this.parent = node;
  19189. return this;
  19190. };
  19191. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19192. get: function () {
  19193. return this._nonUniformScaling;
  19194. },
  19195. enumerable: true,
  19196. configurable: true
  19197. });
  19198. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19199. if (this._nonUniformScaling === value) {
  19200. return false;
  19201. }
  19202. this._nonUniformScaling = value;
  19203. return true;
  19204. };
  19205. /**
  19206. * Attach the current TransformNode to another TransformNode associated with a bone
  19207. * @param bone Bone affecting the TransformNode
  19208. * @param affectedTransformNode TransformNode associated with the bone
  19209. */
  19210. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19211. this._transformToBoneReferal = affectedTransformNode;
  19212. this.parent = bone;
  19213. if (bone.getWorldMatrix().determinant() < 0) {
  19214. this.scalingDeterminant *= -1;
  19215. }
  19216. return this;
  19217. };
  19218. TransformNode.prototype.detachFromBone = function () {
  19219. if (!this.parent) {
  19220. return this;
  19221. }
  19222. if (this.parent.getWorldMatrix().determinant() < 0) {
  19223. this.scalingDeterminant *= -1;
  19224. }
  19225. this._transformToBoneReferal = null;
  19226. this.parent = null;
  19227. return this;
  19228. };
  19229. /**
  19230. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19231. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19232. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19233. * The passed axis is also normalized.
  19234. * Returns the TransformNode.
  19235. */
  19236. TransformNode.prototype.rotate = function (axis, amount, space) {
  19237. axis.normalize();
  19238. if (!this.rotationQuaternion) {
  19239. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19240. this.rotation = BABYLON.Vector3.Zero();
  19241. }
  19242. var rotationQuaternion;
  19243. if (!space || space === BABYLON.Space.LOCAL) {
  19244. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19245. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19246. }
  19247. else {
  19248. if (this.parent) {
  19249. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19250. invertParentWorldMatrix.invert();
  19251. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19252. }
  19253. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19254. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19255. }
  19256. return this;
  19257. };
  19258. /**
  19259. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19260. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19261. * The passed axis is also normalized.
  19262. * Returns the TransformNode.
  19263. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19264. */
  19265. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19266. axis.normalize();
  19267. if (!this.rotationQuaternion) {
  19268. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19269. this.rotation.copyFromFloats(0, 0, 0);
  19270. }
  19271. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19272. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19273. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19274. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19275. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19276. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19277. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19278. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19279. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19280. return this;
  19281. };
  19282. /**
  19283. * Translates the mesh along the axis vector for the passed distance in the given space.
  19284. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19285. * Returns the TransformNode.
  19286. */
  19287. TransformNode.prototype.translate = function (axis, distance, space) {
  19288. var displacementVector = axis.scale(distance);
  19289. if (!space || space === BABYLON.Space.LOCAL) {
  19290. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19291. this.setPositionWithLocalVector(tempV3);
  19292. }
  19293. else {
  19294. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19295. }
  19296. return this;
  19297. };
  19298. /**
  19299. * Adds a rotation step to the mesh current rotation.
  19300. * x, y, z are Euler angles expressed in radians.
  19301. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19302. * This means this rotation is made in the mesh local space only.
  19303. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19304. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19305. * ```javascript
  19306. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19307. * ```
  19308. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19309. * 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.
  19310. * Returns the TransformNode.
  19311. */
  19312. TransformNode.prototype.addRotation = function (x, y, z) {
  19313. var rotationQuaternion;
  19314. if (this.rotationQuaternion) {
  19315. rotationQuaternion = this.rotationQuaternion;
  19316. }
  19317. else {
  19318. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19319. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19320. }
  19321. var accumulation = BABYLON.Tmp.Quaternion[0];
  19322. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19323. rotationQuaternion.multiplyInPlace(accumulation);
  19324. if (!this.rotationQuaternion) {
  19325. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19326. }
  19327. return this;
  19328. };
  19329. /**
  19330. * Computes the mesh World matrix and returns it.
  19331. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19332. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19333. * If the parameter `force`is set to `true`, the actual computation is done.
  19334. * Returns the mesh World Matrix.
  19335. */
  19336. TransformNode.prototype.computeWorldMatrix = function (force) {
  19337. if (this._isWorldMatrixFrozen) {
  19338. return this._worldMatrix;
  19339. }
  19340. if (!force && this.isSynchronized(true)) {
  19341. this._currentRenderId = this.getScene().getRenderId();
  19342. return this._worldMatrix;
  19343. }
  19344. this._cache.position.copyFrom(this.position);
  19345. this._cache.scaling.copyFrom(this.scaling);
  19346. this._cache.pivotMatrixUpdated = false;
  19347. this._cache.billboardMode = this.billboardMode;
  19348. this._currentRenderId = this.getScene().getRenderId();
  19349. this._childRenderId = this.getScene().getRenderId();
  19350. this._isDirty = false;
  19351. // Scaling
  19352. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19353. // Rotation
  19354. //rotate, if quaternion is set and rotation was used
  19355. if (this.rotationQuaternion) {
  19356. var len = this.rotation.length();
  19357. if (len) {
  19358. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19359. this.rotation.copyFromFloats(0, 0, 0);
  19360. }
  19361. }
  19362. if (this.rotationQuaternion) {
  19363. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19364. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19365. }
  19366. else {
  19367. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19368. this._cache.rotation.copyFrom(this.rotation);
  19369. }
  19370. // Translation
  19371. var camera = this.getScene().activeCamera;
  19372. if (this.infiniteDistance && !this.parent && camera) {
  19373. var cameraWorldMatrix = camera.getWorldMatrix();
  19374. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19375. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19376. }
  19377. else {
  19378. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19379. }
  19380. // Composing transformations
  19381. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19382. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19383. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19384. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19385. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19386. // Need to decompose each rotation here
  19387. var currentPosition = BABYLON.Tmp.Vector3[3];
  19388. if (this.parent && this.parent.getWorldMatrix) {
  19389. if (this._transformToBoneReferal) {
  19390. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19391. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19392. }
  19393. else {
  19394. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19395. }
  19396. }
  19397. else {
  19398. currentPosition.copyFrom(this.position);
  19399. }
  19400. currentPosition.subtractInPlace(camera.globalPosition);
  19401. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19402. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19403. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19404. }
  19405. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19406. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19407. }
  19408. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19409. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19410. }
  19411. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19412. }
  19413. else {
  19414. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19415. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19416. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19417. }
  19418. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19419. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19420. }
  19421. // Local world
  19422. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19423. // Parent
  19424. if (this.parent && this.parent.getWorldMatrix) {
  19425. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19426. if (this._transformToBoneReferal) {
  19427. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19428. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19429. }
  19430. else {
  19431. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19432. }
  19433. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19434. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19435. this._worldMatrix.copyFrom(this._localWorld);
  19436. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19437. }
  19438. else {
  19439. if (this._transformToBoneReferal) {
  19440. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19441. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19442. }
  19443. else {
  19444. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19445. }
  19446. }
  19447. this._markSyncedWithParent();
  19448. }
  19449. else {
  19450. this._worldMatrix.copyFrom(this._localWorld);
  19451. }
  19452. // Post multiply inverse of pivotMatrix
  19453. if (this._postMultiplyPivotMatrix) {
  19454. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19455. }
  19456. // Normal matrix
  19457. if (!this.ignoreNonUniformScaling) {
  19458. if (this.scaling.isNonUniform) {
  19459. this._updateNonUniformScalingState(true);
  19460. }
  19461. else if (this.parent && this.parent._nonUniformScaling) {
  19462. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19463. }
  19464. else {
  19465. this._updateNonUniformScalingState(false);
  19466. }
  19467. }
  19468. else {
  19469. this._updateNonUniformScalingState(false);
  19470. }
  19471. this._afterComputeWorldMatrix();
  19472. // Absolute position
  19473. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19474. // Callbacks
  19475. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19476. if (!this._poseMatrix) {
  19477. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19478. }
  19479. // Cache the determinant
  19480. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19481. return this._worldMatrix;
  19482. };
  19483. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19484. };
  19485. /**
  19486. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19487. * @param func: callback function to add
  19488. *
  19489. * Returns the TransformNode.
  19490. */
  19491. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19492. this.onAfterWorldMatrixUpdateObservable.add(func);
  19493. return this;
  19494. };
  19495. /**
  19496. * Removes a registered callback function.
  19497. * Returns the TransformNode.
  19498. */
  19499. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19500. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19501. return this;
  19502. };
  19503. /**
  19504. * Clone the current transform node
  19505. * Returns the new transform node
  19506. * @param name Name of the new clone
  19507. * @param newParent New parent for the clone
  19508. * @param doNotCloneChildren Do not clone children hierarchy
  19509. */
  19510. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19511. var _this = this;
  19512. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19513. result.name = name;
  19514. result.id = name;
  19515. if (newParent) {
  19516. result.parent = newParent;
  19517. }
  19518. if (!doNotCloneChildren) {
  19519. // Children
  19520. var directDescendants = this.getDescendants(true);
  19521. for (var index = 0; index < directDescendants.length; index++) {
  19522. var child = directDescendants[index];
  19523. if (child.clone) {
  19524. child.clone(name + "." + child.name, result);
  19525. }
  19526. }
  19527. }
  19528. return result;
  19529. };
  19530. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19531. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19532. serializationObject.type = this.getClassName();
  19533. // Parent
  19534. if (this.parent) {
  19535. serializationObject.parentId = this.parent.id;
  19536. }
  19537. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19538. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19539. }
  19540. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19541. serializationObject.isEnabled = this.isEnabled();
  19542. // Parent
  19543. if (this.parent) {
  19544. serializationObject.parentId = this.parent.id;
  19545. }
  19546. return serializationObject;
  19547. };
  19548. // Statics
  19549. /**
  19550. * Returns a new TransformNode object parsed from the source provided.
  19551. * The parameter `parsedMesh` is the source.
  19552. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19553. */
  19554. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19555. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19556. if (BABYLON.Tags) {
  19557. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19558. }
  19559. if (parsedTransformNode.localMatrix) {
  19560. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19561. }
  19562. else if (parsedTransformNode.pivotMatrix) {
  19563. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19564. }
  19565. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19566. // Parent
  19567. if (parsedTransformNode.parentId) {
  19568. transformNode._waitingParentId = parsedTransformNode.parentId;
  19569. }
  19570. return transformNode;
  19571. };
  19572. /**
  19573. * Releases resources associated with this transform node.
  19574. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19575. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19576. */
  19577. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19578. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19579. // Animations
  19580. this.getScene().stopAnimation(this);
  19581. // Remove from scene
  19582. this.getScene().removeTransformNode(this);
  19583. this.onAfterWorldMatrixUpdateObservable.clear();
  19584. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19585. };
  19586. // Statics
  19587. TransformNode.BILLBOARDMODE_NONE = 0;
  19588. TransformNode.BILLBOARDMODE_X = 1;
  19589. TransformNode.BILLBOARDMODE_Y = 2;
  19590. TransformNode.BILLBOARDMODE_Z = 4;
  19591. TransformNode.BILLBOARDMODE_ALL = 7;
  19592. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19593. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19594. __decorate([
  19595. BABYLON.serializeAsVector3()
  19596. ], TransformNode.prototype, "_rotation", void 0);
  19597. __decorate([
  19598. BABYLON.serializeAsQuaternion()
  19599. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19600. __decorate([
  19601. BABYLON.serializeAsVector3()
  19602. ], TransformNode.prototype, "_scaling", void 0);
  19603. __decorate([
  19604. BABYLON.serialize()
  19605. ], TransformNode.prototype, "billboardMode", void 0);
  19606. __decorate([
  19607. BABYLON.serialize()
  19608. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19609. __decorate([
  19610. BABYLON.serialize()
  19611. ], TransformNode.prototype, "infiniteDistance", void 0);
  19612. __decorate([
  19613. BABYLON.serialize()
  19614. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19615. __decorate([
  19616. BABYLON.serializeAsVector3()
  19617. ], TransformNode.prototype, "position", void 0);
  19618. return TransformNode;
  19619. }(BABYLON.Node));
  19620. BABYLON.TransformNode = TransformNode;
  19621. })(BABYLON || (BABYLON = {}));
  19622. //# sourceMappingURL=babylon.transformNode.js.map
  19623. var BABYLON;
  19624. (function (BABYLON) {
  19625. /**
  19626. * Class used to store all common mesh properties
  19627. */
  19628. var AbstractMesh = /** @class */ (function (_super) {
  19629. __extends(AbstractMesh, _super);
  19630. // Constructor
  19631. /**
  19632. * Creates a new AbstractMesh
  19633. * @param name defines the name of the mesh
  19634. * @param scene defines the hosting scene
  19635. */
  19636. function AbstractMesh(name, scene) {
  19637. if (scene === void 0) { scene = null; }
  19638. var _this = _super.call(this, name, scene, false) || this;
  19639. _this._facetNb = 0; // facet number
  19640. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19641. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19642. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19643. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19644. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19645. _this._subDiv = {
  19646. max: 1,
  19647. X: 1,
  19648. Y: 1,
  19649. Z: 1
  19650. };
  19651. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19652. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19653. // Events
  19654. /**
  19655. * An event triggered when this mesh collides with another one
  19656. */
  19657. _this.onCollideObservable = new BABYLON.Observable();
  19658. /**
  19659. * An event triggered when the collision's position changes
  19660. */
  19661. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19662. /**
  19663. * An event triggered when material is changed
  19664. */
  19665. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19666. // Properties
  19667. /**
  19668. * Gets or sets the orientation for POV movement & rotation
  19669. */
  19670. _this.definedFacingForward = true;
  19671. /**
  19672. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19673. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19674. * * 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.
  19675. * @see http://doc.babylonjs.com/features/occlusionquery
  19676. */
  19677. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19678. /**
  19679. * 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:
  19680. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19681. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19682. * * 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.
  19683. * @see http://doc.babylonjs.com/features/occlusionquery
  19684. */
  19685. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19686. /**
  19687. * 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.
  19688. * The default value is -1 which means don't break the query and wait till the result
  19689. * @see http://doc.babylonjs.com/features/occlusionquery
  19690. */
  19691. _this.occlusionRetryCount = -1;
  19692. _this._occlusionInternalRetryCounter = 0;
  19693. _this._isOccluded = false;
  19694. _this._isOcclusionQueryInProgress = false;
  19695. _this._visibility = 1.0;
  19696. /** Gets or sets the alpha index used to sort transparent meshes
  19697. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19698. */
  19699. _this.alphaIndex = Number.MAX_VALUE;
  19700. /**
  19701. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19702. */
  19703. _this.isVisible = true;
  19704. /**
  19705. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19706. */
  19707. _this.isPickable = true;
  19708. /**
  19709. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19710. */
  19711. _this.showBoundingBox = false;
  19712. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19713. _this.showSubMeshesBoundingBox = false;
  19714. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19715. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19716. */
  19717. _this.isBlocker = false;
  19718. /**
  19719. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19720. */
  19721. _this.enablePointerMoveEvents = false;
  19722. /**
  19723. * Specifies the rendering group id for this mesh (0 by default)
  19724. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19725. */
  19726. _this.renderingGroupId = 0;
  19727. _this._receiveShadows = false;
  19728. /**
  19729. * Gets or sets a boolean indicating if the outline must be rendered as well
  19730. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19731. */
  19732. _this.renderOutline = false;
  19733. /** Defines color to use when rendering outline */
  19734. _this.outlineColor = BABYLON.Color3.Red();
  19735. /** Define width to use when rendering outline */
  19736. _this.outlineWidth = 0.02;
  19737. /**
  19738. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19739. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19740. */
  19741. _this.renderOverlay = false;
  19742. /** Defines color to use when rendering overlay */
  19743. _this.overlayColor = BABYLON.Color3.Red();
  19744. /** Defines alpha to use when rendering overlay */
  19745. _this.overlayAlpha = 0.5;
  19746. _this._hasVertexAlpha = false;
  19747. _this._useVertexColors = true;
  19748. _this._computeBonesUsingShaders = true;
  19749. _this._numBoneInfluencers = 4;
  19750. _this._applyFog = true;
  19751. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19752. _this.useOctreeForRenderingSelection = true;
  19753. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19754. _this.useOctreeForPicking = true;
  19755. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19756. _this.useOctreeForCollisions = true;
  19757. _this._layerMask = 0x0FFFFFFF;
  19758. /**
  19759. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19760. */
  19761. _this.alwaysSelectAsActiveMesh = false;
  19762. /**
  19763. * Gets or sets the current action manager
  19764. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19765. */
  19766. _this.actionManager = null;
  19767. /**
  19768. * Gets or sets impostor used for physic simulation
  19769. * @see http://doc.babylonjs.com/features/physics_engine
  19770. */
  19771. _this.physicsImpostor = null;
  19772. // Collisions
  19773. _this._checkCollisions = false;
  19774. _this._collisionMask = -1;
  19775. _this._collisionGroup = -1;
  19776. /**
  19777. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19778. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19779. */
  19780. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19781. /**
  19782. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19783. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19784. */
  19785. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19786. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19787. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19788. // Edges
  19789. /**
  19790. * Defines edge width used when edgesRenderer is enabled
  19791. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19792. */
  19793. _this.edgesWidth = 1;
  19794. /**
  19795. * Defines edge color used when edgesRenderer is enabled
  19796. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19797. */
  19798. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19799. // Cache
  19800. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19801. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19802. /** @hidden */
  19803. _this._renderId = 0;
  19804. /** @hidden */
  19805. _this._intersectionsInProgress = new Array();
  19806. /** @hidden */
  19807. _this._unIndexed = false;
  19808. /** @hidden */
  19809. _this._lightSources = new Array();
  19810. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19811. if (collidedMesh === void 0) { collidedMesh = null; }
  19812. //TODO move this to the collision coordinator!
  19813. if (_this.getScene().workerCollisions)
  19814. newPosition.multiplyInPlace(_this._collider._radius);
  19815. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19816. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19817. _this.position.addInPlace(_this._diffPositionForCollisions);
  19818. }
  19819. if (collidedMesh) {
  19820. _this.onCollideObservable.notifyObservers(collidedMesh);
  19821. }
  19822. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19823. };
  19824. _this.getScene().addMesh(_this);
  19825. _this._resyncLightSources();
  19826. return _this;
  19827. }
  19828. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19829. /**
  19830. * No billboard
  19831. */
  19832. get: function () {
  19833. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19839. /** Billboard on X axis */
  19840. get: function () {
  19841. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19847. /** Billboard on Y axis */
  19848. get: function () {
  19849. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19855. /** Billboard on Z axis */
  19856. get: function () {
  19857. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19858. },
  19859. enumerable: true,
  19860. configurable: true
  19861. });
  19862. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19863. /** Billboard on all axes */
  19864. get: function () {
  19865. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19871. /**
  19872. * Gets the number of facets in the mesh
  19873. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19874. */
  19875. get: function () {
  19876. return this._facetNb;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19882. /**
  19883. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19884. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19885. */
  19886. get: function () {
  19887. return this._partitioningSubdivisions;
  19888. },
  19889. set: function (nb) {
  19890. this._partitioningSubdivisions = nb;
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19896. /**
  19897. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19898. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19899. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19900. */
  19901. get: function () {
  19902. return this._partitioningBBoxRatio;
  19903. },
  19904. set: function (ratio) {
  19905. this._partitioningBBoxRatio = ratio;
  19906. },
  19907. enumerable: true,
  19908. configurable: true
  19909. });
  19910. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19911. /**
  19912. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19913. * Works only for updatable meshes.
  19914. * Doesn't work with multi-materials
  19915. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19916. */
  19917. get: function () {
  19918. return this._facetDepthSort;
  19919. },
  19920. set: function (sort) {
  19921. this._facetDepthSort = sort;
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19927. /**
  19928. * The location (Vector3) where the facet depth sort must be computed from.
  19929. * By default, the active camera position.
  19930. * Used only when facet depth sort is enabled
  19931. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19932. */
  19933. get: function () {
  19934. return this._facetDepthSortFrom;
  19935. },
  19936. set: function (location) {
  19937. this._facetDepthSortFrom = location;
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19943. /**
  19944. * gets a boolean indicating if facetData is enabled
  19945. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19946. */
  19947. get: function () {
  19948. return this._facetDataEnabled;
  19949. },
  19950. enumerable: true,
  19951. configurable: true
  19952. });
  19953. /** @hidden */
  19954. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19955. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19956. return false;
  19957. }
  19958. this._markSubMeshesAsMiscDirty();
  19959. return true;
  19960. };
  19961. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19962. /** Set a function to call when this mesh collides with another one */
  19963. set: function (callback) {
  19964. if (this._onCollideObserver) {
  19965. this.onCollideObservable.remove(this._onCollideObserver);
  19966. }
  19967. this._onCollideObserver = this.onCollideObservable.add(callback);
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19973. /** Set a function to call when the collision's position changes */
  19974. set: function (callback) {
  19975. if (this._onCollisionPositionChangeObserver) {
  19976. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19977. }
  19978. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19984. /**
  19985. * 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
  19986. * @see http://doc.babylonjs.com/features/occlusionquery
  19987. */
  19988. get: function () {
  19989. return this._isOccluded;
  19990. },
  19991. set: function (value) {
  19992. this._isOccluded = value;
  19993. },
  19994. enumerable: true,
  19995. configurable: true
  19996. });
  19997. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19998. /**
  19999. * Flag to check the progress status of the query
  20000. * @see http://doc.babylonjs.com/features/occlusionquery
  20001. */
  20002. get: function () {
  20003. return this._isOcclusionQueryInProgress;
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20009. /**
  20010. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20011. */
  20012. get: function () {
  20013. return this._visibility;
  20014. },
  20015. /**
  20016. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20017. */
  20018. set: function (value) {
  20019. if (this._visibility === value) {
  20020. return;
  20021. }
  20022. this._visibility = value;
  20023. this._markSubMeshesAsMiscDirty();
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. Object.defineProperty(AbstractMesh.prototype, "material", {
  20029. /** Gets or sets current material */
  20030. get: function () {
  20031. return this._material;
  20032. },
  20033. set: function (value) {
  20034. if (this._material === value) {
  20035. return;
  20036. }
  20037. this._material = value;
  20038. if (this.onMaterialChangedObservable.hasObservers) {
  20039. this.onMaterialChangedObservable.notifyObservers(this);
  20040. }
  20041. if (!this.subMeshes) {
  20042. return;
  20043. }
  20044. this._unBindEffect();
  20045. },
  20046. enumerable: true,
  20047. configurable: true
  20048. });
  20049. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20050. /**
  20051. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20052. * @see http://doc.babylonjs.com/babylon101/shadows
  20053. */
  20054. get: function () {
  20055. return this._receiveShadows;
  20056. },
  20057. set: function (value) {
  20058. if (this._receiveShadows === value) {
  20059. return;
  20060. }
  20061. this._receiveShadows = value;
  20062. this._markSubMeshesAsLightDirty();
  20063. },
  20064. enumerable: true,
  20065. configurable: true
  20066. });
  20067. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20068. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20069. get: function () {
  20070. return this._hasVertexAlpha;
  20071. },
  20072. set: function (value) {
  20073. if (this._hasVertexAlpha === value) {
  20074. return;
  20075. }
  20076. this._hasVertexAlpha = value;
  20077. this._markSubMeshesAsAttributesDirty();
  20078. this._markSubMeshesAsMiscDirty();
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20084. /** 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) */
  20085. get: function () {
  20086. return this._useVertexColors;
  20087. },
  20088. set: function (value) {
  20089. if (this._useVertexColors === value) {
  20090. return;
  20091. }
  20092. this._useVertexColors = value;
  20093. this._markSubMeshesAsAttributesDirty();
  20094. },
  20095. enumerable: true,
  20096. configurable: true
  20097. });
  20098. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20099. /**
  20100. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20101. */
  20102. get: function () {
  20103. return this._computeBonesUsingShaders;
  20104. },
  20105. set: function (value) {
  20106. if (this._computeBonesUsingShaders === value) {
  20107. return;
  20108. }
  20109. this._computeBonesUsingShaders = value;
  20110. this._markSubMeshesAsAttributesDirty();
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20116. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20117. get: function () {
  20118. return this._numBoneInfluencers;
  20119. },
  20120. set: function (value) {
  20121. if (this._numBoneInfluencers === value) {
  20122. return;
  20123. }
  20124. this._numBoneInfluencers = value;
  20125. this._markSubMeshesAsAttributesDirty();
  20126. },
  20127. enumerable: true,
  20128. configurable: true
  20129. });
  20130. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20131. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20132. get: function () {
  20133. return this._applyFog;
  20134. },
  20135. set: function (value) {
  20136. if (this._applyFog === value) {
  20137. return;
  20138. }
  20139. this._applyFog = value;
  20140. this._markSubMeshesAsMiscDirty();
  20141. },
  20142. enumerable: true,
  20143. configurable: true
  20144. });
  20145. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20146. /**
  20147. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20148. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20149. */
  20150. get: function () {
  20151. return this._layerMask;
  20152. },
  20153. set: function (value) {
  20154. if (value === this._layerMask) {
  20155. return;
  20156. }
  20157. this._layerMask = value;
  20158. this._resyncLightSources();
  20159. },
  20160. enumerable: true,
  20161. configurable: true
  20162. });
  20163. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20164. /**
  20165. * Gets or sets a collision mask used to mask collisions (default is -1).
  20166. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20167. */
  20168. get: function () {
  20169. return this._collisionMask;
  20170. },
  20171. set: function (mask) {
  20172. this._collisionMask = !isNaN(mask) ? mask : -1;
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20178. /**
  20179. * Gets or sets the current collision group mask (-1 by default).
  20180. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20181. */
  20182. get: function () {
  20183. return this._collisionGroup;
  20184. },
  20185. set: function (mask) {
  20186. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20192. /** @hidden */
  20193. get: function () {
  20194. return null;
  20195. },
  20196. enumerable: true,
  20197. configurable: true
  20198. });
  20199. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20200. get: function () {
  20201. return this._skeleton;
  20202. },
  20203. /**
  20204. * Gets or sets a skeleton to apply skining transformations
  20205. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20206. */
  20207. set: function (value) {
  20208. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20209. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20210. }
  20211. if (value && value.needInitialSkinMatrix) {
  20212. value._registerMeshWithPoseMatrix(this);
  20213. }
  20214. this._skeleton = value;
  20215. if (!this._skeleton) {
  20216. this._bonesTransformMatrices = null;
  20217. }
  20218. this._markSubMeshesAsAttributesDirty();
  20219. },
  20220. enumerable: true,
  20221. configurable: true
  20222. });
  20223. /**
  20224. * Returns the string "AbstractMesh"
  20225. * @returns "AbstractMesh"
  20226. */
  20227. AbstractMesh.prototype.getClassName = function () {
  20228. return "AbstractMesh";
  20229. };
  20230. /**
  20231. * Gets a string representation of the current mesh
  20232. * @param fullDetails defines a boolean indicating if full details must be included
  20233. * @returns a string representation of the current mesh
  20234. */
  20235. AbstractMesh.prototype.toString = function (fullDetails) {
  20236. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20237. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20238. if (this._skeleton) {
  20239. ret += ", skeleton: " + this._skeleton.name;
  20240. }
  20241. if (fullDetails) {
  20242. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20243. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20244. }
  20245. return ret;
  20246. };
  20247. /** @hidden */
  20248. AbstractMesh.prototype._rebuild = function () {
  20249. if (this._occlusionQuery) {
  20250. this._occlusionQuery = null;
  20251. }
  20252. if (this._edgesRenderer) {
  20253. this._edgesRenderer._rebuild();
  20254. }
  20255. if (!this.subMeshes) {
  20256. return;
  20257. }
  20258. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20259. var subMesh = _a[_i];
  20260. subMesh._rebuild();
  20261. }
  20262. };
  20263. /** @hidden */
  20264. AbstractMesh.prototype._resyncLightSources = function () {
  20265. this._lightSources.length = 0;
  20266. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20267. var light = _a[_i];
  20268. if (!light.isEnabled()) {
  20269. continue;
  20270. }
  20271. if (light.canAffectMesh(this)) {
  20272. this._lightSources.push(light);
  20273. }
  20274. }
  20275. this._markSubMeshesAsLightDirty();
  20276. };
  20277. /** @hidden */
  20278. AbstractMesh.prototype._resyncLighSource = function (light) {
  20279. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20280. var index = this._lightSources.indexOf(light);
  20281. if (index === -1) {
  20282. if (!isIn) {
  20283. return;
  20284. }
  20285. this._lightSources.push(light);
  20286. }
  20287. else {
  20288. if (isIn) {
  20289. return;
  20290. }
  20291. this._lightSources.splice(index, 1);
  20292. }
  20293. this._markSubMeshesAsLightDirty();
  20294. };
  20295. /** @hidden */
  20296. AbstractMesh.prototype._unBindEffect = function () {
  20297. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20298. var subMesh = _a[_i];
  20299. subMesh.setEffect(null);
  20300. }
  20301. };
  20302. /** @hidden */
  20303. AbstractMesh.prototype._removeLightSource = function (light) {
  20304. var index = this._lightSources.indexOf(light);
  20305. if (index === -1) {
  20306. return;
  20307. }
  20308. this._lightSources.splice(index, 1);
  20309. this._markSubMeshesAsLightDirty();
  20310. };
  20311. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20312. if (!this.subMeshes) {
  20313. return;
  20314. }
  20315. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20316. var subMesh = _a[_i];
  20317. if (subMesh._materialDefines) {
  20318. func(subMesh._materialDefines);
  20319. }
  20320. }
  20321. };
  20322. /** @hidden */
  20323. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20324. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20325. };
  20326. /** @hidden */
  20327. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20328. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20329. };
  20330. /** @hidden */
  20331. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20332. if (!this.subMeshes) {
  20333. return;
  20334. }
  20335. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20336. var subMesh = _a[_i];
  20337. var material = subMesh.getMaterial();
  20338. if (material) {
  20339. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20340. }
  20341. }
  20342. };
  20343. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20344. /**
  20345. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20346. */
  20347. get: function () {
  20348. return this._scaling;
  20349. },
  20350. set: function (newScaling) {
  20351. this._scaling = newScaling;
  20352. if (this.physicsImpostor) {
  20353. this.physicsImpostor.forceUpdate();
  20354. }
  20355. },
  20356. enumerable: true,
  20357. configurable: true
  20358. });
  20359. // Methods
  20360. /**
  20361. * Disables the mesh edge rendering mode
  20362. * @returns the currentAbstractMesh
  20363. */
  20364. AbstractMesh.prototype.disableEdgesRendering = function () {
  20365. if (this._edgesRenderer) {
  20366. this._edgesRenderer.dispose();
  20367. this._edgesRenderer = null;
  20368. }
  20369. return this;
  20370. };
  20371. /**
  20372. * Enables the edge rendering mode on the mesh.
  20373. * This mode makes the mesh edges visible
  20374. * @param epsilon defines the maximal distance between two angles to detect a face
  20375. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20376. * @returns the currentAbstractMesh
  20377. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20378. */
  20379. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20380. if (epsilon === void 0) { epsilon = 0.95; }
  20381. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20382. this.disableEdgesRendering();
  20383. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20384. return this;
  20385. };
  20386. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20387. /**
  20388. * Gets the edgesRenderer associated with the mesh
  20389. */
  20390. get: function () {
  20391. return this._edgesRenderer;
  20392. },
  20393. enumerable: true,
  20394. configurable: true
  20395. });
  20396. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20397. /**
  20398. * Returns true if the mesh is blocked. Implemented by child classes
  20399. */
  20400. get: function () {
  20401. return false;
  20402. },
  20403. enumerable: true,
  20404. configurable: true
  20405. });
  20406. /**
  20407. * Returns the mesh itself by default. Implemented by child classes
  20408. * @param camera defines the camera to use to pick the right LOD level
  20409. * @returns the currentAbstractMesh
  20410. */
  20411. AbstractMesh.prototype.getLOD = function (camera) {
  20412. return this;
  20413. };
  20414. /**
  20415. * Returns 0 by default. Implemented by child classes
  20416. * @returns an integer
  20417. */
  20418. AbstractMesh.prototype.getTotalVertices = function () {
  20419. return 0;
  20420. };
  20421. /**
  20422. * Returns null by default. Implemented by child classes
  20423. * @returns null
  20424. */
  20425. AbstractMesh.prototype.getIndices = function () {
  20426. return null;
  20427. };
  20428. /**
  20429. * Returns the array of the requested vertex data kind. Implemented by child classes
  20430. * @param kind defines the vertex data kind to use
  20431. * @returns null
  20432. */
  20433. AbstractMesh.prototype.getVerticesData = function (kind) {
  20434. return null;
  20435. };
  20436. /**
  20437. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20438. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20439. * Note that a new underlying VertexBuffer object is created each call.
  20440. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20441. * @param kind defines vertex data kind:
  20442. * * BABYLON.VertexBuffer.PositionKind
  20443. * * BABYLON.VertexBuffer.UVKind
  20444. * * BABYLON.VertexBuffer.UV2Kind
  20445. * * BABYLON.VertexBuffer.UV3Kind
  20446. * * BABYLON.VertexBuffer.UV4Kind
  20447. * * BABYLON.VertexBuffer.UV5Kind
  20448. * * BABYLON.VertexBuffer.UV6Kind
  20449. * * BABYLON.VertexBuffer.ColorKind
  20450. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20451. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20452. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20453. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20454. * @param data defines the data source
  20455. * @param updatable defines if the data must be flagged as updatable (or static)
  20456. * @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
  20457. * @returns the current mesh
  20458. */
  20459. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20460. return this;
  20461. };
  20462. /**
  20463. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20464. * If the mesh has no geometry, it is simply returned as it is.
  20465. * @param kind defines vertex data kind:
  20466. * * BABYLON.VertexBuffer.PositionKind
  20467. * * BABYLON.VertexBuffer.UVKind
  20468. * * BABYLON.VertexBuffer.UV2Kind
  20469. * * BABYLON.VertexBuffer.UV3Kind
  20470. * * BABYLON.VertexBuffer.UV4Kind
  20471. * * BABYLON.VertexBuffer.UV5Kind
  20472. * * BABYLON.VertexBuffer.UV6Kind
  20473. * * BABYLON.VertexBuffer.ColorKind
  20474. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20475. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20476. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20477. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20478. * @param data defines the data source
  20479. * @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
  20480. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20481. * @returns the current mesh
  20482. */
  20483. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20484. return this;
  20485. };
  20486. /**
  20487. * Sets the mesh indices,
  20488. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20489. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20490. * @param totalVertices Defines the total number of vertices
  20491. * @returns the current mesh
  20492. */
  20493. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20494. return this;
  20495. };
  20496. /**
  20497. * Gets a boolean indicating if specific vertex data is present
  20498. * @param kind defines the vertex data kind to use
  20499. * @returns true is data kind is present
  20500. */
  20501. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20502. return false;
  20503. };
  20504. /**
  20505. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20506. * @returns a BoundingInfo
  20507. */
  20508. AbstractMesh.prototype.getBoundingInfo = function () {
  20509. if (this._masterMesh) {
  20510. return this._masterMesh.getBoundingInfo();
  20511. }
  20512. if (!this._boundingInfo) {
  20513. // this._boundingInfo is being created here
  20514. this._updateBoundingInfo();
  20515. }
  20516. // cannot be null.
  20517. return this._boundingInfo;
  20518. };
  20519. /**
  20520. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20521. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20522. * @returns the current mesh
  20523. */
  20524. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20525. if (includeDescendants === void 0) { includeDescendants = true; }
  20526. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20527. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20528. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20529. if (maxDimension === 0) {
  20530. return this;
  20531. }
  20532. var scale = 1 / maxDimension;
  20533. this.scaling.scaleInPlace(scale);
  20534. return this;
  20535. };
  20536. /**
  20537. * Overwrite the current bounding info
  20538. * @param boundingInfo defines the new bounding info
  20539. * @returns the current mesh
  20540. */
  20541. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20542. this._boundingInfo = boundingInfo;
  20543. return this;
  20544. };
  20545. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20546. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20547. get: function () {
  20548. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20549. },
  20550. enumerable: true,
  20551. configurable: true
  20552. });
  20553. /** @hidden */
  20554. AbstractMesh.prototype._preActivate = function () {
  20555. };
  20556. /** @hidden */
  20557. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20558. };
  20559. /** @hidden */
  20560. AbstractMesh.prototype._activate = function (renderId) {
  20561. this._renderId = renderId;
  20562. };
  20563. /**
  20564. * Gets the current world matrix
  20565. * @returns a Matrix
  20566. */
  20567. AbstractMesh.prototype.getWorldMatrix = function () {
  20568. if (this._masterMesh) {
  20569. return this._masterMesh.getWorldMatrix();
  20570. }
  20571. return _super.prototype.getWorldMatrix.call(this);
  20572. };
  20573. /** @hidden */
  20574. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20575. if (this._masterMesh) {
  20576. return this._masterMesh._getWorldMatrixDeterminant();
  20577. }
  20578. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20579. };
  20580. // ================================== Point of View Movement =================================
  20581. /**
  20582. * Perform relative position change from the point of view of behind the front of the mesh.
  20583. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20584. * Supports definition of mesh facing forward or backward
  20585. * @param amountRight defines the distance on the right axis
  20586. * @param amountUp defines the distance on the up axis
  20587. * @param amountForward defines the distance on the forward axis
  20588. * @returns the current mesh
  20589. */
  20590. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20591. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20592. return this;
  20593. };
  20594. /**
  20595. * Calculate relative position change from the point of view of behind the front of the mesh.
  20596. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20597. * Supports definition of mesh facing forward or backward
  20598. * @param amountRight defines the distance on the right axis
  20599. * @param amountUp defines the distance on the up axis
  20600. * @param amountForward defines the distance on the forward axis
  20601. * @returns the new displacement vector
  20602. */
  20603. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20604. var rotMatrix = new BABYLON.Matrix();
  20605. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20606. rotQuaternion.toRotationMatrix(rotMatrix);
  20607. var translationDelta = BABYLON.Vector3.Zero();
  20608. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20609. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20610. return translationDelta;
  20611. };
  20612. // ================================== Point of View Rotation =================================
  20613. /**
  20614. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20615. * Supports definition of mesh facing forward or backward
  20616. * @param flipBack defines the flip
  20617. * @param twirlClockwise defines the twirl
  20618. * @param tiltRight defines the tilt
  20619. * @returns the current mesh
  20620. */
  20621. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20622. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20623. return this;
  20624. };
  20625. /**
  20626. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20627. * Supports definition of mesh facing forward or backward.
  20628. * @param flipBack defines the flip
  20629. * @param twirlClockwise defines the twirl
  20630. * @param tiltRight defines the tilt
  20631. * @returns the new rotation vector
  20632. */
  20633. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20634. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20635. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20636. };
  20637. /**
  20638. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20639. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20640. * @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
  20641. * @returns the new bounding vectors
  20642. */
  20643. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20644. if (includeDescendants === void 0) { includeDescendants = true; }
  20645. if (predicate === void 0) { predicate = null; }
  20646. // Ensures that all world matrix will be recomputed.
  20647. this.getScene().incrementRenderId();
  20648. this.computeWorldMatrix(true);
  20649. var min;
  20650. var max;
  20651. var boundingInfo = this.getBoundingInfo();
  20652. if (!this.subMeshes) {
  20653. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20654. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20655. }
  20656. else {
  20657. min = boundingInfo.boundingBox.minimumWorld;
  20658. max = boundingInfo.boundingBox.maximumWorld;
  20659. }
  20660. if (includeDescendants) {
  20661. var descendants = this.getDescendants(false);
  20662. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20663. var descendant = descendants_1[_i];
  20664. var childMesh = descendant;
  20665. childMesh.computeWorldMatrix(true);
  20666. // Filters meshes based on custom predicate function.
  20667. if (predicate && !predicate(childMesh)) {
  20668. continue;
  20669. }
  20670. //make sure we have the needed params to get mix and max
  20671. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20672. continue;
  20673. }
  20674. var childBoundingInfo = childMesh.getBoundingInfo();
  20675. var boundingBox = childBoundingInfo.boundingBox;
  20676. var minBox = boundingBox.minimumWorld;
  20677. var maxBox = boundingBox.maximumWorld;
  20678. BABYLON.Tools.CheckExtends(minBox, min, max);
  20679. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20680. }
  20681. }
  20682. return {
  20683. min: min,
  20684. max: max
  20685. };
  20686. };
  20687. /** @hidden */
  20688. AbstractMesh.prototype._updateBoundingInfo = function () {
  20689. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20690. this._boundingInfo.update(this.worldMatrixFromCache);
  20691. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20692. return this;
  20693. };
  20694. /** @hidden */
  20695. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20696. if (!this.subMeshes) {
  20697. return this;
  20698. }
  20699. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20700. var subMesh = this.subMeshes[subIndex];
  20701. if (!subMesh.IsGlobal) {
  20702. subMesh.updateBoundingInfo(matrix);
  20703. }
  20704. }
  20705. return this;
  20706. };
  20707. /** @hidden */
  20708. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20709. // Bounding info
  20710. this._updateBoundingInfo();
  20711. };
  20712. /**
  20713. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20714. * A mesh is in the frustum if its bounding box intersects the frustum
  20715. * @param frustumPlanes defines the frustum to test
  20716. * @returns true if the mesh is in the frustum planes
  20717. */
  20718. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20719. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20720. };
  20721. /**
  20722. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20723. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20724. * @param frustumPlanes defines the frustum to test
  20725. * @returns true if the mesh is completely in the frustum planes
  20726. */
  20727. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20728. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20729. };
  20730. /**
  20731. * True if the mesh intersects another mesh or a SolidParticle object
  20732. * @param mesh defines a target mesh or SolidParticle to test
  20733. * @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)
  20734. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20735. * @returns true if there is an intersection
  20736. */
  20737. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20738. if (precise === void 0) { precise = false; }
  20739. if (!this._boundingInfo || !mesh._boundingInfo) {
  20740. return false;
  20741. }
  20742. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20743. return true;
  20744. }
  20745. if (includeDescendants) {
  20746. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20747. var child = _a[_i];
  20748. if (child.intersectsMesh(mesh, precise, true)) {
  20749. return true;
  20750. }
  20751. }
  20752. }
  20753. return false;
  20754. };
  20755. /**
  20756. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20757. * @param point defines the point to test
  20758. * @returns true if there is an intersection
  20759. */
  20760. AbstractMesh.prototype.intersectsPoint = function (point) {
  20761. if (!this._boundingInfo) {
  20762. return false;
  20763. }
  20764. return this._boundingInfo.intersectsPoint(point);
  20765. };
  20766. /**
  20767. * Gets the current physics impostor
  20768. * @see http://doc.babylonjs.com/features/physics_engine
  20769. * @returns a physics impostor or null
  20770. */
  20771. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20772. return this.physicsImpostor;
  20773. };
  20774. /**
  20775. * Gets the position of the current mesh in camera space
  20776. * @param camera defines the camera to use
  20777. * @returns a position
  20778. */
  20779. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20780. if (camera === void 0) { camera = null; }
  20781. if (!camera) {
  20782. camera = this.getScene().activeCamera;
  20783. }
  20784. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20785. };
  20786. /**
  20787. * Returns the distance from the mesh to the active camera
  20788. * @param camera defines the camera to use
  20789. * @returns the distance
  20790. */
  20791. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20792. if (camera === void 0) { camera = null; }
  20793. if (!camera) {
  20794. camera = this.getScene().activeCamera;
  20795. }
  20796. return this.absolutePosition.subtract(camera.position).length();
  20797. };
  20798. /**
  20799. * Apply a physic impulse to the mesh
  20800. * @param force defines the force to apply
  20801. * @param contactPoint defines where to apply the force
  20802. * @returns the current mesh
  20803. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20804. */
  20805. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20806. if (!this.physicsImpostor) {
  20807. return this;
  20808. }
  20809. this.physicsImpostor.applyImpulse(force, contactPoint);
  20810. return this;
  20811. };
  20812. /**
  20813. * Creates a physic joint between two meshes
  20814. * @param otherMesh defines the other mesh to use
  20815. * @param pivot1 defines the pivot to use on this mesh
  20816. * @param pivot2 defines the pivot to use on the other mesh
  20817. * @param options defines additional options (can be plugin dependent)
  20818. * @returns the current mesh
  20819. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20820. */
  20821. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20822. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20823. return this;
  20824. }
  20825. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20826. mainPivot: pivot1,
  20827. connectedPivot: pivot2,
  20828. nativeParams: options
  20829. });
  20830. return this;
  20831. };
  20832. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20833. // Collisions
  20834. /**
  20835. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20836. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20837. */
  20838. get: function () {
  20839. return this._checkCollisions;
  20840. },
  20841. set: function (collisionEnabled) {
  20842. this._checkCollisions = collisionEnabled;
  20843. if (this.getScene().workerCollisions) {
  20844. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20845. }
  20846. },
  20847. enumerable: true,
  20848. configurable: true
  20849. });
  20850. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20851. /**
  20852. * Gets Collider object used to compute collisions (not physics)
  20853. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20854. */
  20855. get: function () {
  20856. return this._collider;
  20857. },
  20858. enumerable: true,
  20859. configurable: true
  20860. });
  20861. /**
  20862. * Move the mesh using collision engine
  20863. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20864. * @param displacement defines the requested displacement vector
  20865. * @returns the current mesh
  20866. */
  20867. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20868. var globalPosition = this.getAbsolutePosition();
  20869. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20870. if (!this._collider) {
  20871. this._collider = new BABYLON.Collider();
  20872. }
  20873. this._collider._radius = this.ellipsoid;
  20874. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20875. return this;
  20876. };
  20877. // Submeshes octree
  20878. /**
  20879. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20880. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20881. * @param maxCapacity defines the maximum size of each block (64 by default)
  20882. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20883. * @returns the new octree
  20884. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20885. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20886. */
  20887. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20888. if (maxCapacity === void 0) { maxCapacity = 64; }
  20889. if (maxDepth === void 0) { maxDepth = 2; }
  20890. if (!this._submeshesOctree) {
  20891. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20892. }
  20893. this.computeWorldMatrix(true);
  20894. var boundingInfo = this.getBoundingInfo();
  20895. // Update octree
  20896. var bbox = boundingInfo.boundingBox;
  20897. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20898. return this._submeshesOctree;
  20899. };
  20900. // Collisions
  20901. /** @hidden */
  20902. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20903. this._generatePointsArray();
  20904. if (!this._positions) {
  20905. return this;
  20906. }
  20907. // Transformation
  20908. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20909. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20910. subMesh._lastColliderWorldVertices = [];
  20911. subMesh._trianglePlanes = [];
  20912. var start = subMesh.verticesStart;
  20913. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20914. for (var i = start; i < end; i++) {
  20915. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20916. }
  20917. }
  20918. // Collide
  20919. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20920. if (collider.collisionFound) {
  20921. collider.collidedMesh = this;
  20922. }
  20923. return this;
  20924. };
  20925. /** @hidden */
  20926. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20927. var subMeshes;
  20928. var len;
  20929. // Octrees
  20930. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20931. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20932. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20933. len = intersections.length;
  20934. subMeshes = intersections.data;
  20935. }
  20936. else {
  20937. subMeshes = this.subMeshes;
  20938. len = subMeshes.length;
  20939. }
  20940. for (var index = 0; index < len; index++) {
  20941. var subMesh = subMeshes[index];
  20942. // Bounding test
  20943. if (len > 1 && !subMesh._checkCollision(collider))
  20944. continue;
  20945. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20946. }
  20947. return this;
  20948. };
  20949. /** @hidden */
  20950. AbstractMesh.prototype._checkCollision = function (collider) {
  20951. // Bounding box test
  20952. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20953. return this;
  20954. // Transformation matrix
  20955. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20956. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20957. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20958. return this;
  20959. };
  20960. // Picking
  20961. /** @hidden */
  20962. AbstractMesh.prototype._generatePointsArray = function () {
  20963. return false;
  20964. };
  20965. /**
  20966. * Checks if the passed Ray intersects with the mesh
  20967. * @param ray defines the ray to use
  20968. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20969. * @returns the picking info
  20970. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20971. */
  20972. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20973. var pickingInfo = new BABYLON.PickingInfo();
  20974. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20975. return pickingInfo;
  20976. }
  20977. if (!this._generatePointsArray()) {
  20978. return pickingInfo;
  20979. }
  20980. var intersectInfo = null;
  20981. // Octrees
  20982. var subMeshes;
  20983. var len;
  20984. if (this._submeshesOctree && this.useOctreeForPicking) {
  20985. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20986. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20987. len = intersections.length;
  20988. subMeshes = intersections.data;
  20989. }
  20990. else {
  20991. subMeshes = this.subMeshes;
  20992. len = subMeshes.length;
  20993. }
  20994. for (var index = 0; index < len; index++) {
  20995. var subMesh = subMeshes[index];
  20996. // Bounding test
  20997. if (len > 1 && !subMesh.canIntersects(ray))
  20998. continue;
  20999. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21000. if (currentIntersectInfo) {
  21001. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21002. intersectInfo = currentIntersectInfo;
  21003. intersectInfo.subMeshId = index;
  21004. if (fastCheck) {
  21005. break;
  21006. }
  21007. }
  21008. }
  21009. }
  21010. if (intersectInfo) {
  21011. // Get picked point
  21012. var world = this.getWorldMatrix();
  21013. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21014. var direction = ray.direction.clone();
  21015. direction = direction.scale(intersectInfo.distance);
  21016. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21017. var pickedPoint = worldOrigin.add(worldDirection);
  21018. // Return result
  21019. pickingInfo.hit = true;
  21020. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21021. pickingInfo.pickedPoint = pickedPoint;
  21022. pickingInfo.pickedMesh = this;
  21023. pickingInfo.bu = intersectInfo.bu || 0;
  21024. pickingInfo.bv = intersectInfo.bv || 0;
  21025. pickingInfo.faceId = intersectInfo.faceId;
  21026. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21027. return pickingInfo;
  21028. }
  21029. return pickingInfo;
  21030. };
  21031. /**
  21032. * Clones the current mesh
  21033. * @param name defines the mesh name
  21034. * @param newParent defines the new mesh parent
  21035. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21036. * @returns the new mesh
  21037. */
  21038. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21039. return null;
  21040. };
  21041. /**
  21042. * Disposes all the submeshes of the current meshnp
  21043. * @returns the current mesh
  21044. */
  21045. AbstractMesh.prototype.releaseSubMeshes = function () {
  21046. if (this.subMeshes) {
  21047. while (this.subMeshes.length) {
  21048. this.subMeshes[0].dispose();
  21049. }
  21050. }
  21051. else {
  21052. this.subMeshes = new Array();
  21053. }
  21054. return this;
  21055. };
  21056. /**
  21057. * Releases resources associated with this abstract mesh.
  21058. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21059. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21060. */
  21061. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21062. var _this = this;
  21063. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21064. var index;
  21065. // Smart Array Retainers.
  21066. this.getScene().freeActiveMeshes();
  21067. this.getScene().freeRenderingGroups();
  21068. // Action manager
  21069. if (this.actionManager !== undefined && this.actionManager !== null) {
  21070. this.actionManager.dispose();
  21071. this.actionManager = null;
  21072. }
  21073. // Skeleton
  21074. this._skeleton = null;
  21075. // Physics
  21076. if (this.physicsImpostor) {
  21077. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21078. }
  21079. // Intersections in progress
  21080. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21081. var other = this._intersectionsInProgress[index];
  21082. var pos = other._intersectionsInProgress.indexOf(this);
  21083. other._intersectionsInProgress.splice(pos, 1);
  21084. }
  21085. this._intersectionsInProgress = [];
  21086. // Lights
  21087. var lights = this.getScene().lights;
  21088. lights.forEach(function (light) {
  21089. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21090. if (meshIndex !== -1) {
  21091. light.includedOnlyMeshes.splice(meshIndex, 1);
  21092. }
  21093. meshIndex = light.excludedMeshes.indexOf(_this);
  21094. if (meshIndex !== -1) {
  21095. light.excludedMeshes.splice(meshIndex, 1);
  21096. }
  21097. // Shadow generators
  21098. var generator = light.getShadowGenerator();
  21099. if (generator) {
  21100. var shadowMap = generator.getShadowMap();
  21101. if (shadowMap && shadowMap.renderList) {
  21102. meshIndex = shadowMap.renderList.indexOf(_this);
  21103. if (meshIndex !== -1) {
  21104. shadowMap.renderList.splice(meshIndex, 1);
  21105. }
  21106. }
  21107. }
  21108. });
  21109. // Edges
  21110. if (this._edgesRenderer) {
  21111. this._edgesRenderer.dispose();
  21112. this._edgesRenderer = null;
  21113. }
  21114. // SubMeshes
  21115. if (this.getClassName() !== "InstancedMesh") {
  21116. this.releaseSubMeshes();
  21117. }
  21118. // Octree
  21119. var sceneOctree = this.getScene().selectionOctree;
  21120. if (sceneOctree !== undefined && sceneOctree !== null) {
  21121. var index = sceneOctree.dynamicContent.indexOf(this);
  21122. if (index !== -1) {
  21123. sceneOctree.dynamicContent.splice(index, 1);
  21124. }
  21125. }
  21126. // Query
  21127. var engine = this.getScene().getEngine();
  21128. if (this._occlusionQuery) {
  21129. this._isOcclusionQueryInProgress = false;
  21130. engine.deleteQuery(this._occlusionQuery);
  21131. this._occlusionQuery = null;
  21132. }
  21133. // Engine
  21134. engine.wipeCaches();
  21135. // Remove from scene
  21136. this.getScene().removeMesh(this);
  21137. if (disposeMaterialAndTextures) {
  21138. if (this.material) {
  21139. this.material.dispose(false, true);
  21140. }
  21141. }
  21142. if (!doNotRecurse) {
  21143. // Particles
  21144. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21145. if (this.getScene().particleSystems[index].emitter === this) {
  21146. this.getScene().particleSystems[index].dispose();
  21147. index--;
  21148. }
  21149. }
  21150. }
  21151. // facet data
  21152. if (this._facetDataEnabled) {
  21153. this.disableFacetData();
  21154. }
  21155. this.onAfterWorldMatrixUpdateObservable.clear();
  21156. this.onCollideObservable.clear();
  21157. this.onCollisionPositionChangeObservable.clear();
  21158. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21159. };
  21160. /**
  21161. * Adds the passed mesh as a child to the current mesh
  21162. * @param mesh defines the child mesh
  21163. * @returns the current mesh
  21164. */
  21165. AbstractMesh.prototype.addChild = function (mesh) {
  21166. mesh.setParent(this);
  21167. return this;
  21168. };
  21169. /**
  21170. * Removes the passed mesh from the current mesh children list
  21171. * @param mesh defines the child mesh
  21172. * @returns the current mesh
  21173. */
  21174. AbstractMesh.prototype.removeChild = function (mesh) {
  21175. mesh.setParent(null);
  21176. return this;
  21177. };
  21178. // Facet data
  21179. /** @hidden */
  21180. AbstractMesh.prototype._initFacetData = function () {
  21181. if (!this._facetNormals) {
  21182. this._facetNormals = new Array();
  21183. }
  21184. if (!this._facetPositions) {
  21185. this._facetPositions = new Array();
  21186. }
  21187. if (!this._facetPartitioning) {
  21188. this._facetPartitioning = new Array();
  21189. }
  21190. this._facetNb = (this.getIndices().length / 3) | 0;
  21191. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21192. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21193. for (var f = 0; f < this._facetNb; f++) {
  21194. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21195. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21196. }
  21197. this._facetDataEnabled = true;
  21198. return this;
  21199. };
  21200. /**
  21201. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21202. * This method can be called within the render loop.
  21203. * 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
  21204. * @returns the current mesh
  21205. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21206. */
  21207. AbstractMesh.prototype.updateFacetData = function () {
  21208. if (!this._facetDataEnabled) {
  21209. this._initFacetData();
  21210. }
  21211. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21212. var indices = this.getIndices();
  21213. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21214. var bInfo = this.getBoundingInfo();
  21215. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21216. // init arrays, matrix and sort function on first call
  21217. this._facetDepthSortEnabled = true;
  21218. if (indices instanceof Uint16Array) {
  21219. this._depthSortedIndices = new Uint16Array(indices);
  21220. }
  21221. else if (indices instanceof Uint32Array) {
  21222. this._depthSortedIndices = new Uint32Array(indices);
  21223. }
  21224. else {
  21225. var needs32bits = false;
  21226. for (var i = 0; i < indices.length; i++) {
  21227. if (indices[i] > 65535) {
  21228. needs32bits = true;
  21229. break;
  21230. }
  21231. }
  21232. if (needs32bits) {
  21233. this._depthSortedIndices = new Uint32Array(indices);
  21234. }
  21235. else {
  21236. this._depthSortedIndices = new Uint16Array(indices);
  21237. }
  21238. }
  21239. this._facetDepthSortFunction = function (f1, f2) {
  21240. return (f2.sqDistance - f1.sqDistance);
  21241. };
  21242. if (!this._facetDepthSortFrom) {
  21243. var camera = this.getScene().activeCamera;
  21244. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21245. }
  21246. this._depthSortedFacets = [];
  21247. for (var f = 0; f < this._facetNb; f++) {
  21248. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21249. this._depthSortedFacets.push(depthSortedFacet);
  21250. }
  21251. this._invertedMatrix = BABYLON.Matrix.Identity();
  21252. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21253. }
  21254. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21255. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21256. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21257. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21258. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21259. this._subDiv.max = this._partitioningSubdivisions;
  21260. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21261. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21262. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21263. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21264. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21265. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21266. // set the parameters for ComputeNormals()
  21267. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21268. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21269. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21270. this._facetParameters.bInfo = bInfo;
  21271. this._facetParameters.bbSize = this._bbSize;
  21272. this._facetParameters.subDiv = this._subDiv;
  21273. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21274. this._facetParameters.depthSort = this._facetDepthSort;
  21275. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21276. this.computeWorldMatrix(true);
  21277. this._worldMatrix.invertToRef(this._invertedMatrix);
  21278. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21279. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21280. }
  21281. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21282. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21283. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21284. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21285. var l = (this._depthSortedIndices.length / 3) | 0;
  21286. for (var f = 0; f < l; f++) {
  21287. var sind = this._depthSortedFacets[f].ind;
  21288. this._depthSortedIndices[f * 3] = indices[sind];
  21289. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21290. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21291. }
  21292. this.updateIndices(this._depthSortedIndices);
  21293. }
  21294. return this;
  21295. };
  21296. /**
  21297. * Returns the facetLocalNormals array.
  21298. * The normals are expressed in the mesh local spac
  21299. * @returns an array of Vector3
  21300. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21301. */
  21302. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21303. if (!this._facetNormals) {
  21304. this.updateFacetData();
  21305. }
  21306. return this._facetNormals;
  21307. };
  21308. /**
  21309. * Returns the facetLocalPositions array.
  21310. * The facet positions are expressed in the mesh local space
  21311. * @returns an array of Vector3
  21312. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21313. */
  21314. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21315. if (!this._facetPositions) {
  21316. this.updateFacetData();
  21317. }
  21318. return this._facetPositions;
  21319. };
  21320. /**
  21321. * Returns the facetLocalPartioning array
  21322. * @returns an array of array of numbers
  21323. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21324. */
  21325. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21326. if (!this._facetPartitioning) {
  21327. this.updateFacetData();
  21328. }
  21329. return this._facetPartitioning;
  21330. };
  21331. /**
  21332. * Returns the i-th facet position in the world system.
  21333. * This method allocates a new Vector3 per call
  21334. * @param i defines the facet index
  21335. * @returns a new Vector3
  21336. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21337. */
  21338. AbstractMesh.prototype.getFacetPosition = function (i) {
  21339. var pos = BABYLON.Vector3.Zero();
  21340. this.getFacetPositionToRef(i, pos);
  21341. return pos;
  21342. };
  21343. /**
  21344. * Sets the reference Vector3 with the i-th facet position in the world system
  21345. * @param i defines the facet index
  21346. * @param ref defines the target vector
  21347. * @returns the current mesh
  21348. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21349. */
  21350. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21351. var localPos = (this.getFacetLocalPositions())[i];
  21352. var world = this.getWorldMatrix();
  21353. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21354. return this;
  21355. };
  21356. /**
  21357. * Returns the i-th facet normal in the world system.
  21358. * This method allocates a new Vector3 per call
  21359. * @param i defines the facet index
  21360. * @returns a new Vector3
  21361. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21362. */
  21363. AbstractMesh.prototype.getFacetNormal = function (i) {
  21364. var norm = BABYLON.Vector3.Zero();
  21365. this.getFacetNormalToRef(i, norm);
  21366. return norm;
  21367. };
  21368. /**
  21369. * Sets the reference Vector3 with the i-th facet normal in the world system
  21370. * @param i defines the facet index
  21371. * @param ref defines the target vector
  21372. * @returns the current mesh
  21373. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21374. */
  21375. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21376. var localNorm = (this.getFacetLocalNormals())[i];
  21377. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21378. return this;
  21379. };
  21380. /**
  21381. * 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)
  21382. * @param x defines x coordinate
  21383. * @param y defines y coordinate
  21384. * @param z defines z coordinate
  21385. * @returns the array of facet indexes
  21386. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21387. */
  21388. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21389. var bInfo = this.getBoundingInfo();
  21390. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21391. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21392. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21393. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21394. return null;
  21395. }
  21396. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21397. };
  21398. /**
  21399. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21400. * @param projected sets as the (x,y,z) world projection on the facet
  21401. * @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
  21402. * @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
  21403. * @param x defines x coordinate
  21404. * @param y defines y coordinate
  21405. * @param z defines z coordinate
  21406. * @returns the face index if found (or null instead)
  21407. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21408. */
  21409. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21410. if (checkFace === void 0) { checkFace = false; }
  21411. if (facing === void 0) { facing = true; }
  21412. var world = this.getWorldMatrix();
  21413. var invMat = BABYLON.Tmp.Matrix[5];
  21414. world.invertToRef(invMat);
  21415. var invVect = BABYLON.Tmp.Vector3[8];
  21416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21417. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21418. if (projected) {
  21419. // tranform the local computed projected vector to world coordinates
  21420. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21421. }
  21422. return closest;
  21423. };
  21424. /**
  21425. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21426. * @param projected sets as the (x,y,z) local projection on the facet
  21427. * @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
  21428. * @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
  21429. * @param x defines x coordinate
  21430. * @param y defines y coordinate
  21431. * @param z defines z coordinate
  21432. * @returns the face index if found (or null instead)
  21433. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21434. */
  21435. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21436. if (checkFace === void 0) { checkFace = false; }
  21437. if (facing === void 0) { facing = true; }
  21438. var closest = null;
  21439. var tmpx = 0.0;
  21440. var tmpy = 0.0;
  21441. var tmpz = 0.0;
  21442. var d = 0.0; // tmp dot facet normal * facet position
  21443. var t0 = 0.0;
  21444. var projx = 0.0;
  21445. var projy = 0.0;
  21446. var projz = 0.0;
  21447. // Get all the facets in the same partitioning block than (x, y, z)
  21448. var facetPositions = this.getFacetLocalPositions();
  21449. var facetNormals = this.getFacetLocalNormals();
  21450. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21451. if (!facetsInBlock) {
  21452. return null;
  21453. }
  21454. // Get the closest facet to (x, y, z)
  21455. var shortest = Number.MAX_VALUE; // init distance vars
  21456. var tmpDistance = shortest;
  21457. var fib; // current facet in the block
  21458. var norm; // current facet normal
  21459. var p0; // current facet barycenter position
  21460. // loop on all the facets in the current partitioning block
  21461. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21462. fib = facetsInBlock[idx];
  21463. norm = facetNormals[fib];
  21464. p0 = facetPositions[fib];
  21465. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21466. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21467. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21468. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21469. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21470. projx = x + norm.x * t0;
  21471. projy = y + norm.y * t0;
  21472. projz = z + norm.z * t0;
  21473. tmpx = projx - x;
  21474. tmpy = projy - y;
  21475. tmpz = projz - z;
  21476. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21477. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21478. shortest = tmpDistance;
  21479. closest = fib;
  21480. if (projected) {
  21481. projected.x = projx;
  21482. projected.y = projy;
  21483. projected.z = projz;
  21484. }
  21485. }
  21486. }
  21487. }
  21488. return closest;
  21489. };
  21490. /**
  21491. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21492. * @returns the parameters
  21493. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21494. */
  21495. AbstractMesh.prototype.getFacetDataParameters = function () {
  21496. return this._facetParameters;
  21497. };
  21498. /**
  21499. * Disables the feature FacetData and frees the related memory
  21500. * @returns the current mesh
  21501. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21502. */
  21503. AbstractMesh.prototype.disableFacetData = function () {
  21504. if (this._facetDataEnabled) {
  21505. this._facetDataEnabled = false;
  21506. this._facetPositions = new Array();
  21507. this._facetNormals = new Array();
  21508. this._facetPartitioning = new Array();
  21509. this._facetParameters = null;
  21510. this._depthSortedIndices = new Uint32Array(0);
  21511. }
  21512. return this;
  21513. };
  21514. /**
  21515. * Updates the AbstractMesh indices array
  21516. * @param indices defines the data source
  21517. * @returns the current mesh
  21518. */
  21519. AbstractMesh.prototype.updateIndices = function (indices) {
  21520. return this;
  21521. };
  21522. /**
  21523. * Creates new normals data for the mesh
  21524. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21525. * @returns the current mesh
  21526. */
  21527. AbstractMesh.prototype.createNormals = function (updatable) {
  21528. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21529. var indices = this.getIndices();
  21530. var normals;
  21531. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21532. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21533. }
  21534. else {
  21535. normals = [];
  21536. }
  21537. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21538. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21539. return this;
  21540. };
  21541. /**
  21542. * Align the mesh with a normal
  21543. * @param normal defines the normal to use
  21544. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21545. * @returns the current mesh
  21546. */
  21547. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21548. if (!upDirection) {
  21549. upDirection = BABYLON.Axis.Y;
  21550. }
  21551. var axisX = BABYLON.Tmp.Vector3[0];
  21552. var axisZ = BABYLON.Tmp.Vector3[1];
  21553. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21554. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21555. if (this.rotationQuaternion) {
  21556. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21557. }
  21558. else {
  21559. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21560. }
  21561. return this;
  21562. };
  21563. /** @hidden */
  21564. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21565. var engine = this.getEngine();
  21566. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21567. this._isOccluded = false;
  21568. return;
  21569. }
  21570. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21571. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21572. if (isOcclusionQueryAvailable) {
  21573. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21574. this._isOcclusionQueryInProgress = false;
  21575. this._occlusionInternalRetryCounter = 0;
  21576. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21577. }
  21578. else {
  21579. this._occlusionInternalRetryCounter++;
  21580. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21581. this._isOcclusionQueryInProgress = false;
  21582. this._occlusionInternalRetryCounter = 0;
  21583. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21584. // if strict continue the last state of the object.
  21585. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21586. }
  21587. else {
  21588. return;
  21589. }
  21590. }
  21591. }
  21592. var scene = this.getScene();
  21593. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21594. if (!this._occlusionQuery) {
  21595. this._occlusionQuery = engine.createQuery();
  21596. }
  21597. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21598. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21599. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21600. this._isOcclusionQueryInProgress = true;
  21601. };
  21602. /** No occlusion */
  21603. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21604. /** Occlusion set to optimisitic */
  21605. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21606. /** Occlusion set to strict */
  21607. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21608. /** Use an accurante occlusion algorithm */
  21609. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21610. /** Use a conservative occlusion algorithm */
  21611. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21612. return AbstractMesh;
  21613. }(BABYLON.TransformNode));
  21614. BABYLON.AbstractMesh = AbstractMesh;
  21615. })(BABYLON || (BABYLON = {}));
  21616. //# sourceMappingURL=babylon.abstractMesh.js.map
  21617. var BABYLON;
  21618. (function (BABYLON) {
  21619. /**
  21620. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21621. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21622. * 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.
  21623. */
  21624. var Light = /** @class */ (function (_super) {
  21625. __extends(Light, _super);
  21626. /**
  21627. * Creates a Light object in the scene.
  21628. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21629. * @param name The firendly name of the light
  21630. * @param scene The scene the light belongs too
  21631. */
  21632. function Light(name, scene) {
  21633. var _this = _super.call(this, name, scene) || this;
  21634. /**
  21635. * Diffuse gives the basic color to an object.
  21636. */
  21637. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21638. /**
  21639. * Specular produces a highlight color on an object.
  21640. * Note: This is note affecting PBR materials.
  21641. */
  21642. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21643. /**
  21644. * Strength of the light.
  21645. * Note: By default it is define in the framework own unit.
  21646. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21647. */
  21648. _this.intensity = 1.0;
  21649. /**
  21650. * Defines how far from the source the light is impacting in scene units.
  21651. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21652. */
  21653. _this.range = Number.MAX_VALUE;
  21654. /**
  21655. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21656. * of light.
  21657. */
  21658. _this._photometricScale = 1.0;
  21659. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21660. _this._radius = 0.00001;
  21661. /**
  21662. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21663. * exceeding the number allowed of the materials.
  21664. */
  21665. _this.renderPriority = 0;
  21666. _this._shadowEnabled = true;
  21667. _this._excludeWithLayerMask = 0;
  21668. _this._includeOnlyWithLayerMask = 0;
  21669. _this._lightmapMode = 0;
  21670. /**
  21671. * @hidden Internal use only.
  21672. */
  21673. _this._excludedMeshesIds = new Array();
  21674. /**
  21675. * @hidden Internal use only.
  21676. */
  21677. _this._includedOnlyMeshesIds = new Array();
  21678. _this.getScene().addLight(_this);
  21679. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21680. _this._buildUniformLayout();
  21681. _this.includedOnlyMeshes = new Array();
  21682. _this.excludedMeshes = new Array();
  21683. _this._resyncMeshes();
  21684. return _this;
  21685. }
  21686. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21687. /**
  21688. * If every light affecting the material is in this lightmapMode,
  21689. * material.lightmapTexture adds or multiplies
  21690. * (depends on material.useLightmapAsShadowmap)
  21691. * after every other light calculations.
  21692. */
  21693. get: function () {
  21694. return Light._LIGHTMAP_DEFAULT;
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21700. /**
  21701. * material.lightmapTexture as only diffuse lighting from this light
  21702. * adds only specular lighting from this light
  21703. * adds dynamic shadows
  21704. */
  21705. get: function () {
  21706. return Light._LIGHTMAP_SPECULAR;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21712. /**
  21713. * material.lightmapTexture as only lighting
  21714. * no light calculation from this light
  21715. * only adds dynamic shadows from this light
  21716. */
  21717. get: function () {
  21718. return Light._LIGHTMAP_SHADOWSONLY;
  21719. },
  21720. enumerable: true,
  21721. configurable: true
  21722. });
  21723. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21724. /**
  21725. * Each light type uses the default quantity according to its type:
  21726. * point/spot lights use luminous intensity
  21727. * directional lights use illuminance
  21728. */
  21729. get: function () {
  21730. return Light._INTENSITYMODE_AUTOMATIC;
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21736. /**
  21737. * lumen (lm)
  21738. */
  21739. get: function () {
  21740. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21746. /**
  21747. * candela (lm/sr)
  21748. */
  21749. get: function () {
  21750. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21756. /**
  21757. * lux (lm/m^2)
  21758. */
  21759. get: function () {
  21760. return Light._INTENSITYMODE_ILLUMINANCE;
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21766. /**
  21767. * nit (cd/m^2)
  21768. */
  21769. get: function () {
  21770. return Light._INTENSITYMODE_LUMINANCE;
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21776. /**
  21777. * Light type const id of the point light.
  21778. */
  21779. get: function () {
  21780. return Light._LIGHTTYPEID_POINTLIGHT;
  21781. },
  21782. enumerable: true,
  21783. configurable: true
  21784. });
  21785. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21786. /**
  21787. * Light type const id of the directional light.
  21788. */
  21789. get: function () {
  21790. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21796. /**
  21797. * Light type const id of the spot light.
  21798. */
  21799. get: function () {
  21800. return Light._LIGHTTYPEID_SPOTLIGHT;
  21801. },
  21802. enumerable: true,
  21803. configurable: true
  21804. });
  21805. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21806. /**
  21807. * Light type const id of the hemispheric light.
  21808. */
  21809. get: function () {
  21810. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21811. },
  21812. enumerable: true,
  21813. configurable: true
  21814. });
  21815. Object.defineProperty(Light.prototype, "intensityMode", {
  21816. /**
  21817. * Gets the photometric scale used to interpret the intensity.
  21818. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21819. */
  21820. get: function () {
  21821. return this._intensityMode;
  21822. },
  21823. /**
  21824. * Sets the photometric scale used to interpret the intensity.
  21825. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21826. */
  21827. set: function (value) {
  21828. this._intensityMode = value;
  21829. this._computePhotometricScale();
  21830. },
  21831. enumerable: true,
  21832. configurable: true
  21833. });
  21834. ;
  21835. ;
  21836. Object.defineProperty(Light.prototype, "radius", {
  21837. /**
  21838. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21839. */
  21840. get: function () {
  21841. return this._radius;
  21842. },
  21843. /**
  21844. * sets the light radius used by PBR Materials to simulate soft area lights.
  21845. */
  21846. set: function (value) {
  21847. this._radius = value;
  21848. this._computePhotometricScale();
  21849. },
  21850. enumerable: true,
  21851. configurable: true
  21852. });
  21853. ;
  21854. ;
  21855. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21856. /**
  21857. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21858. * the current shadow generator.
  21859. */
  21860. get: function () {
  21861. return this._shadowEnabled;
  21862. },
  21863. /**
  21864. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21865. * the current shadow generator.
  21866. */
  21867. set: function (value) {
  21868. if (this._shadowEnabled === value) {
  21869. return;
  21870. }
  21871. this._shadowEnabled = value;
  21872. this._markMeshesAsLightDirty();
  21873. },
  21874. enumerable: true,
  21875. configurable: true
  21876. });
  21877. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21878. /**
  21879. * Gets the only meshes impacted by this light.
  21880. */
  21881. get: function () {
  21882. return this._includedOnlyMeshes;
  21883. },
  21884. /**
  21885. * Sets the only meshes impacted by this light.
  21886. */
  21887. set: function (value) {
  21888. this._includedOnlyMeshes = value;
  21889. this._hookArrayForIncludedOnly(value);
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21895. /**
  21896. * Gets the meshes not impacted by this light.
  21897. */
  21898. get: function () {
  21899. return this._excludedMeshes;
  21900. },
  21901. /**
  21902. * Sets the meshes not impacted by this light.
  21903. */
  21904. set: function (value) {
  21905. this._excludedMeshes = value;
  21906. this._hookArrayForExcluded(value);
  21907. },
  21908. enumerable: true,
  21909. configurable: true
  21910. });
  21911. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21912. /**
  21913. * Gets the layer id use to find what meshes are not impacted by the light.
  21914. * Inactive if 0
  21915. */
  21916. get: function () {
  21917. return this._excludeWithLayerMask;
  21918. },
  21919. /**
  21920. * Sets the layer id use to find what meshes are not impacted by the light.
  21921. * Inactive if 0
  21922. */
  21923. set: function (value) {
  21924. this._excludeWithLayerMask = value;
  21925. this._resyncMeshes();
  21926. },
  21927. enumerable: true,
  21928. configurable: true
  21929. });
  21930. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21931. /**
  21932. * Gets the layer id use to find what meshes are impacted by the light.
  21933. * Inactive if 0
  21934. */
  21935. get: function () {
  21936. return this._includeOnlyWithLayerMask;
  21937. },
  21938. /**
  21939. * Sets the layer id use to find what meshes are impacted by the light.
  21940. * Inactive if 0
  21941. */
  21942. set: function (value) {
  21943. this._includeOnlyWithLayerMask = value;
  21944. this._resyncMeshes();
  21945. },
  21946. enumerable: true,
  21947. configurable: true
  21948. });
  21949. Object.defineProperty(Light.prototype, "lightmapMode", {
  21950. /**
  21951. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21952. */
  21953. get: function () {
  21954. return this._lightmapMode;
  21955. },
  21956. /**
  21957. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21958. */
  21959. set: function (value) {
  21960. if (this._lightmapMode === value) {
  21961. return;
  21962. }
  21963. this._lightmapMode = value;
  21964. this._markMeshesAsLightDirty();
  21965. },
  21966. enumerable: true,
  21967. configurable: true
  21968. });
  21969. /**
  21970. * Returns the string "Light".
  21971. * @returns the class name
  21972. */
  21973. Light.prototype.getClassName = function () {
  21974. return "Light";
  21975. };
  21976. /**
  21977. * Converts the light information to a readable string for debug purpose.
  21978. * @param fullDetails Supports for multiple levels of logging within scene loading
  21979. * @returns the human readable light info
  21980. */
  21981. Light.prototype.toString = function (fullDetails) {
  21982. var ret = "Name: " + this.name;
  21983. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21984. if (this.animations) {
  21985. for (var i = 0; i < this.animations.length; i++) {
  21986. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21987. }
  21988. }
  21989. if (fullDetails) {
  21990. }
  21991. return ret;
  21992. };
  21993. /**
  21994. * Set the enabled state of this node.
  21995. * @param value - the new enabled state
  21996. */
  21997. Light.prototype.setEnabled = function (value) {
  21998. _super.prototype.setEnabled.call(this, value);
  21999. this._resyncMeshes();
  22000. };
  22001. /**
  22002. * Returns the Light associated shadow generator if any.
  22003. * @return the associated shadow generator.
  22004. */
  22005. Light.prototype.getShadowGenerator = function () {
  22006. return this._shadowGenerator;
  22007. };
  22008. /**
  22009. * Returns a Vector3, the absolute light position in the World.
  22010. * @returns the world space position of the light
  22011. */
  22012. Light.prototype.getAbsolutePosition = function () {
  22013. return BABYLON.Vector3.Zero();
  22014. };
  22015. /**
  22016. * Specifies if the light will affect the passed mesh.
  22017. * @param mesh The mesh to test against the light
  22018. * @return true the mesh is affected otherwise, false.
  22019. */
  22020. Light.prototype.canAffectMesh = function (mesh) {
  22021. if (!mesh) {
  22022. return true;
  22023. }
  22024. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22025. return false;
  22026. }
  22027. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22028. return false;
  22029. }
  22030. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22031. return false;
  22032. }
  22033. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22034. return false;
  22035. }
  22036. return true;
  22037. };
  22038. /**
  22039. * Computes and Returns the light World matrix.
  22040. * @returns the world matrix
  22041. */
  22042. Light.prototype.getWorldMatrix = function () {
  22043. this._currentRenderId = this.getScene().getRenderId();
  22044. this._childRenderId = this._currentRenderId;
  22045. var worldMatrix = this._getWorldMatrix();
  22046. if (this.parent && this.parent.getWorldMatrix) {
  22047. if (!this._parentedWorldMatrix) {
  22048. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  22049. }
  22050. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  22051. this._markSyncedWithParent();
  22052. return this._parentedWorldMatrix;
  22053. }
  22054. return worldMatrix;
  22055. };
  22056. /**
  22057. * Sort function to order lights for rendering.
  22058. * @param a First Light object to compare to second.
  22059. * @param b Second Light object to compare first.
  22060. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22061. */
  22062. Light.CompareLightsPriority = function (a, b) {
  22063. //shadow-casting lights have priority over non-shadow-casting lights
  22064. //the renderPrioirty is a secondary sort criterion
  22065. if (a.shadowEnabled !== b.shadowEnabled) {
  22066. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22067. }
  22068. return b.renderPriority - a.renderPriority;
  22069. };
  22070. /**
  22071. * Releases resources associated with this node.
  22072. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22073. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22074. */
  22075. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22076. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22077. if (this._shadowGenerator) {
  22078. this._shadowGenerator.dispose();
  22079. this._shadowGenerator = null;
  22080. }
  22081. // Animations
  22082. this.getScene().stopAnimation(this);
  22083. // Remove from meshes
  22084. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22085. var mesh = _a[_i];
  22086. mesh._removeLightSource(this);
  22087. }
  22088. this._uniformBuffer.dispose();
  22089. // Remove from scene
  22090. this.getScene().removeLight(this);
  22091. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22092. };
  22093. /**
  22094. * Returns the light type ID (integer).
  22095. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22096. */
  22097. Light.prototype.getTypeID = function () {
  22098. return 0;
  22099. };
  22100. /**
  22101. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22102. * @returns the scaled intensity in intensity mode unit
  22103. */
  22104. Light.prototype.getScaledIntensity = function () {
  22105. return this._photometricScale * this.intensity;
  22106. };
  22107. /**
  22108. * Returns a new Light object, named "name", from the current one.
  22109. * @param name The name of the cloned light
  22110. * @returns the new created light
  22111. */
  22112. Light.prototype.clone = function (name) {
  22113. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22114. if (!constructor) {
  22115. return null;
  22116. }
  22117. return BABYLON.SerializationHelper.Clone(constructor, this);
  22118. };
  22119. /**
  22120. * Serializes the current light into a Serialization object.
  22121. * @returns the serialized object.
  22122. */
  22123. Light.prototype.serialize = function () {
  22124. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22125. // Type
  22126. serializationObject.type = this.getTypeID();
  22127. // Parent
  22128. if (this.parent) {
  22129. serializationObject.parentId = this.parent.id;
  22130. }
  22131. // Inclusion / exclusions
  22132. if (this.excludedMeshes.length > 0) {
  22133. serializationObject.excludedMeshesIds = [];
  22134. this.excludedMeshes.forEach(function (mesh) {
  22135. serializationObject.excludedMeshesIds.push(mesh.id);
  22136. });
  22137. }
  22138. if (this.includedOnlyMeshes.length > 0) {
  22139. serializationObject.includedOnlyMeshesIds = [];
  22140. this.includedOnlyMeshes.forEach(function (mesh) {
  22141. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22142. });
  22143. }
  22144. // Animations
  22145. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22146. serializationObject.ranges = this.serializeAnimationRanges();
  22147. return serializationObject;
  22148. };
  22149. /**
  22150. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22151. * This new light is named "name" and added to the passed scene.
  22152. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22153. * @param name The friendly name of the light
  22154. * @param scene The scene the new light will belong to
  22155. * @returns the constructor function
  22156. */
  22157. Light.GetConstructorFromName = function (type, name, scene) {
  22158. switch (type) {
  22159. case 0:
  22160. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22161. case 1:
  22162. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22163. case 2:
  22164. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22165. case 3:
  22166. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22167. }
  22168. return null;
  22169. };
  22170. /**
  22171. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22172. * @param parsedLight The JSON representation of the light
  22173. * @param scene The scene to create the parsed light in
  22174. * @returns the created light after parsing
  22175. */
  22176. Light.Parse = function (parsedLight, scene) {
  22177. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22178. if (!constructor) {
  22179. return null;
  22180. }
  22181. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22182. // Inclusion / exclusions
  22183. if (parsedLight.excludedMeshesIds) {
  22184. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22185. }
  22186. if (parsedLight.includedOnlyMeshesIds) {
  22187. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22188. }
  22189. // Parent
  22190. if (parsedLight.parentId) {
  22191. light._waitingParentId = parsedLight.parentId;
  22192. }
  22193. // Animations
  22194. if (parsedLight.animations) {
  22195. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22196. var parsedAnimation = parsedLight.animations[animationIndex];
  22197. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22198. }
  22199. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22200. }
  22201. if (parsedLight.autoAnimate) {
  22202. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22203. }
  22204. return light;
  22205. };
  22206. Light.prototype._hookArrayForExcluded = function (array) {
  22207. var _this = this;
  22208. var oldPush = array.push;
  22209. array.push = function () {
  22210. var items = [];
  22211. for (var _i = 0; _i < arguments.length; _i++) {
  22212. items[_i] = arguments[_i];
  22213. }
  22214. var result = oldPush.apply(array, items);
  22215. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22216. var item = items_1[_a];
  22217. item._resyncLighSource(_this);
  22218. }
  22219. return result;
  22220. };
  22221. var oldSplice = array.splice;
  22222. array.splice = function (index, deleteCount) {
  22223. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22224. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22225. var item = deleted_1[_i];
  22226. item._resyncLighSource(_this);
  22227. }
  22228. return deleted;
  22229. };
  22230. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22231. var item = array_1[_i];
  22232. item._resyncLighSource(this);
  22233. }
  22234. };
  22235. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22236. var _this = this;
  22237. var oldPush = array.push;
  22238. array.push = function () {
  22239. var items = [];
  22240. for (var _i = 0; _i < arguments.length; _i++) {
  22241. items[_i] = arguments[_i];
  22242. }
  22243. var result = oldPush.apply(array, items);
  22244. _this._resyncMeshes();
  22245. return result;
  22246. };
  22247. var oldSplice = array.splice;
  22248. array.splice = function (index, deleteCount) {
  22249. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22250. _this._resyncMeshes();
  22251. return deleted;
  22252. };
  22253. this._resyncMeshes();
  22254. };
  22255. Light.prototype._resyncMeshes = function () {
  22256. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22257. var mesh = _a[_i];
  22258. mesh._resyncLighSource(this);
  22259. }
  22260. };
  22261. /**
  22262. * Forces the meshes to update their light related information in their rendering used effects
  22263. * @hidden Internal Use Only
  22264. */
  22265. Light.prototype._markMeshesAsLightDirty = function () {
  22266. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22267. var mesh = _a[_i];
  22268. if (mesh._lightSources.indexOf(this) !== -1) {
  22269. mesh._markSubMeshesAsLightDirty();
  22270. }
  22271. }
  22272. };
  22273. /**
  22274. * Recomputes the cached photometric scale if needed.
  22275. */
  22276. Light.prototype._computePhotometricScale = function () {
  22277. this._photometricScale = this._getPhotometricScale();
  22278. this.getScene().resetCachedMaterial();
  22279. };
  22280. /**
  22281. * Returns the Photometric Scale according to the light type and intensity mode.
  22282. */
  22283. Light.prototype._getPhotometricScale = function () {
  22284. var photometricScale = 0.0;
  22285. var lightTypeID = this.getTypeID();
  22286. //get photometric mode
  22287. var photometricMode = this.intensityMode;
  22288. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22289. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22290. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22291. }
  22292. else {
  22293. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22294. }
  22295. }
  22296. //compute photometric scale
  22297. switch (lightTypeID) {
  22298. case Light.LIGHTTYPEID_POINTLIGHT:
  22299. case Light.LIGHTTYPEID_SPOTLIGHT:
  22300. switch (photometricMode) {
  22301. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22302. photometricScale = 1.0 / (4.0 * Math.PI);
  22303. break;
  22304. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22305. photometricScale = 1.0;
  22306. break;
  22307. case Light.INTENSITYMODE_LUMINANCE:
  22308. photometricScale = this.radius * this.radius;
  22309. break;
  22310. }
  22311. break;
  22312. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22313. switch (photometricMode) {
  22314. case Light.INTENSITYMODE_ILLUMINANCE:
  22315. photometricScale = 1.0;
  22316. break;
  22317. case Light.INTENSITYMODE_LUMINANCE:
  22318. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22319. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22320. var apexAngleRadians = this.radius;
  22321. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22322. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22323. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22324. photometricScale = solidAngle;
  22325. break;
  22326. }
  22327. break;
  22328. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22329. // No fall off in hemisperic light.
  22330. photometricScale = 1.0;
  22331. break;
  22332. }
  22333. return photometricScale;
  22334. };
  22335. /**
  22336. * Reorder the light in the scene according to their defined priority.
  22337. * @hidden Internal Use Only
  22338. */
  22339. Light.prototype._reorderLightsInScene = function () {
  22340. var scene = this.getScene();
  22341. if (this._renderPriority != 0) {
  22342. scene.requireLightSorting = true;
  22343. }
  22344. this.getScene().sortLightsByPriority();
  22345. };
  22346. //lightmapMode Consts
  22347. Light._LIGHTMAP_DEFAULT = 0;
  22348. Light._LIGHTMAP_SPECULAR = 1;
  22349. Light._LIGHTMAP_SHADOWSONLY = 2;
  22350. // Intensity Mode Consts
  22351. Light._INTENSITYMODE_AUTOMATIC = 0;
  22352. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22353. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22354. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22355. Light._INTENSITYMODE_LUMINANCE = 4;
  22356. // Light types ids const.
  22357. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22358. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22359. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22360. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22361. __decorate([
  22362. BABYLON.serializeAsColor3()
  22363. ], Light.prototype, "diffuse", void 0);
  22364. __decorate([
  22365. BABYLON.serializeAsColor3()
  22366. ], Light.prototype, "specular", void 0);
  22367. __decorate([
  22368. BABYLON.serialize()
  22369. ], Light.prototype, "intensity", void 0);
  22370. __decorate([
  22371. BABYLON.serialize()
  22372. ], Light.prototype, "range", void 0);
  22373. __decorate([
  22374. BABYLON.serialize()
  22375. ], Light.prototype, "intensityMode", null);
  22376. __decorate([
  22377. BABYLON.serialize()
  22378. ], Light.prototype, "radius", null);
  22379. __decorate([
  22380. BABYLON.serialize()
  22381. ], Light.prototype, "_renderPriority", void 0);
  22382. __decorate([
  22383. BABYLON.expandToProperty("_reorderLightsInScene")
  22384. ], Light.prototype, "renderPriority", void 0);
  22385. __decorate([
  22386. BABYLON.serialize("shadowEnabled")
  22387. ], Light.prototype, "_shadowEnabled", void 0);
  22388. __decorate([
  22389. BABYLON.serialize("excludeWithLayerMask")
  22390. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22391. __decorate([
  22392. BABYLON.serialize("includeOnlyWithLayerMask")
  22393. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22394. __decorate([
  22395. BABYLON.serialize("lightmapMode")
  22396. ], Light.prototype, "_lightmapMode", void 0);
  22397. return Light;
  22398. }(BABYLON.Node));
  22399. BABYLON.Light = Light;
  22400. })(BABYLON || (BABYLON = {}));
  22401. //# sourceMappingURL=babylon.light.js.map
  22402. var BABYLON;
  22403. (function (BABYLON) {
  22404. var Camera = /** @class */ (function (_super) {
  22405. __extends(Camera, _super);
  22406. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22407. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22408. var _this = _super.call(this, name, scene) || this;
  22409. /**
  22410. * The vector the camera should consider as up.
  22411. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22412. */
  22413. _this.upVector = BABYLON.Vector3.Up();
  22414. _this.orthoLeft = null;
  22415. _this.orthoRight = null;
  22416. _this.orthoBottom = null;
  22417. _this.orthoTop = null;
  22418. /**
  22419. * FOV is set in Radians. (default is 0.8)
  22420. */
  22421. _this.fov = 0.8;
  22422. _this.minZ = 1;
  22423. _this.maxZ = 10000.0;
  22424. _this.inertia = 0.9;
  22425. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22426. _this.isIntermediate = false;
  22427. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22428. /**
  22429. * Restricts the camera to viewing objects with the same layerMask.
  22430. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22431. */
  22432. _this.layerMask = 0x0FFFFFFF;
  22433. /**
  22434. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22435. */
  22436. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22437. // Camera rig members
  22438. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22439. _this._rigCameras = new Array();
  22440. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22441. _this._skipRendering = false;
  22442. _this.customRenderTargets = new Array();
  22443. // Observables
  22444. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22445. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22446. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22447. _this.onRestoreStateObservable = new BABYLON.Observable();
  22448. // Cache
  22449. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22450. _this._projectionMatrix = new BABYLON.Matrix();
  22451. _this._doNotComputeProjectionMatrix = false;
  22452. _this._worldMatrix = BABYLON.Matrix.Identity();
  22453. _this._postProcesses = new Array();
  22454. _this._transformMatrix = BABYLON.Matrix.Zero();
  22455. _this._activeMeshes = new BABYLON.SmartArray(256);
  22456. _this._globalPosition = BABYLON.Vector3.Zero();
  22457. _this._refreshFrustumPlanes = true;
  22458. _this.getScene().addCamera(_this);
  22459. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22460. _this.getScene().activeCamera = _this;
  22461. }
  22462. _this.position = position;
  22463. return _this;
  22464. }
  22465. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22466. get: function () {
  22467. return Camera._PERSPECTIVE_CAMERA;
  22468. },
  22469. enumerable: true,
  22470. configurable: true
  22471. });
  22472. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22473. get: function () {
  22474. return Camera._ORTHOGRAPHIC_CAMERA;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22480. /**
  22481. * This is the default FOV mode for perspective cameras.
  22482. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22483. *
  22484. */
  22485. get: function () {
  22486. return Camera._FOVMODE_VERTICAL_FIXED;
  22487. },
  22488. enumerable: true,
  22489. configurable: true
  22490. });
  22491. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22492. /**
  22493. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22494. *
  22495. */
  22496. get: function () {
  22497. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22498. },
  22499. enumerable: true,
  22500. configurable: true
  22501. });
  22502. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22503. get: function () {
  22504. return Camera._RIG_MODE_NONE;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22510. get: function () {
  22511. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22517. get: function () {
  22518. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22519. },
  22520. enumerable: true,
  22521. configurable: true
  22522. });
  22523. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22524. get: function () {
  22525. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22526. },
  22527. enumerable: true,
  22528. configurable: true
  22529. });
  22530. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22531. get: function () {
  22532. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22533. },
  22534. enumerable: true,
  22535. configurable: true
  22536. });
  22537. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22538. get: function () {
  22539. return Camera._RIG_MODE_VR;
  22540. },
  22541. enumerable: true,
  22542. configurable: true
  22543. });
  22544. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22545. get: function () {
  22546. return Camera._RIG_MODE_WEBVR;
  22547. },
  22548. enumerable: true,
  22549. configurable: true
  22550. });
  22551. /**
  22552. * Store current camera state (fov, position, etc..)
  22553. */
  22554. Camera.prototype.storeState = function () {
  22555. this._stateStored = true;
  22556. this._storedFov = this.fov;
  22557. return this;
  22558. };
  22559. /**
  22560. * Restores the camera state values if it has been stored. You must call storeState() first
  22561. */
  22562. Camera.prototype._restoreStateValues = function () {
  22563. if (!this._stateStored) {
  22564. return false;
  22565. }
  22566. this.fov = this._storedFov;
  22567. return true;
  22568. };
  22569. /**
  22570. * Restored camera state. You must call storeState() first
  22571. */
  22572. Camera.prototype.restoreState = function () {
  22573. if (this._restoreStateValues()) {
  22574. this.onRestoreStateObservable.notifyObservers(this);
  22575. return true;
  22576. }
  22577. return false;
  22578. };
  22579. Camera.prototype.getClassName = function () {
  22580. return "Camera";
  22581. };
  22582. /**
  22583. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22584. */
  22585. Camera.prototype.toString = function (fullDetails) {
  22586. var ret = "Name: " + this.name;
  22587. ret += ", type: " + this.getClassName();
  22588. if (this.animations) {
  22589. for (var i = 0; i < this.animations.length; i++) {
  22590. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22591. }
  22592. }
  22593. if (fullDetails) {
  22594. }
  22595. return ret;
  22596. };
  22597. Object.defineProperty(Camera.prototype, "globalPosition", {
  22598. get: function () {
  22599. return this._globalPosition;
  22600. },
  22601. enumerable: true,
  22602. configurable: true
  22603. });
  22604. Camera.prototype.getActiveMeshes = function () {
  22605. return this._activeMeshes;
  22606. };
  22607. Camera.prototype.isActiveMesh = function (mesh) {
  22608. return (this._activeMeshes.indexOf(mesh) !== -1);
  22609. };
  22610. /**
  22611. * Is this camera ready to be used/rendered
  22612. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22613. * @return true if the camera is ready
  22614. */
  22615. Camera.prototype.isReady = function (completeCheck) {
  22616. if (completeCheck === void 0) { completeCheck = false; }
  22617. if (completeCheck) {
  22618. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22619. var pp = _a[_i];
  22620. if (pp && !pp.isReady()) {
  22621. return false;
  22622. }
  22623. }
  22624. }
  22625. return _super.prototype.isReady.call(this, completeCheck);
  22626. };
  22627. //Cache
  22628. Camera.prototype._initCache = function () {
  22629. _super.prototype._initCache.call(this);
  22630. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22631. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22632. this._cache.mode = undefined;
  22633. this._cache.minZ = undefined;
  22634. this._cache.maxZ = undefined;
  22635. this._cache.fov = undefined;
  22636. this._cache.fovMode = undefined;
  22637. this._cache.aspectRatio = undefined;
  22638. this._cache.orthoLeft = undefined;
  22639. this._cache.orthoRight = undefined;
  22640. this._cache.orthoBottom = undefined;
  22641. this._cache.orthoTop = undefined;
  22642. this._cache.renderWidth = undefined;
  22643. this._cache.renderHeight = undefined;
  22644. };
  22645. Camera.prototype._updateCache = function (ignoreParentClass) {
  22646. if (!ignoreParentClass) {
  22647. _super.prototype._updateCache.call(this);
  22648. }
  22649. this._cache.position.copyFrom(this.position);
  22650. this._cache.upVector.copyFrom(this.upVector);
  22651. };
  22652. // Synchronized
  22653. Camera.prototype._isSynchronized = function () {
  22654. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22655. };
  22656. Camera.prototype._isSynchronizedViewMatrix = function () {
  22657. if (!_super.prototype._isSynchronized.call(this))
  22658. return false;
  22659. return this._cache.position.equals(this.position)
  22660. && this._cache.upVector.equals(this.upVector)
  22661. && this.isSynchronizedWithParent();
  22662. };
  22663. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22664. var check = this._cache.mode === this.mode
  22665. && this._cache.minZ === this.minZ
  22666. && this._cache.maxZ === this.maxZ;
  22667. if (!check) {
  22668. return false;
  22669. }
  22670. var engine = this.getEngine();
  22671. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22672. check = this._cache.fov === this.fov
  22673. && this._cache.fovMode === this.fovMode
  22674. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22675. }
  22676. else {
  22677. check = this._cache.orthoLeft === this.orthoLeft
  22678. && this._cache.orthoRight === this.orthoRight
  22679. && this._cache.orthoBottom === this.orthoBottom
  22680. && this._cache.orthoTop === this.orthoTop
  22681. && this._cache.renderWidth === engine.getRenderWidth()
  22682. && this._cache.renderHeight === engine.getRenderHeight();
  22683. }
  22684. return check;
  22685. };
  22686. // Controls
  22687. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22688. };
  22689. Camera.prototype.detachControl = function (element) {
  22690. };
  22691. Camera.prototype.update = function () {
  22692. this._checkInputs();
  22693. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22694. this._updateRigCameras();
  22695. }
  22696. };
  22697. Camera.prototype._checkInputs = function () {
  22698. this.onAfterCheckInputsObservable.notifyObservers(this);
  22699. };
  22700. Object.defineProperty(Camera.prototype, "rigCameras", {
  22701. get: function () {
  22702. return this._rigCameras;
  22703. },
  22704. enumerable: true,
  22705. configurable: true
  22706. });
  22707. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22708. get: function () {
  22709. return this._rigPostProcess;
  22710. },
  22711. enumerable: true,
  22712. configurable: true
  22713. });
  22714. /**
  22715. * Internal, gets the first post proces.
  22716. * @returns the first post process to be run on this camera.
  22717. */
  22718. Camera.prototype._getFirstPostProcess = function () {
  22719. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22720. if (this._postProcesses[ppIndex] !== null) {
  22721. return this._postProcesses[ppIndex];
  22722. }
  22723. }
  22724. return null;
  22725. };
  22726. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22727. // invalidate framebuffer
  22728. var firstPostProcess = this._getFirstPostProcess();
  22729. if (firstPostProcess) {
  22730. firstPostProcess.markTextureDirty();
  22731. }
  22732. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22733. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22734. var cam = this._rigCameras[i];
  22735. var rigPostProcess = cam._rigPostProcess;
  22736. // for VR rig, there does not have to be a post process
  22737. if (rigPostProcess) {
  22738. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22739. if (isPass) {
  22740. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22741. cam.isIntermediate = this._postProcesses.length === 0;
  22742. }
  22743. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22744. rigPostProcess.markTextureDirty();
  22745. }
  22746. else {
  22747. cam._postProcesses = this._postProcesses.slice(0);
  22748. }
  22749. }
  22750. };
  22751. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22752. if (insertAt === void 0) { insertAt = null; }
  22753. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22754. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22755. return 0;
  22756. }
  22757. if (insertAt == null || insertAt < 0) {
  22758. this._postProcesses.push(postProcess);
  22759. }
  22760. else if (this._postProcesses[insertAt] === null) {
  22761. this._postProcesses[insertAt] = postProcess;
  22762. }
  22763. else {
  22764. this._postProcesses.splice(insertAt, 0, postProcess);
  22765. }
  22766. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22767. return this._postProcesses.indexOf(postProcess);
  22768. };
  22769. Camera.prototype.detachPostProcess = function (postProcess) {
  22770. var idx = this._postProcesses.indexOf(postProcess);
  22771. if (idx !== -1) {
  22772. this._postProcesses[idx] = null;
  22773. }
  22774. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22775. };
  22776. Camera.prototype.getWorldMatrix = function () {
  22777. if (this._isSynchronizedViewMatrix()) {
  22778. return this._worldMatrix;
  22779. }
  22780. // Getting the the view matrix will also compute the world matrix.
  22781. this.getViewMatrix();
  22782. return this._worldMatrix;
  22783. };
  22784. Camera.prototype._getViewMatrix = function () {
  22785. return BABYLON.Matrix.Identity();
  22786. };
  22787. Camera.prototype.getViewMatrix = function (force) {
  22788. if (!force && this._isSynchronizedViewMatrix()) {
  22789. return this._computedViewMatrix;
  22790. }
  22791. this.updateCache();
  22792. this._computedViewMatrix = this._getViewMatrix();
  22793. this._currentRenderId = this.getScene().getRenderId();
  22794. this._childRenderId = this._currentRenderId;
  22795. this._refreshFrustumPlanes = true;
  22796. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22797. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22798. }
  22799. this.onViewMatrixChangedObservable.notifyObservers(this);
  22800. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22801. return this._computedViewMatrix;
  22802. };
  22803. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22804. this._doNotComputeProjectionMatrix = true;
  22805. if (projection !== undefined) {
  22806. this._projectionMatrix = projection;
  22807. }
  22808. };
  22809. ;
  22810. Camera.prototype.unfreezeProjectionMatrix = function () {
  22811. this._doNotComputeProjectionMatrix = false;
  22812. };
  22813. ;
  22814. Camera.prototype.getProjectionMatrix = function (force) {
  22815. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22816. return this._projectionMatrix;
  22817. }
  22818. // Cache
  22819. this._cache.mode = this.mode;
  22820. this._cache.minZ = this.minZ;
  22821. this._cache.maxZ = this.maxZ;
  22822. // Matrix
  22823. this._refreshFrustumPlanes = true;
  22824. var engine = this.getEngine();
  22825. var scene = this.getScene();
  22826. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22827. this._cache.fov = this.fov;
  22828. this._cache.fovMode = this.fovMode;
  22829. this._cache.aspectRatio = engine.getAspectRatio(this);
  22830. if (this.minZ <= 0) {
  22831. this.minZ = 0.1;
  22832. }
  22833. if (scene.useRightHandedSystem) {
  22834. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22835. }
  22836. else {
  22837. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22838. }
  22839. }
  22840. else {
  22841. var halfWidth = engine.getRenderWidth() / 2.0;
  22842. var halfHeight = engine.getRenderHeight() / 2.0;
  22843. if (scene.useRightHandedSystem) {
  22844. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22845. }
  22846. else {
  22847. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22848. }
  22849. this._cache.orthoLeft = this.orthoLeft;
  22850. this._cache.orthoRight = this.orthoRight;
  22851. this._cache.orthoBottom = this.orthoBottom;
  22852. this._cache.orthoTop = this.orthoTop;
  22853. this._cache.renderWidth = engine.getRenderWidth();
  22854. this._cache.renderHeight = engine.getRenderHeight();
  22855. }
  22856. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22857. return this._projectionMatrix;
  22858. };
  22859. Camera.prototype.getTranformationMatrix = function () {
  22860. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22861. return this._transformMatrix;
  22862. };
  22863. Camera.prototype.updateFrustumPlanes = function () {
  22864. if (!this._refreshFrustumPlanes) {
  22865. return;
  22866. }
  22867. this.getTranformationMatrix();
  22868. if (!this._frustumPlanes) {
  22869. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22870. }
  22871. else {
  22872. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22873. }
  22874. this._refreshFrustumPlanes = false;
  22875. };
  22876. Camera.prototype.isInFrustum = function (target) {
  22877. this.updateFrustumPlanes();
  22878. return target.isInFrustum(this._frustumPlanes);
  22879. };
  22880. Camera.prototype.isCompletelyInFrustum = function (target) {
  22881. this.updateFrustumPlanes();
  22882. return target.isCompletelyInFrustum(this._frustumPlanes);
  22883. };
  22884. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22885. if (length === void 0) { length = 100; }
  22886. if (!transform) {
  22887. transform = this.getWorldMatrix();
  22888. }
  22889. if (!origin) {
  22890. origin = this.position;
  22891. }
  22892. var forward = new BABYLON.Vector3(0, 0, 1);
  22893. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22894. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22895. return new BABYLON.Ray(origin, direction, length);
  22896. };
  22897. /**
  22898. * Releases resources associated with this node.
  22899. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22900. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22901. */
  22902. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22903. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22904. // Observables
  22905. this.onViewMatrixChangedObservable.clear();
  22906. this.onProjectionMatrixChangedObservable.clear();
  22907. this.onAfterCheckInputsObservable.clear();
  22908. this.onRestoreStateObservable.clear();
  22909. // Inputs
  22910. if (this.inputs) {
  22911. this.inputs.clear();
  22912. }
  22913. // Animations
  22914. this.getScene().stopAnimation(this);
  22915. // Remove from scene
  22916. this.getScene().removeCamera(this);
  22917. while (this._rigCameras.length > 0) {
  22918. var camera = this._rigCameras.pop();
  22919. if (camera) {
  22920. camera.dispose();
  22921. }
  22922. }
  22923. // Postprocesses
  22924. if (this._rigPostProcess) {
  22925. this._rigPostProcess.dispose(this);
  22926. this._rigPostProcess = null;
  22927. this._postProcesses = [];
  22928. }
  22929. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22930. this._rigPostProcess = null;
  22931. this._postProcesses = [];
  22932. }
  22933. else {
  22934. var i = this._postProcesses.length;
  22935. while (--i >= 0) {
  22936. var postProcess = this._postProcesses[i];
  22937. if (postProcess) {
  22938. postProcess.dispose(this);
  22939. }
  22940. }
  22941. }
  22942. // Render targets
  22943. var i = this.customRenderTargets.length;
  22944. while (--i >= 0) {
  22945. this.customRenderTargets[i].dispose();
  22946. }
  22947. this.customRenderTargets = [];
  22948. // Active Meshes
  22949. this._activeMeshes.dispose();
  22950. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22951. };
  22952. Object.defineProperty(Camera.prototype, "leftCamera", {
  22953. // ---- Camera rigs section ----
  22954. get: function () {
  22955. if (this._rigCameras.length < 1) {
  22956. return null;
  22957. }
  22958. return this._rigCameras[0];
  22959. },
  22960. enumerable: true,
  22961. configurable: true
  22962. });
  22963. Object.defineProperty(Camera.prototype, "rightCamera", {
  22964. get: function () {
  22965. if (this._rigCameras.length < 2) {
  22966. return null;
  22967. }
  22968. return this._rigCameras[1];
  22969. },
  22970. enumerable: true,
  22971. configurable: true
  22972. });
  22973. Camera.prototype.getLeftTarget = function () {
  22974. if (this._rigCameras.length < 1) {
  22975. return null;
  22976. }
  22977. return this._rigCameras[0].getTarget();
  22978. };
  22979. Camera.prototype.getRightTarget = function () {
  22980. if (this._rigCameras.length < 2) {
  22981. return null;
  22982. }
  22983. return this._rigCameras[1].getTarget();
  22984. };
  22985. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22986. if (this.cameraRigMode === mode) {
  22987. return;
  22988. }
  22989. while (this._rigCameras.length > 0) {
  22990. var camera = this._rigCameras.pop();
  22991. if (camera) {
  22992. camera.dispose();
  22993. }
  22994. }
  22995. this.cameraRigMode = mode;
  22996. this._cameraRigParams = {};
  22997. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22998. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22999. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23000. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23001. // create the rig cameras, unless none
  23002. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23003. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23004. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23005. if (leftCamera && rightCamera) {
  23006. this._rigCameras.push(leftCamera);
  23007. this._rigCameras.push(rightCamera);
  23008. }
  23009. }
  23010. switch (this.cameraRigMode) {
  23011. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23012. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23013. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23014. break;
  23015. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23016. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23017. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23018. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23019. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23020. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23021. break;
  23022. case Camera.RIG_MODE_VR:
  23023. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23024. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23025. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23026. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23027. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23028. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23029. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23030. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23031. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23032. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23033. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23034. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23035. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23036. if (metrics.compensateDistortion) {
  23037. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23038. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23039. }
  23040. break;
  23041. case Camera.RIG_MODE_WEBVR:
  23042. if (rigParams.vrDisplay) {
  23043. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23044. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23045. //Left eye
  23046. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23047. this._rigCameras[0].setCameraRigParameter("left", true);
  23048. //leaving this for future reference
  23049. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23050. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23051. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23052. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23053. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23054. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23055. this._rigCameras[0].parent = this;
  23056. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23057. //Right eye
  23058. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23059. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23060. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23061. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23062. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23063. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23064. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23065. this._rigCameras[1].parent = this;
  23066. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23067. if (Camera.UseAlternateWebVRRendering) {
  23068. this._rigCameras[1]._skipRendering = true;
  23069. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23070. }
  23071. }
  23072. break;
  23073. }
  23074. this._cascadePostProcessesToRigCams();
  23075. this.update();
  23076. };
  23077. Camera.prototype._getVRProjectionMatrix = function () {
  23078. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23079. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23080. return this._projectionMatrix;
  23081. };
  23082. Camera.prototype._updateCameraRotationMatrix = function () {
  23083. //Here for WebVR
  23084. };
  23085. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23086. //Here for WebVR
  23087. };
  23088. /**
  23089. * This function MUST be overwritten by the different WebVR cameras available.
  23090. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23091. */
  23092. Camera.prototype._getWebVRProjectionMatrix = function () {
  23093. return BABYLON.Matrix.Identity();
  23094. };
  23095. /**
  23096. * This function MUST be overwritten by the different WebVR cameras available.
  23097. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23098. */
  23099. Camera.prototype._getWebVRViewMatrix = function () {
  23100. return BABYLON.Matrix.Identity();
  23101. };
  23102. Camera.prototype.setCameraRigParameter = function (name, value) {
  23103. if (!this._cameraRigParams) {
  23104. this._cameraRigParams = {};
  23105. }
  23106. this._cameraRigParams[name] = value;
  23107. //provisionnally:
  23108. if (name === "interaxialDistance") {
  23109. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23110. }
  23111. };
  23112. /**
  23113. * needs to be overridden by children so sub has required properties to be copied
  23114. */
  23115. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23116. return null;
  23117. };
  23118. /**
  23119. * May need to be overridden by children
  23120. */
  23121. Camera.prototype._updateRigCameras = function () {
  23122. for (var i = 0; i < this._rigCameras.length; i++) {
  23123. this._rigCameras[i].minZ = this.minZ;
  23124. this._rigCameras[i].maxZ = this.maxZ;
  23125. this._rigCameras[i].fov = this.fov;
  23126. }
  23127. // only update viewport when ANAGLYPH
  23128. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23129. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23130. }
  23131. };
  23132. Camera.prototype._setupInputs = function () {
  23133. };
  23134. Camera.prototype.serialize = function () {
  23135. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23136. // Type
  23137. serializationObject.type = this.getClassName();
  23138. // Parent
  23139. if (this.parent) {
  23140. serializationObject.parentId = this.parent.id;
  23141. }
  23142. if (this.inputs) {
  23143. this.inputs.serialize(serializationObject);
  23144. }
  23145. // Animations
  23146. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23147. serializationObject.ranges = this.serializeAnimationRanges();
  23148. return serializationObject;
  23149. };
  23150. Camera.prototype.clone = function (name) {
  23151. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23152. };
  23153. Camera.prototype.getDirection = function (localAxis) {
  23154. var result = BABYLON.Vector3.Zero();
  23155. this.getDirectionToRef(localAxis, result);
  23156. return result;
  23157. };
  23158. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23159. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23160. };
  23161. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23162. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23163. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23164. switch (type) {
  23165. case "ArcRotateCamera":
  23166. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23167. case "DeviceOrientationCamera":
  23168. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23169. case "FollowCamera":
  23170. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23171. case "ArcFollowCamera":
  23172. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23173. case "GamepadCamera":
  23174. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23175. case "TouchCamera":
  23176. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23177. case "VirtualJoysticksCamera":
  23178. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23179. case "WebVRFreeCamera":
  23180. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23181. case "WebVRGamepadCamera":
  23182. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23183. case "VRDeviceOrientationFreeCamera":
  23184. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23185. case "VRDeviceOrientationGamepadCamera":
  23186. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23187. case "AnaglyphArcRotateCamera":
  23188. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23189. case "AnaglyphFreeCamera":
  23190. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23191. case "AnaglyphGamepadCamera":
  23192. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23193. case "AnaglyphUniversalCamera":
  23194. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23195. case "StereoscopicArcRotateCamera":
  23196. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23197. case "StereoscopicFreeCamera":
  23198. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23199. case "StereoscopicGamepadCamera":
  23200. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23201. case "StereoscopicUniversalCamera":
  23202. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23203. case "FreeCamera": // Forcing Universal here
  23204. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23205. default: // Universal Camera is the default value
  23206. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23207. }
  23208. };
  23209. Camera.prototype.computeWorldMatrix = function () {
  23210. return this.getWorldMatrix();
  23211. };
  23212. Camera.Parse = function (parsedCamera, scene) {
  23213. var type = parsedCamera.type;
  23214. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23215. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23216. // Parent
  23217. if (parsedCamera.parentId) {
  23218. camera._waitingParentId = parsedCamera.parentId;
  23219. }
  23220. //If camera has an input manager, let it parse inputs settings
  23221. if (camera.inputs) {
  23222. camera.inputs.parse(parsedCamera);
  23223. camera._setupInputs();
  23224. }
  23225. if (camera.setPosition) { // need to force position
  23226. camera.position.copyFromFloats(0, 0, 0);
  23227. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23228. }
  23229. // Target
  23230. if (parsedCamera.target) {
  23231. if (camera.setTarget) {
  23232. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23233. }
  23234. }
  23235. // Apply 3d rig, when found
  23236. if (parsedCamera.cameraRigMode) {
  23237. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23238. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23239. }
  23240. // Animations
  23241. if (parsedCamera.animations) {
  23242. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23243. var parsedAnimation = parsedCamera.animations[animationIndex];
  23244. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23245. }
  23246. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23247. }
  23248. if (parsedCamera.autoAnimate) {
  23249. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23250. }
  23251. return camera;
  23252. };
  23253. // Statics
  23254. Camera._PERSPECTIVE_CAMERA = 0;
  23255. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23256. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23257. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23258. Camera._RIG_MODE_NONE = 0;
  23259. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23260. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23261. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23262. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23263. Camera._RIG_MODE_VR = 20;
  23264. Camera._RIG_MODE_WEBVR = 21;
  23265. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23266. Camera.UseAlternateWebVRRendering = false;
  23267. __decorate([
  23268. BABYLON.serializeAsVector3()
  23269. ], Camera.prototype, "position", void 0);
  23270. __decorate([
  23271. BABYLON.serializeAsVector3()
  23272. ], Camera.prototype, "upVector", void 0);
  23273. __decorate([
  23274. BABYLON.serialize()
  23275. ], Camera.prototype, "orthoLeft", void 0);
  23276. __decorate([
  23277. BABYLON.serialize()
  23278. ], Camera.prototype, "orthoRight", void 0);
  23279. __decorate([
  23280. BABYLON.serialize()
  23281. ], Camera.prototype, "orthoBottom", void 0);
  23282. __decorate([
  23283. BABYLON.serialize()
  23284. ], Camera.prototype, "orthoTop", void 0);
  23285. __decorate([
  23286. BABYLON.serialize()
  23287. ], Camera.prototype, "fov", void 0);
  23288. __decorate([
  23289. BABYLON.serialize()
  23290. ], Camera.prototype, "minZ", void 0);
  23291. __decorate([
  23292. BABYLON.serialize()
  23293. ], Camera.prototype, "maxZ", void 0);
  23294. __decorate([
  23295. BABYLON.serialize()
  23296. ], Camera.prototype, "inertia", void 0);
  23297. __decorate([
  23298. BABYLON.serialize()
  23299. ], Camera.prototype, "mode", void 0);
  23300. __decorate([
  23301. BABYLON.serialize()
  23302. ], Camera.prototype, "layerMask", void 0);
  23303. __decorate([
  23304. BABYLON.serialize()
  23305. ], Camera.prototype, "fovMode", void 0);
  23306. __decorate([
  23307. BABYLON.serialize()
  23308. ], Camera.prototype, "cameraRigMode", void 0);
  23309. __decorate([
  23310. BABYLON.serialize()
  23311. ], Camera.prototype, "interaxialDistance", void 0);
  23312. __decorate([
  23313. BABYLON.serialize()
  23314. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23315. return Camera;
  23316. }(BABYLON.Node));
  23317. BABYLON.Camera = Camera;
  23318. })(BABYLON || (BABYLON = {}));
  23319. //# sourceMappingURL=babylon.camera.js.map
  23320. var BABYLON;
  23321. (function (BABYLON) {
  23322. var RenderingManager = /** @class */ (function () {
  23323. function RenderingManager(scene) {
  23324. this._renderingGroups = new Array();
  23325. this._autoClearDepthStencil = {};
  23326. this._customOpaqueSortCompareFn = {};
  23327. this._customAlphaTestSortCompareFn = {};
  23328. this._customTransparentSortCompareFn = {};
  23329. this._renderinGroupInfo = null;
  23330. this._scene = scene;
  23331. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23332. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23333. }
  23334. }
  23335. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23336. if (depth === void 0) { depth = true; }
  23337. if (stencil === void 0) { stencil = true; }
  23338. if (this._depthStencilBufferAlreadyCleaned) {
  23339. return;
  23340. }
  23341. this._scene.getEngine().clear(null, false, depth, stencil);
  23342. this._depthStencilBufferAlreadyCleaned = true;
  23343. };
  23344. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23345. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23346. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23347. var info = null;
  23348. if (observable) {
  23349. if (!this._renderinGroupInfo) {
  23350. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23351. }
  23352. info = this._renderinGroupInfo;
  23353. info.scene = this._scene;
  23354. info.camera = this._scene.activeCamera;
  23355. }
  23356. // Dispatch sprites
  23357. if (renderSprites) {
  23358. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23359. var manager = this._scene.spriteManagers[index];
  23360. this.dispatchSprites(manager);
  23361. }
  23362. }
  23363. // Render
  23364. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23365. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23366. var renderingGroup = this._renderingGroups[index];
  23367. if (!renderingGroup && !observable)
  23368. continue;
  23369. var renderingGroupMask = 0;
  23370. // Fire PRECLEAR stage
  23371. if (observable && info) {
  23372. renderingGroupMask = Math.pow(2, index);
  23373. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23374. info.renderingGroupId = index;
  23375. observable.notifyObservers(info, renderingGroupMask);
  23376. }
  23377. // Clear depth/stencil if needed
  23378. if (RenderingManager.AUTOCLEAR) {
  23379. var autoClear = this._autoClearDepthStencil[index];
  23380. if (autoClear && autoClear.autoClear) {
  23381. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23382. }
  23383. }
  23384. if (observable && info) {
  23385. // Fire PREOPAQUE stage
  23386. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23387. observable.notifyObservers(info, renderingGroupMask);
  23388. // Fire PRETRANSPARENT stage
  23389. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23390. observable.notifyObservers(info, renderingGroupMask);
  23391. }
  23392. if (renderingGroup)
  23393. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23394. // Fire POSTTRANSPARENT stage
  23395. if (observable && info) {
  23396. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23397. observable.notifyObservers(info, renderingGroupMask);
  23398. }
  23399. }
  23400. };
  23401. RenderingManager.prototype.reset = function () {
  23402. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23403. var renderingGroup = this._renderingGroups[index];
  23404. if (renderingGroup) {
  23405. renderingGroup.prepare();
  23406. }
  23407. }
  23408. };
  23409. RenderingManager.prototype.dispose = function () {
  23410. this.freeRenderingGroups();
  23411. this._renderingGroups.length = 0;
  23412. };
  23413. /**
  23414. * Clear the info related to rendering groups preventing retention points during dispose.
  23415. */
  23416. RenderingManager.prototype.freeRenderingGroups = function () {
  23417. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23418. var renderingGroup = this._renderingGroups[index];
  23419. if (renderingGroup) {
  23420. renderingGroup.dispose();
  23421. }
  23422. }
  23423. };
  23424. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23425. if (this._renderingGroups[renderingGroupId] === undefined) {
  23426. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23427. }
  23428. };
  23429. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23430. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23431. this._prepareRenderingGroup(renderingGroupId);
  23432. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23433. };
  23434. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23435. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23436. this._prepareRenderingGroup(renderingGroupId);
  23437. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23438. };
  23439. /**
  23440. * @param subMesh The submesh to dispatch
  23441. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23442. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23443. */
  23444. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23445. if (mesh === undefined) {
  23446. mesh = subMesh.getMesh();
  23447. }
  23448. var renderingGroupId = mesh.renderingGroupId || 0;
  23449. this._prepareRenderingGroup(renderingGroupId);
  23450. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23451. };
  23452. /**
  23453. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23454. * This allowed control for front to back rendering or reversly depending of the special needs.
  23455. *
  23456. * @param renderingGroupId The rendering group id corresponding to its index
  23457. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23458. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23459. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23460. */
  23461. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23462. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23463. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23464. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23465. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23466. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23467. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23468. if (this._renderingGroups[renderingGroupId]) {
  23469. var group = this._renderingGroups[renderingGroupId];
  23470. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23471. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23472. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23473. }
  23474. };
  23475. /**
  23476. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23477. *
  23478. * @param renderingGroupId The rendering group id corresponding to its index
  23479. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23480. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23481. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23482. */
  23483. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23484. if (depth === void 0) { depth = true; }
  23485. if (stencil === void 0) { stencil = true; }
  23486. this._autoClearDepthStencil[renderingGroupId] = {
  23487. autoClear: autoClearDepthStencil,
  23488. depth: depth,
  23489. stencil: stencil
  23490. };
  23491. };
  23492. /**
  23493. * The max id used for rendering groups (not included)
  23494. */
  23495. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23496. /**
  23497. * The min id used for rendering groups (included)
  23498. */
  23499. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23500. /**
  23501. * Used to globally prevent autoclearing scenes.
  23502. */
  23503. RenderingManager.AUTOCLEAR = true;
  23504. return RenderingManager;
  23505. }());
  23506. BABYLON.RenderingManager = RenderingManager;
  23507. })(BABYLON || (BABYLON = {}));
  23508. //# sourceMappingURL=babylon.renderingManager.js.map
  23509. var BABYLON;
  23510. (function (BABYLON) {
  23511. var RenderingGroup = /** @class */ (function () {
  23512. /**
  23513. * Creates a new rendering group.
  23514. * @param index The rendering group index
  23515. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23516. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23517. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23518. */
  23519. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23520. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23521. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23522. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23523. this.index = index;
  23524. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23525. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23526. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23527. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23528. this._particleSystems = new BABYLON.SmartArray(256);
  23529. this._spriteManagers = new BABYLON.SmartArray(256);
  23530. this._edgesRenderers = new BABYLON.SmartArray(16);
  23531. this._scene = scene;
  23532. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23533. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23534. this.transparentSortCompareFn = transparentSortCompareFn;
  23535. }
  23536. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23537. /**
  23538. * Set the opaque sort comparison function.
  23539. * If null the sub meshes will be render in the order they were created
  23540. */
  23541. set: function (value) {
  23542. this._opaqueSortCompareFn = value;
  23543. if (value) {
  23544. this._renderOpaque = this.renderOpaqueSorted;
  23545. }
  23546. else {
  23547. this._renderOpaque = RenderingGroup.renderUnsorted;
  23548. }
  23549. },
  23550. enumerable: true,
  23551. configurable: true
  23552. });
  23553. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23554. /**
  23555. * Set the alpha test sort comparison function.
  23556. * If null the sub meshes will be render in the order they were created
  23557. */
  23558. set: function (value) {
  23559. this._alphaTestSortCompareFn = value;
  23560. if (value) {
  23561. this._renderAlphaTest = this.renderAlphaTestSorted;
  23562. }
  23563. else {
  23564. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23565. }
  23566. },
  23567. enumerable: true,
  23568. configurable: true
  23569. });
  23570. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23571. /**
  23572. * Set the transparent sort comparison function.
  23573. * If null the sub meshes will be render in the order they were created
  23574. */
  23575. set: function (value) {
  23576. if (value) {
  23577. this._transparentSortCompareFn = value;
  23578. }
  23579. else {
  23580. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23581. }
  23582. this._renderTransparent = this.renderTransparentSorted;
  23583. },
  23584. enumerable: true,
  23585. configurable: true
  23586. });
  23587. /**
  23588. * Render all the sub meshes contained in the group.
  23589. * @param customRenderFunction Used to override the default render behaviour of the group.
  23590. * @returns true if rendered some submeshes.
  23591. */
  23592. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23593. if (customRenderFunction) {
  23594. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23595. return;
  23596. }
  23597. var engine = this._scene.getEngine();
  23598. // Depth only
  23599. if (this._depthOnlySubMeshes.length !== 0) {
  23600. engine.setColorWrite(false);
  23601. this._renderAlphaTest(this._depthOnlySubMeshes);
  23602. engine.setColorWrite(true);
  23603. }
  23604. // Opaque
  23605. if (this._opaqueSubMeshes.length !== 0) {
  23606. this._renderOpaque(this._opaqueSubMeshes);
  23607. }
  23608. // Alpha test
  23609. if (this._alphaTestSubMeshes.length !== 0) {
  23610. this._renderAlphaTest(this._alphaTestSubMeshes);
  23611. }
  23612. var stencilState = engine.getStencilBuffer();
  23613. engine.setStencilBuffer(false);
  23614. // Sprites
  23615. if (renderSprites) {
  23616. this._renderSprites();
  23617. }
  23618. // Particles
  23619. if (renderParticles) {
  23620. this._renderParticles(activeMeshes);
  23621. }
  23622. if (this.onBeforeTransparentRendering) {
  23623. this.onBeforeTransparentRendering();
  23624. }
  23625. // Transparent
  23626. if (this._transparentSubMeshes.length !== 0) {
  23627. this._renderTransparent(this._transparentSubMeshes);
  23628. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23629. }
  23630. // Set back stencil to false in case it changes before the edge renderer.
  23631. engine.setStencilBuffer(false);
  23632. // Edges
  23633. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23634. this._edgesRenderers.data[edgesRendererIndex].render();
  23635. }
  23636. // Restore Stencil state.
  23637. engine.setStencilBuffer(stencilState);
  23638. };
  23639. /**
  23640. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23641. * @param subMeshes The submeshes to render
  23642. */
  23643. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23644. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23645. };
  23646. /**
  23647. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23648. * @param subMeshes The submeshes to render
  23649. */
  23650. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23651. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23652. };
  23653. /**
  23654. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23655. * @param subMeshes The submeshes to render
  23656. */
  23657. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23658. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23659. };
  23660. /**
  23661. * Renders the submeshes in a specified order.
  23662. * @param subMeshes The submeshes to sort before render
  23663. * @param sortCompareFn The comparison function use to sort
  23664. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23665. * @param transparent Specifies to activate blending if true
  23666. */
  23667. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23668. var subIndex = 0;
  23669. var subMesh;
  23670. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23671. for (; subIndex < subMeshes.length; subIndex++) {
  23672. subMesh = subMeshes.data[subIndex];
  23673. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23674. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23675. }
  23676. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23677. if (sortCompareFn) {
  23678. sortedArray.sort(sortCompareFn);
  23679. }
  23680. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23681. subMesh = sortedArray[subIndex];
  23682. if (transparent) {
  23683. var material = subMesh.getMaterial();
  23684. if (material && material.needDepthPrePass) {
  23685. var engine = material.getScene().getEngine();
  23686. engine.setColorWrite(false);
  23687. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23688. subMesh.render(false);
  23689. engine.setColorWrite(true);
  23690. }
  23691. }
  23692. subMesh.render(transparent);
  23693. }
  23694. };
  23695. /**
  23696. * Renders the submeshes in the order they were dispatched (no sort applied).
  23697. * @param subMeshes The submeshes to render
  23698. */
  23699. RenderingGroup.renderUnsorted = function (subMeshes) {
  23700. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23701. var submesh = subMeshes.data[subIndex];
  23702. submesh.render(false);
  23703. }
  23704. };
  23705. /**
  23706. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23707. * are rendered back to front if in the same alpha index.
  23708. *
  23709. * @param a The first submesh
  23710. * @param b The second submesh
  23711. * @returns The result of the comparison
  23712. */
  23713. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23714. // Alpha index first
  23715. if (a._alphaIndex > b._alphaIndex) {
  23716. return 1;
  23717. }
  23718. if (a._alphaIndex < b._alphaIndex) {
  23719. return -1;
  23720. }
  23721. // Then distance to camera
  23722. return RenderingGroup.backToFrontSortCompare(a, b);
  23723. };
  23724. /**
  23725. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23726. * are rendered back to front.
  23727. *
  23728. * @param a The first submesh
  23729. * @param b The second submesh
  23730. * @returns The result of the comparison
  23731. */
  23732. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23733. // Then distance to camera
  23734. if (a._distanceToCamera < b._distanceToCamera) {
  23735. return 1;
  23736. }
  23737. if (a._distanceToCamera > b._distanceToCamera) {
  23738. return -1;
  23739. }
  23740. return 0;
  23741. };
  23742. /**
  23743. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23744. * are rendered front to back (prevent overdraw).
  23745. *
  23746. * @param a The first submesh
  23747. * @param b The second submesh
  23748. * @returns The result of the comparison
  23749. */
  23750. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23751. // Then distance to camera
  23752. if (a._distanceToCamera < b._distanceToCamera) {
  23753. return -1;
  23754. }
  23755. if (a._distanceToCamera > b._distanceToCamera) {
  23756. return 1;
  23757. }
  23758. return 0;
  23759. };
  23760. /**
  23761. * Resets the different lists of submeshes to prepare a new frame.
  23762. */
  23763. RenderingGroup.prototype.prepare = function () {
  23764. this._opaqueSubMeshes.reset();
  23765. this._transparentSubMeshes.reset();
  23766. this._alphaTestSubMeshes.reset();
  23767. this._depthOnlySubMeshes.reset();
  23768. this._particleSystems.reset();
  23769. this._spriteManagers.reset();
  23770. this._edgesRenderers.reset();
  23771. };
  23772. RenderingGroup.prototype.dispose = function () {
  23773. this._opaqueSubMeshes.dispose();
  23774. this._transparentSubMeshes.dispose();
  23775. this._alphaTestSubMeshes.dispose();
  23776. this._depthOnlySubMeshes.dispose();
  23777. this._particleSystems.dispose();
  23778. this._spriteManagers.dispose();
  23779. this._edgesRenderers.dispose();
  23780. };
  23781. /**
  23782. * Inserts the submesh in its correct queue depending on its material.
  23783. * @param subMesh The submesh to dispatch
  23784. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23785. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23786. */
  23787. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23788. // Get mesh and materials if not provided
  23789. if (mesh === undefined) {
  23790. mesh = subMesh.getMesh();
  23791. }
  23792. if (material === undefined) {
  23793. material = subMesh.getMaterial();
  23794. }
  23795. if (material === null || material === undefined) {
  23796. return;
  23797. }
  23798. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23799. this._transparentSubMeshes.push(subMesh);
  23800. }
  23801. else if (material.needAlphaTesting()) { // Alpha test
  23802. if (material.needDepthPrePass) {
  23803. this._depthOnlySubMeshes.push(subMesh);
  23804. }
  23805. this._alphaTestSubMeshes.push(subMesh);
  23806. }
  23807. else {
  23808. if (material.needDepthPrePass) {
  23809. this._depthOnlySubMeshes.push(subMesh);
  23810. }
  23811. this._opaqueSubMeshes.push(subMesh); // Opaque
  23812. }
  23813. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23814. this._edgesRenderers.push(mesh._edgesRenderer);
  23815. }
  23816. };
  23817. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23818. this._spriteManagers.push(spriteManager);
  23819. };
  23820. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23821. this._particleSystems.push(particleSystem);
  23822. };
  23823. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23824. if (this._particleSystems.length === 0) {
  23825. return;
  23826. }
  23827. // Particles
  23828. var activeCamera = this._scene.activeCamera;
  23829. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23830. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23831. var particleSystem = this._particleSystems.data[particleIndex];
  23832. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23833. continue;
  23834. }
  23835. var emitter = particleSystem.emitter;
  23836. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23837. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23838. }
  23839. }
  23840. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23841. };
  23842. RenderingGroup.prototype._renderSprites = function () {
  23843. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23844. return;
  23845. }
  23846. // Sprites
  23847. var activeCamera = this._scene.activeCamera;
  23848. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23849. for (var id = 0; id < this._spriteManagers.length; id++) {
  23850. var spriteManager = this._spriteManagers.data[id];
  23851. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23852. spriteManager.render();
  23853. }
  23854. }
  23855. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23856. };
  23857. return RenderingGroup;
  23858. }());
  23859. BABYLON.RenderingGroup = RenderingGroup;
  23860. })(BABYLON || (BABYLON = {}));
  23861. //# sourceMappingURL=babylon.renderingGroup.js.map
  23862. var BABYLON;
  23863. (function (BABYLON) {
  23864. /** @hidden */
  23865. var ClickInfo = /** @class */ (function () {
  23866. function ClickInfo() {
  23867. this._singleClick = false;
  23868. this._doubleClick = false;
  23869. this._hasSwiped = false;
  23870. this._ignore = false;
  23871. }
  23872. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23873. get: function () {
  23874. return this._singleClick;
  23875. },
  23876. set: function (b) {
  23877. this._singleClick = b;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23883. get: function () {
  23884. return this._doubleClick;
  23885. },
  23886. set: function (b) {
  23887. this._doubleClick = b;
  23888. },
  23889. enumerable: true,
  23890. configurable: true
  23891. });
  23892. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23893. get: function () {
  23894. return this._hasSwiped;
  23895. },
  23896. set: function (b) {
  23897. this._hasSwiped = b;
  23898. },
  23899. enumerable: true,
  23900. configurable: true
  23901. });
  23902. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23903. get: function () {
  23904. return this._ignore;
  23905. },
  23906. set: function (b) {
  23907. this._ignore = b;
  23908. },
  23909. enumerable: true,
  23910. configurable: true
  23911. });
  23912. return ClickInfo;
  23913. }());
  23914. /**
  23915. * This class is used by the onRenderingGroupObservable
  23916. */
  23917. var RenderingGroupInfo = /** @class */ (function () {
  23918. function RenderingGroupInfo() {
  23919. }
  23920. /**
  23921. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23922. * This stage will be fired no matter what
  23923. */
  23924. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23925. /**
  23926. * Called before opaque object are rendered.
  23927. * This stage will be fired only if there's 3D Opaque content to render
  23928. */
  23929. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23930. /**
  23931. * Called after the opaque objects are rendered and before the transparent ones
  23932. * This stage will be fired only if there's 3D transparent content to render
  23933. */
  23934. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23935. /**
  23936. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23937. * This stage will be fired no matter what
  23938. */
  23939. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23940. return RenderingGroupInfo;
  23941. }());
  23942. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23943. /**
  23944. * Represents a scene to be rendered by the engine.
  23945. * @see http://doc.babylonjs.com/features/scene
  23946. */
  23947. var Scene = /** @class */ (function () {
  23948. /**
  23949. * Creates a new Scene
  23950. * @param engine defines the engine to use to render this scene
  23951. */
  23952. function Scene(engine) {
  23953. // Members
  23954. /**
  23955. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23956. */
  23957. this.autoClear = true;
  23958. /**
  23959. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23960. */
  23961. this.autoClearDepthAndStencil = true;
  23962. /**
  23963. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23964. */
  23965. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23966. /**
  23967. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23968. */
  23969. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23970. this._forceWireframe = false;
  23971. this._forcePointsCloud = false;
  23972. /**
  23973. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23974. */
  23975. this.forceShowBoundingBoxes = false;
  23976. /**
  23977. * Gets or sets a boolean indicating if animations are enabled
  23978. */
  23979. this.animationsEnabled = true;
  23980. this._animationPropertiesOverride = null;
  23981. /**
  23982. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23983. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23984. */
  23985. this.useConstantAnimationDeltaTime = false;
  23986. /**
  23987. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23988. * Please note that it requires to run a ray cast through the scene on every frame
  23989. */
  23990. this.constantlyUpdateMeshUnderPointer = false;
  23991. /**
  23992. * Defines the HTML cursor to use when hovering over interactive elements
  23993. */
  23994. this.hoverCursor = "pointer";
  23995. /**
  23996. * Defines the HTML default cursor to use (empty by default)
  23997. */
  23998. this.defaultCursor = "";
  23999. /**
  24000. * This is used to call preventDefault() on pointer down
  24001. * in order to block unwanted artifacts like system double clicks
  24002. */
  24003. this.preventDefaultOnPointerDown = true;
  24004. // Metadata
  24005. /**
  24006. * Gets or sets user defined metadata
  24007. */
  24008. this.metadata = null;
  24009. /**
  24010. * Use this array to add regular expressions used to disable offline support for specific urls
  24011. */
  24012. this.disableOfflineSupportExceptionRules = new Array();
  24013. /**
  24014. * An event triggered when the scene is disposed.
  24015. */
  24016. this.onDisposeObservable = new BABYLON.Observable();
  24017. this._onDisposeObserver = null;
  24018. /**
  24019. * An event triggered before rendering the scene (right after animations and physics)
  24020. */
  24021. this.onBeforeRenderObservable = new BABYLON.Observable();
  24022. this._onBeforeRenderObserver = null;
  24023. /**
  24024. * An event triggered after rendering the scene
  24025. */
  24026. this.onAfterRenderObservable = new BABYLON.Observable();
  24027. this._onAfterRenderObserver = null;
  24028. /**
  24029. * An event triggered before animating the scene
  24030. */
  24031. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24032. /**
  24033. * An event triggered after animations processing
  24034. */
  24035. this.onAfterAnimationsObservable = new BABYLON.Observable();
  24036. /**
  24037. * An event triggered before draw calls are ready to be sent
  24038. */
  24039. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24040. /**
  24041. * An event triggered after draw calls have been sent
  24042. */
  24043. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24044. /**
  24045. * An event triggered when physic simulation is about to be run
  24046. */
  24047. this.onBeforePhysicsObservable = new BABYLON.Observable();
  24048. /**
  24049. * An event triggered when physic simulation has been done
  24050. */
  24051. this.onAfterPhysicsObservable = new BABYLON.Observable();
  24052. /**
  24053. * An event triggered when the scene is ready
  24054. */
  24055. this.onReadyObservable = new BABYLON.Observable();
  24056. /**
  24057. * An event triggered before rendering a camera
  24058. */
  24059. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24060. this._onBeforeCameraRenderObserver = null;
  24061. /**
  24062. * An event triggered after rendering a camera
  24063. */
  24064. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24065. this._onAfterCameraRenderObserver = null;
  24066. /**
  24067. * An event triggered when active meshes evaluation is about to start
  24068. */
  24069. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24070. /**
  24071. * An event triggered when active meshes evaluation is done
  24072. */
  24073. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24074. /**
  24075. * An event triggered when particles rendering is about to start
  24076. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24077. */
  24078. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24079. /**
  24080. * An event triggered when particles rendering is done
  24081. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24082. */
  24083. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24084. /**
  24085. * An event triggered when sprites rendering is about to start
  24086. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24087. */
  24088. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24089. /**
  24090. * An event triggered when sprites rendering is done
  24091. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24092. */
  24093. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24094. /**
  24095. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24096. */
  24097. this.onDataLoadedObservable = new BABYLON.Observable();
  24098. /**
  24099. * An event triggered when a camera is created
  24100. */
  24101. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24102. /**
  24103. * An event triggered when a camera is removed
  24104. */
  24105. this.onCameraRemovedObservable = new BABYLON.Observable();
  24106. /**
  24107. * An event triggered when a light is created
  24108. */
  24109. this.onNewLightAddedObservable = new BABYLON.Observable();
  24110. /**
  24111. * An event triggered when a light is removed
  24112. */
  24113. this.onLightRemovedObservable = new BABYLON.Observable();
  24114. /**
  24115. * An event triggered when a geometry is created
  24116. */
  24117. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24118. /**
  24119. * An event triggered when a geometry is removed
  24120. */
  24121. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24122. /**
  24123. * An event triggered when a transform node is created
  24124. */
  24125. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24126. /**
  24127. * An event triggered when a transform node is removed
  24128. */
  24129. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24130. /**
  24131. * An event triggered when a mesh is created
  24132. */
  24133. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24134. /**
  24135. * An event triggered when a mesh is removed
  24136. */
  24137. this.onMeshRemovedObservable = new BABYLON.Observable();
  24138. /**
  24139. * An event triggered when render targets are about to be rendered
  24140. * Can happen multiple times per frame.
  24141. */
  24142. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24143. /**
  24144. * An event triggered when render targets were rendered.
  24145. * Can happen multiple times per frame.
  24146. */
  24147. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24148. /**
  24149. * An event triggered before calculating deterministic simulation step
  24150. */
  24151. this.onBeforeStepObservable = new BABYLON.Observable();
  24152. /**
  24153. * An event triggered after calculating deterministic simulation step
  24154. */
  24155. this.onAfterStepObservable = new BABYLON.Observable();
  24156. /**
  24157. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24158. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24159. * 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)
  24160. */
  24161. this.onRenderingGroupObservable = new BABYLON.Observable();
  24162. // Animations
  24163. /**
  24164. * Gets a list of Animations associated with the scene
  24165. */
  24166. this.animations = [];
  24167. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24168. /**
  24169. * 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).
  24170. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24171. */
  24172. this.onPrePointerObservable = new BABYLON.Observable();
  24173. /**
  24174. * Observable event triggered each time an input event is received from the rendering canvas
  24175. */
  24176. this.onPointerObservable = new BABYLON.Observable();
  24177. this._meshPickProceed = false;
  24178. this._currentPickResult = null;
  24179. this._previousPickResult = null;
  24180. this._totalPointersPressed = 0;
  24181. this._doubleClickOccured = false;
  24182. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24183. this.cameraToUseForPointers = null;
  24184. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24185. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24186. this._startingPointerTime = 0;
  24187. this._previousStartingPointerTime = 0;
  24188. this._pointerCaptures = {};
  24189. // Deterministic lockstep
  24190. this._timeAccumulator = 0;
  24191. this._currentStepId = 0;
  24192. this._currentInternalStep = 0;
  24193. // Keyboard
  24194. /**
  24195. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24196. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24197. */
  24198. this.onPreKeyboardObservable = new BABYLON.Observable();
  24199. /**
  24200. * Observable event triggered each time an keyboard event is received from the hosting window
  24201. */
  24202. this.onKeyboardObservable = new BABYLON.Observable();
  24203. // Coordinates system
  24204. this._useRightHandedSystem = false;
  24205. // Fog
  24206. this._fogEnabled = true;
  24207. this._fogMode = Scene.FOGMODE_NONE;
  24208. /**
  24209. * Gets or sets the fog color to use
  24210. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24211. */
  24212. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24213. /**
  24214. * Gets or sets the fog density to use
  24215. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24216. */
  24217. this.fogDensity = 0.1;
  24218. /**
  24219. * Gets or sets the fog start distance to use
  24220. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24221. */
  24222. this.fogStart = 0;
  24223. /**
  24224. * Gets or sets the fog end distance to use
  24225. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24226. */
  24227. this.fogEnd = 1000.0;
  24228. // Lights
  24229. this._shadowsEnabled = true;
  24230. this._lightsEnabled = true;
  24231. /**
  24232. * All of the lights added to this scene
  24233. * @see http://doc.babylonjs.com/babylon101/lights
  24234. */
  24235. this.lights = new Array();
  24236. // Cameras
  24237. /** All of the cameras added to this scene.
  24238. * @see http://doc.babylonjs.com/babylon101/cameras
  24239. */
  24240. this.cameras = new Array();
  24241. /** All of the active cameras added to this scene. */
  24242. this.activeCameras = new Array();
  24243. // Meshes
  24244. /**
  24245. * All of the tranform nodes added to this scene
  24246. * @see http://doc.babylonjs.com/how_to/transformnode
  24247. */
  24248. this.transformNodes = new Array();
  24249. /**
  24250. * All of the (abstract) meshes added to this scene
  24251. */
  24252. this.meshes = new Array();
  24253. /**
  24254. * All of the animation groups added to this scene
  24255. * @see http://doc.babylonjs.com/how_to/group
  24256. */
  24257. this.animationGroups = new Array();
  24258. // Geometries
  24259. this._geometries = new Array();
  24260. /**
  24261. * All of the materials added to this scene
  24262. * @see http://doc.babylonjs.com/babylon101/materials
  24263. */
  24264. this.materials = new Array();
  24265. /**
  24266. * All of the multi-materials added to this scene
  24267. * @see http://doc.babylonjs.com/how_to/multi_materials
  24268. */
  24269. this.multiMaterials = new Array();
  24270. // Textures
  24271. this._texturesEnabled = true;
  24272. /**
  24273. * All of the textures added to this scene
  24274. */
  24275. this.textures = new Array();
  24276. // Particles
  24277. /**
  24278. * Gets or sets a boolean indicating if particles are enabled on this scene
  24279. */
  24280. this.particlesEnabled = true;
  24281. /**
  24282. * All of the particle systems added to this scene
  24283. * @see http://doc.babylonjs.com/babylon101/particles
  24284. */
  24285. this.particleSystems = new Array();
  24286. // Sprites
  24287. /**
  24288. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24289. */
  24290. this.spritesEnabled = true;
  24291. /**
  24292. * All of the sprite managers added to this scene
  24293. * @see http://doc.babylonjs.com/babylon101/sprites
  24294. */
  24295. this.spriteManagers = new Array();
  24296. /**
  24297. * The list of layers (background and foreground) of the scene
  24298. */
  24299. this.layers = new Array();
  24300. /**
  24301. * The list of effect layers (highlights/glow) added to the scene
  24302. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24303. * @see http://doc.babylonjs.com/how_to/glow_layer
  24304. */
  24305. this.effectLayers = new Array();
  24306. // Skeletons
  24307. this._skeletonsEnabled = true;
  24308. /**
  24309. * The list of skeletons added to the scene
  24310. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24311. */
  24312. this.skeletons = new Array();
  24313. // Morph targets
  24314. /**
  24315. * The list of morph target managers added to the scene
  24316. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24317. */
  24318. this.morphTargetManagers = new Array();
  24319. // Lens flares
  24320. /**
  24321. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24322. */
  24323. this.lensFlaresEnabled = true;
  24324. /**
  24325. * The list of lens flare system added to the scene
  24326. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24327. */
  24328. this.lensFlareSystems = new Array();
  24329. // Collisions
  24330. /**
  24331. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24332. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24333. */
  24334. this.collisionsEnabled = true;
  24335. /**
  24336. * Defines the gravity applied to this scene (used only for collisions)
  24337. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24338. */
  24339. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24340. // Postprocesses
  24341. /**
  24342. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24343. */
  24344. this.postProcessesEnabled = true;
  24345. /**
  24346. * The list of postprocesses added to the scene
  24347. */
  24348. this.postProcesses = new Array();
  24349. // Customs render targets
  24350. /**
  24351. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24352. */
  24353. this.renderTargetsEnabled = true;
  24354. /**
  24355. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24356. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24357. */
  24358. this.dumpNextRenderTargets = false;
  24359. /**
  24360. * The list of user defined render targets added to the scene
  24361. */
  24362. this.customRenderTargets = new Array();
  24363. /**
  24364. * Gets the list of meshes imported to the scene through SceneLoader
  24365. */
  24366. this.importedMeshesFiles = new Array();
  24367. // Probes
  24368. /**
  24369. * Gets or sets a boolean indicating if probes are enabled on this scene
  24370. */
  24371. this.probesEnabled = true;
  24372. /**
  24373. * The list of reflection probes added to the scene
  24374. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24375. */
  24376. this.reflectionProbes = new Array();
  24377. /** @hidden */
  24378. this._actionManagers = new Array();
  24379. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24380. // Procedural textures
  24381. /**
  24382. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24383. */
  24384. this.proceduralTexturesEnabled = true;
  24385. /**
  24386. * The list of procedural textures added to the scene
  24387. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24388. */
  24389. this.proceduralTextures = new Array();
  24390. /**
  24391. * The list of sound tracks added to the scene
  24392. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24393. */
  24394. this.soundTracks = new Array();
  24395. this._audioEnabled = true;
  24396. this._headphone = false;
  24397. // Performance counters
  24398. this._totalVertices = new BABYLON.PerfCounter();
  24399. /** @hidden */
  24400. this._activeIndices = new BABYLON.PerfCounter();
  24401. /** @hidden */
  24402. this._activeParticles = new BABYLON.PerfCounter();
  24403. /** @hidden */
  24404. this._activeBones = new BABYLON.PerfCounter();
  24405. this._animationTime = 0;
  24406. /**
  24407. * Gets or sets a general scale for animation speed
  24408. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24409. */
  24410. this.animationTimeScale = 1;
  24411. this._renderId = 0;
  24412. this._executeWhenReadyTimeoutId = -1;
  24413. this._intermediateRendering = false;
  24414. this._viewUpdateFlag = -1;
  24415. this._projectionUpdateFlag = -1;
  24416. this._alternateViewUpdateFlag = -1;
  24417. this._alternateProjectionUpdateFlag = -1;
  24418. /** @hidden */
  24419. this._toBeDisposed = new BABYLON.SmartArray(256);
  24420. this._activeRequests = new Array();
  24421. this._pendingData = new Array();
  24422. this._isDisposed = false;
  24423. /**
  24424. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24425. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24426. */
  24427. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24428. this._activeMeshes = new BABYLON.SmartArray(256);
  24429. this._processedMaterials = new BABYLON.SmartArray(256);
  24430. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24431. /** @hidden */
  24432. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24433. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24434. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24435. /** @hidden */
  24436. this._activeAnimatables = new Array();
  24437. this._transformMatrix = BABYLON.Matrix.Zero();
  24438. this._useAlternateCameraConfiguration = false;
  24439. this._alternateRendering = false;
  24440. /**
  24441. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24442. * This is useful if there are more lights that the maximum simulteanous authorized
  24443. */
  24444. this.requireLightSorting = false;
  24445. this._depthRenderer = {};
  24446. this._activeMeshesFrozen = false;
  24447. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24448. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24449. this._engine.scenes.push(this);
  24450. this._uid = null;
  24451. this._renderingManager = new BABYLON.RenderingManager(this);
  24452. if (BABYLON.PostProcessManager) {
  24453. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24454. }
  24455. if (BABYLON.OutlineRenderer) {
  24456. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24457. }
  24458. if (BABYLON.Tools.IsWindowObjectExist()) {
  24459. this.attachControl();
  24460. }
  24461. //simplification queue
  24462. if (BABYLON.SimplificationQueue) {
  24463. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24464. }
  24465. //collision coordinator initialization. For now legacy per default.
  24466. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24467. // Uniform Buffer
  24468. this._createUbo();
  24469. // Default Image processing definition
  24470. if (BABYLON.ImageProcessingConfiguration) {
  24471. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24472. }
  24473. }
  24474. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24475. /** The fog is deactivated */
  24476. get: function () {
  24477. return Scene._FOGMODE_NONE;
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24483. /** The fog density is following an exponential function */
  24484. get: function () {
  24485. return Scene._FOGMODE_EXP;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24491. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24492. get: function () {
  24493. return Scene._FOGMODE_EXP2;
  24494. },
  24495. enumerable: true,
  24496. configurable: true
  24497. });
  24498. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24499. /** The fog density is following a linear function. */
  24500. get: function () {
  24501. return Scene._FOGMODE_LINEAR;
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24507. /**
  24508. * Texture used in all pbr material as the reflection texture.
  24509. * As in the majority of the scene they are the same (exception for multi room and so on),
  24510. * this is easier to reference from here than from all the materials.
  24511. */
  24512. get: function () {
  24513. return this._environmentTexture;
  24514. },
  24515. /**
  24516. * Texture used in all pbr material as the reflection texture.
  24517. * As in the majority of the scene they are the same (exception for multi room and so on),
  24518. * this is easier to set here than in all the materials.
  24519. */
  24520. set: function (value) {
  24521. if (this._environmentTexture === value) {
  24522. return;
  24523. }
  24524. this._environmentTexture = value;
  24525. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24526. },
  24527. enumerable: true,
  24528. configurable: true
  24529. });
  24530. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24531. /**
  24532. * Default image processing configuration used either in the rendering
  24533. * Forward main pass or through the imageProcessingPostProcess if present.
  24534. * As in the majority of the scene they are the same (exception for multi camera),
  24535. * this is easier to reference from here than from all the materials and post process.
  24536. *
  24537. * No setter as we it is a shared configuration, you can set the values instead.
  24538. */
  24539. get: function () {
  24540. return this._imageProcessingConfiguration;
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24546. get: function () {
  24547. return this._forceWireframe;
  24548. },
  24549. /**
  24550. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24551. */
  24552. set: function (value) {
  24553. if (this._forceWireframe === value) {
  24554. return;
  24555. }
  24556. this._forceWireframe = value;
  24557. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24563. get: function () {
  24564. return this._forcePointsCloud;
  24565. },
  24566. /**
  24567. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24568. */
  24569. set: function (value) {
  24570. if (this._forcePointsCloud === value) {
  24571. return;
  24572. }
  24573. this._forcePointsCloud = value;
  24574. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24580. /**
  24581. * Gets or sets the animation properties override
  24582. */
  24583. get: function () {
  24584. return this._animationPropertiesOverride;
  24585. },
  24586. set: function (value) {
  24587. this._animationPropertiesOverride = value;
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. Object.defineProperty(Scene.prototype, "onDispose", {
  24593. /** Sets a function to be executed when this scene is disposed. */
  24594. set: function (callback) {
  24595. if (this._onDisposeObserver) {
  24596. this.onDisposeObservable.remove(this._onDisposeObserver);
  24597. }
  24598. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24599. },
  24600. enumerable: true,
  24601. configurable: true
  24602. });
  24603. Object.defineProperty(Scene.prototype, "beforeRender", {
  24604. /** Sets a function to be executed before rendering this scene */
  24605. set: function (callback) {
  24606. if (this._onBeforeRenderObserver) {
  24607. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24608. }
  24609. if (callback) {
  24610. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24611. }
  24612. },
  24613. enumerable: true,
  24614. configurable: true
  24615. });
  24616. Object.defineProperty(Scene.prototype, "afterRender", {
  24617. /** Sets a function to be executed after rendering this scene */
  24618. set: function (callback) {
  24619. if (this._onAfterRenderObserver) {
  24620. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24621. }
  24622. if (callback) {
  24623. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24624. }
  24625. },
  24626. enumerable: true,
  24627. configurable: true
  24628. });
  24629. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24630. /** Sets a function to be executed before rendering a camera*/
  24631. set: function (callback) {
  24632. if (this._onBeforeCameraRenderObserver) {
  24633. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24634. }
  24635. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24636. },
  24637. enumerable: true,
  24638. configurable: true
  24639. });
  24640. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24641. /** Sets a function to be executed after rendering a camera*/
  24642. set: function (callback) {
  24643. if (this._onAfterCameraRenderObserver) {
  24644. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24645. }
  24646. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24652. /**
  24653. * Gets the gamepad manager associated with the scene
  24654. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24655. */
  24656. get: function () {
  24657. if (!this._gamepadManager) {
  24658. this._gamepadManager = new BABYLON.GamepadManager(this);
  24659. }
  24660. return this._gamepadManager;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24666. /**
  24667. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24668. */
  24669. get: function () {
  24670. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24671. },
  24672. enumerable: true,
  24673. configurable: true
  24674. });
  24675. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24676. get: function () {
  24677. return this._useRightHandedSystem;
  24678. },
  24679. /**
  24680. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24681. */
  24682. set: function (value) {
  24683. if (this._useRightHandedSystem === value) {
  24684. return;
  24685. }
  24686. this._useRightHandedSystem = value;
  24687. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. /**
  24693. * Sets the step Id used by deterministic lock step
  24694. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24695. * @param newStepId defines the step Id
  24696. */
  24697. Scene.prototype.setStepId = function (newStepId) {
  24698. this._currentStepId = newStepId;
  24699. };
  24700. ;
  24701. /**
  24702. * Gets the step Id used by deterministic lock step
  24703. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24704. * @returns the step Id
  24705. */
  24706. Scene.prototype.getStepId = function () {
  24707. return this._currentStepId;
  24708. };
  24709. ;
  24710. /**
  24711. * Gets the internal step used by deterministic lock step
  24712. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24713. * @returns the internal step
  24714. */
  24715. Scene.prototype.getInternalStep = function () {
  24716. return this._currentInternalStep;
  24717. };
  24718. ;
  24719. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24720. get: function () {
  24721. return this._fogEnabled;
  24722. },
  24723. /**
  24724. * Gets or sets a boolean indicating if fog is enabled on this scene
  24725. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24726. */
  24727. set: function (value) {
  24728. if (this._fogEnabled === value) {
  24729. return;
  24730. }
  24731. this._fogEnabled = value;
  24732. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. Object.defineProperty(Scene.prototype, "fogMode", {
  24738. get: function () {
  24739. return this._fogMode;
  24740. },
  24741. /**
  24742. * Gets or sets the fog mode to use
  24743. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24744. */
  24745. set: function (value) {
  24746. if (this._fogMode === value) {
  24747. return;
  24748. }
  24749. this._fogMode = value;
  24750. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24756. get: function () {
  24757. return this._shadowsEnabled;
  24758. },
  24759. /**
  24760. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24761. */
  24762. set: function (value) {
  24763. if (this._shadowsEnabled === value) {
  24764. return;
  24765. }
  24766. this._shadowsEnabled = value;
  24767. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24773. get: function () {
  24774. return this._lightsEnabled;
  24775. },
  24776. /**
  24777. * Gets or sets a boolean indicating if lights are enabled on this scene
  24778. */
  24779. set: function (value) {
  24780. if (this._lightsEnabled === value) {
  24781. return;
  24782. }
  24783. this._lightsEnabled = value;
  24784. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24785. },
  24786. enumerable: true,
  24787. configurable: true
  24788. });
  24789. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24790. /** The default material used on meshes when no material is affected */
  24791. get: function () {
  24792. if (!this._defaultMaterial) {
  24793. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24794. }
  24795. return this._defaultMaterial;
  24796. },
  24797. /** The default material used on meshes when no material is affected */
  24798. set: function (value) {
  24799. this._defaultMaterial = value;
  24800. },
  24801. enumerable: true,
  24802. configurable: true
  24803. });
  24804. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24805. get: function () {
  24806. return this._texturesEnabled;
  24807. },
  24808. /**
  24809. * Gets or sets a boolean indicating if textures are enabled on this scene
  24810. */
  24811. set: function (value) {
  24812. if (this._texturesEnabled === value) {
  24813. return;
  24814. }
  24815. this._texturesEnabled = value;
  24816. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24817. },
  24818. enumerable: true,
  24819. configurable: true
  24820. });
  24821. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24822. get: function () {
  24823. return this._skeletonsEnabled;
  24824. },
  24825. /**
  24826. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24827. */
  24828. set: function (value) {
  24829. if (this._skeletonsEnabled === value) {
  24830. return;
  24831. }
  24832. this._skeletonsEnabled = value;
  24833. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24839. /**
  24840. * Gets the postprocess render pipeline manager
  24841. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24842. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24843. */
  24844. get: function () {
  24845. if (!this._postProcessRenderPipelineManager) {
  24846. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24847. }
  24848. return this._postProcessRenderPipelineManager;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24854. /**
  24855. * Gets the main soundtrack associated with the scene
  24856. */
  24857. get: function () {
  24858. if (!this._mainSoundTrack) {
  24859. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24860. }
  24861. return this._mainSoundTrack;
  24862. },
  24863. enumerable: true,
  24864. configurable: true
  24865. });
  24866. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24867. /** @hidden */
  24868. get: function () {
  24869. return this._alternateRendering;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24875. /**
  24876. * Gets the list of frustum planes (built from the active camera)
  24877. */
  24878. get: function () {
  24879. return this._frustumPlanes;
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24885. /**
  24886. * Gets the current geometry buffer associated to the scene.
  24887. */
  24888. get: function () {
  24889. return this._geometryBufferRenderer;
  24890. },
  24891. /**
  24892. * Sets the current geometry buffer for the scene.
  24893. */
  24894. set: function (geometryBufferRenderer) {
  24895. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24896. this._geometryBufferRenderer = geometryBufferRenderer;
  24897. }
  24898. },
  24899. enumerable: true,
  24900. configurable: true
  24901. });
  24902. Object.defineProperty(Scene.prototype, "debugLayer", {
  24903. /**
  24904. * Gets the debug layer (aka Inspector) associated with the scene
  24905. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24906. */
  24907. get: function () {
  24908. if (!this._debugLayer) {
  24909. this._debugLayer = new BABYLON.DebugLayer(this);
  24910. }
  24911. return this._debugLayer;
  24912. },
  24913. enumerable: true,
  24914. configurable: true
  24915. });
  24916. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24917. /**
  24918. * Gets a boolean indicating if collisions are processed on a web worker
  24919. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24920. */
  24921. get: function () {
  24922. return this._workerCollisions;
  24923. },
  24924. set: function (enabled) {
  24925. if (!BABYLON.CollisionCoordinatorLegacy) {
  24926. return;
  24927. }
  24928. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24929. this._workerCollisions = enabled;
  24930. if (this.collisionCoordinator) {
  24931. this.collisionCoordinator.destroy();
  24932. }
  24933. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24934. this.collisionCoordinator.init(this);
  24935. },
  24936. enumerable: true,
  24937. configurable: true
  24938. });
  24939. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24940. /**
  24941. * Gets the octree used to boost mesh selection (picking)
  24942. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24943. */
  24944. get: function () {
  24945. return this._selectionOctree;
  24946. },
  24947. enumerable: true,
  24948. configurable: true
  24949. });
  24950. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24951. /**
  24952. * Gets the mesh that is currently under the pointer
  24953. */
  24954. get: function () {
  24955. return this._pointerOverMesh;
  24956. },
  24957. enumerable: true,
  24958. configurable: true
  24959. });
  24960. Object.defineProperty(Scene.prototype, "pointerX", {
  24961. /**
  24962. * Gets the current on-screen X position of the pointer
  24963. */
  24964. get: function () {
  24965. return this._pointerX;
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. Object.defineProperty(Scene.prototype, "pointerY", {
  24971. /**
  24972. * Gets the current on-screen Y position of the pointer
  24973. */
  24974. get: function () {
  24975. return this._pointerY;
  24976. },
  24977. enumerable: true,
  24978. configurable: true
  24979. });
  24980. /**
  24981. * Gets the cached material (ie. the latest rendered one)
  24982. * @returns the cached material
  24983. */
  24984. Scene.prototype.getCachedMaterial = function () {
  24985. return this._cachedMaterial;
  24986. };
  24987. /**
  24988. * Gets the cached effect (ie. the latest rendered one)
  24989. * @returns the cached effect
  24990. */
  24991. Scene.prototype.getCachedEffect = function () {
  24992. return this._cachedEffect;
  24993. };
  24994. /**
  24995. * Gets the cached visibility state (ie. the latest rendered one)
  24996. * @returns the cached visibility state
  24997. */
  24998. Scene.prototype.getCachedVisibility = function () {
  24999. return this._cachedVisibility;
  25000. };
  25001. /**
  25002. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25003. * @param material defines the current material
  25004. * @param effect defines the current effect
  25005. * @param visibility defines the current visibility state
  25006. * @returns true if one parameter is not cached
  25007. */
  25008. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25009. if (visibility === void 0) { visibility = 1; }
  25010. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25011. };
  25012. /**
  25013. * Gets the bounding box renderer associated with the scene
  25014. * @returns a BoundingBoxRenderer
  25015. */
  25016. Scene.prototype.getBoundingBoxRenderer = function () {
  25017. if (!this._boundingBoxRenderer) {
  25018. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  25019. }
  25020. return this._boundingBoxRenderer;
  25021. };
  25022. /**
  25023. * Gets the outline renderer associated with the scene
  25024. * @returns a OutlineRenderer
  25025. */
  25026. Scene.prototype.getOutlineRenderer = function () {
  25027. return this._outlineRenderer;
  25028. };
  25029. /**
  25030. * Gets the engine associated with the scene
  25031. * @returns an Engine
  25032. */
  25033. Scene.prototype.getEngine = function () {
  25034. return this._engine;
  25035. };
  25036. /**
  25037. * Gets the total number of vertices rendered per frame
  25038. * @returns the total number of vertices rendered per frame
  25039. */
  25040. Scene.prototype.getTotalVertices = function () {
  25041. return this._totalVertices.current;
  25042. };
  25043. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25044. /**
  25045. * Gets the performance counter for total vertices
  25046. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25047. */
  25048. get: function () {
  25049. return this._totalVertices;
  25050. },
  25051. enumerable: true,
  25052. configurable: true
  25053. });
  25054. /**
  25055. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25056. * @returns the total number of active indices rendered per frame
  25057. */
  25058. Scene.prototype.getActiveIndices = function () {
  25059. return this._activeIndices.current;
  25060. };
  25061. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25062. /**
  25063. * Gets the performance counter for active indices
  25064. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25065. */
  25066. get: function () {
  25067. return this._activeIndices;
  25068. },
  25069. enumerable: true,
  25070. configurable: true
  25071. });
  25072. /**
  25073. * Gets the total number of active particles rendered per frame
  25074. * @returns the total number of active particles rendered per frame
  25075. */
  25076. Scene.prototype.getActiveParticles = function () {
  25077. return this._activeParticles.current;
  25078. };
  25079. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25080. /**
  25081. * Gets the performance counter for active particles
  25082. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25083. */
  25084. get: function () {
  25085. return this._activeParticles;
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. /**
  25091. * Gets the total number of active bones rendered per frame
  25092. * @returns the total number of active bones rendered per frame
  25093. */
  25094. Scene.prototype.getActiveBones = function () {
  25095. return this._activeBones.current;
  25096. };
  25097. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25098. /**
  25099. * Gets the performance counter for active bones
  25100. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25101. */
  25102. get: function () {
  25103. return this._activeBones;
  25104. },
  25105. enumerable: true,
  25106. configurable: true
  25107. });
  25108. /** @hidden */
  25109. Scene.prototype.getInterFramePerfCounter = function () {
  25110. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25111. return 0;
  25112. };
  25113. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25114. /** @hidden */
  25115. get: function () {
  25116. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25117. return null;
  25118. },
  25119. enumerable: true,
  25120. configurable: true
  25121. });
  25122. /** @hidden */
  25123. Scene.prototype.getLastFrameDuration = function () {
  25124. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25125. return 0;
  25126. };
  25127. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25128. /** @hidden */
  25129. get: function () {
  25130. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25131. return null;
  25132. },
  25133. enumerable: true,
  25134. configurable: true
  25135. });
  25136. /** @hidden */
  25137. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25138. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25139. return 0;
  25140. };
  25141. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25142. /** @hidden */
  25143. get: function () {
  25144. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25145. return null;
  25146. },
  25147. enumerable: true,
  25148. configurable: true
  25149. });
  25150. /**
  25151. * Gets the array of active meshes
  25152. * @returns an array of AbstractMesh
  25153. */
  25154. Scene.prototype.getActiveMeshes = function () {
  25155. return this._activeMeshes;
  25156. };
  25157. /** @hidden */
  25158. Scene.prototype.getRenderTargetsDuration = function () {
  25159. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25160. return 0;
  25161. };
  25162. /** @hidden */
  25163. Scene.prototype.getRenderDuration = function () {
  25164. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25165. return 0;
  25166. };
  25167. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25168. /** @hidden */
  25169. get: function () {
  25170. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25171. return null;
  25172. },
  25173. enumerable: true,
  25174. configurable: true
  25175. });
  25176. /** @hidden */
  25177. Scene.prototype.getParticlesDuration = function () {
  25178. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25179. return 0;
  25180. };
  25181. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25182. /** @hidden */
  25183. get: function () {
  25184. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25185. return null;
  25186. },
  25187. enumerable: true,
  25188. configurable: true
  25189. });
  25190. /** @hidden */
  25191. Scene.prototype.getSpritesDuration = function () {
  25192. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25193. return 0;
  25194. };
  25195. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25196. /** @hidden */
  25197. get: function () {
  25198. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25199. return null;
  25200. },
  25201. enumerable: true,
  25202. configurable: true
  25203. });
  25204. /**
  25205. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25206. * @returns a number
  25207. */
  25208. Scene.prototype.getAnimationRatio = function () {
  25209. return this._animationRatio;
  25210. };
  25211. /**
  25212. * Gets an unique Id for the current frame
  25213. * @returns a number
  25214. */
  25215. Scene.prototype.getRenderId = function () {
  25216. return this._renderId;
  25217. };
  25218. /** Call this function if you want to manually increment the render Id*/
  25219. Scene.prototype.incrementRenderId = function () {
  25220. this._renderId++;
  25221. };
  25222. Scene.prototype._updatePointerPosition = function (evt) {
  25223. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25224. if (!canvasRect) {
  25225. return;
  25226. }
  25227. this._pointerX = evt.clientX - canvasRect.left;
  25228. this._pointerY = evt.clientY - canvasRect.top;
  25229. this._unTranslatedPointerX = this._pointerX;
  25230. this._unTranslatedPointerY = this._pointerY;
  25231. };
  25232. Scene.prototype._createUbo = function () {
  25233. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25234. this._sceneUbo.addUniform("viewProjection", 16);
  25235. this._sceneUbo.addUniform("view", 16);
  25236. };
  25237. Scene.prototype._createAlternateUbo = function () {
  25238. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25239. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25240. this._alternateSceneUbo.addUniform("view", 16);
  25241. };
  25242. // Pointers handling
  25243. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25244. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25245. if (result) {
  25246. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25247. }
  25248. return result;
  25249. };
  25250. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25251. if (pointerInfo.pickInfo) {
  25252. if (!pointerInfo.pickInfo.ray) {
  25253. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25254. }
  25255. }
  25256. };
  25257. /**
  25258. * Use this method to simulate a pointer move on a mesh
  25259. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25260. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25261. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25262. * @returns the current scene
  25263. */
  25264. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25265. var evt = new PointerEvent("pointermove", pointerEventInit);
  25266. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25267. return this;
  25268. }
  25269. return this._processPointerMove(pickResult, evt);
  25270. };
  25271. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25272. var canvas = this._engine.getRenderingCanvas();
  25273. if (!canvas) {
  25274. return this;
  25275. }
  25276. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25277. this.setPointerOverSprite(null);
  25278. this.setPointerOverMesh(pickResult.pickedMesh);
  25279. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25280. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25281. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25282. }
  25283. else {
  25284. canvas.style.cursor = this.hoverCursor;
  25285. }
  25286. }
  25287. else {
  25288. canvas.style.cursor = this.defaultCursor;
  25289. }
  25290. }
  25291. else {
  25292. this.setPointerOverMesh(null);
  25293. // Sprites
  25294. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25295. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25296. this.setPointerOverSprite(pickResult.pickedSprite);
  25297. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25298. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25299. }
  25300. else {
  25301. canvas.style.cursor = this.hoverCursor;
  25302. }
  25303. }
  25304. else {
  25305. this.setPointerOverSprite(null);
  25306. // Restore pointer
  25307. canvas.style.cursor = this.defaultCursor;
  25308. }
  25309. }
  25310. if (pickResult) {
  25311. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25312. if (this.onPointerMove) {
  25313. this.onPointerMove(evt, pickResult, type);
  25314. }
  25315. if (this.onPointerObservable.hasObservers()) {
  25316. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25317. this._setRayOnPointerInfo(pi);
  25318. this.onPointerObservable.notifyObservers(pi, type);
  25319. }
  25320. }
  25321. return this;
  25322. };
  25323. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25324. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25325. if (pickResult) {
  25326. pi.ray = pickResult.ray;
  25327. }
  25328. this.onPrePointerObservable.notifyObservers(pi, type);
  25329. if (pi.skipOnPointerObservable) {
  25330. return true;
  25331. }
  25332. else {
  25333. return false;
  25334. }
  25335. };
  25336. /**
  25337. * Use this method to simulate a pointer down on a mesh
  25338. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25339. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25340. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25341. * @returns the current scene
  25342. */
  25343. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25344. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25345. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25346. return this;
  25347. }
  25348. return this._processPointerDown(pickResult, evt);
  25349. };
  25350. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25351. var _this = this;
  25352. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25353. this._pickedDownMesh = pickResult.pickedMesh;
  25354. var actionManager = pickResult.pickedMesh.actionManager;
  25355. if (actionManager) {
  25356. if (actionManager.hasPickTriggers) {
  25357. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25358. switch (evt.button) {
  25359. case 0:
  25360. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25361. break;
  25362. case 1:
  25363. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25364. break;
  25365. case 2:
  25366. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25367. break;
  25368. }
  25369. }
  25370. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25371. window.setTimeout(function () {
  25372. 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);
  25373. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25374. if (_this._totalPointersPressed !== 0 &&
  25375. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25376. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25377. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25378. _this._startingPointerTime = 0;
  25379. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25380. }
  25381. }
  25382. }, Scene.LongPressDelay);
  25383. }
  25384. }
  25385. }
  25386. if (pickResult) {
  25387. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25388. if (this.onPointerDown) {
  25389. this.onPointerDown(evt, pickResult, type);
  25390. }
  25391. if (this.onPointerObservable.hasObservers()) {
  25392. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25393. this._setRayOnPointerInfo(pi);
  25394. this.onPointerObservable.notifyObservers(pi, type);
  25395. }
  25396. }
  25397. return this;
  25398. };
  25399. /**
  25400. * Use this method to simulate a pointer up on a mesh
  25401. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25402. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25403. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25404. * @returns the current scene
  25405. */
  25406. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25407. var evt = new PointerEvent("pointerup", pointerEventInit);
  25408. var clickInfo = new ClickInfo();
  25409. clickInfo.singleClick = true;
  25410. clickInfo.ignore = true;
  25411. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25412. return this;
  25413. }
  25414. return this._processPointerUp(pickResult, evt, clickInfo);
  25415. };
  25416. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25417. if (pickResult && pickResult && pickResult.pickedMesh) {
  25418. this._pickedUpMesh = pickResult.pickedMesh;
  25419. if (this._pickedDownMesh === this._pickedUpMesh) {
  25420. if (this.onPointerPick) {
  25421. this.onPointerPick(evt, pickResult);
  25422. }
  25423. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25424. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25425. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25426. this._setRayOnPointerInfo(pi);
  25427. this.onPointerObservable.notifyObservers(pi, type_1);
  25428. }
  25429. }
  25430. if (pickResult.pickedMesh.actionManager) {
  25431. if (clickInfo.ignore) {
  25432. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25433. }
  25434. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25435. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25436. }
  25437. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25438. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25439. }
  25440. }
  25441. }
  25442. if (this._pickedDownMesh &&
  25443. this._pickedDownMesh.actionManager &&
  25444. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25445. this._pickedDownMesh !== this._pickedUpMesh) {
  25446. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25447. }
  25448. var type = BABYLON.PointerEventTypes.POINTERUP;
  25449. if (this.onPointerObservable.hasObservers()) {
  25450. if (!clickInfo.ignore) {
  25451. if (!clickInfo.hasSwiped) {
  25452. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25453. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25454. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25455. this._setRayOnPointerInfo(pi);
  25456. this.onPointerObservable.notifyObservers(pi, type_2);
  25457. }
  25458. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25459. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25460. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25461. this._setRayOnPointerInfo(pi);
  25462. this.onPointerObservable.notifyObservers(pi, type_3);
  25463. }
  25464. }
  25465. }
  25466. else {
  25467. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25468. this._setRayOnPointerInfo(pi);
  25469. this.onPointerObservable.notifyObservers(pi, type);
  25470. }
  25471. }
  25472. if (this.onPointerUp) {
  25473. this.onPointerUp(evt, pickResult, type);
  25474. }
  25475. return this;
  25476. };
  25477. /**
  25478. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25479. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25480. * @returns true if the pointer was captured
  25481. */
  25482. Scene.prototype.isPointerCaptured = function (pointerId) {
  25483. if (pointerId === void 0) { pointerId = 0; }
  25484. return this._pointerCaptures[pointerId];
  25485. };
  25486. /**
  25487. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25488. * @param attachUp defines if you want to attach events to pointerup
  25489. * @param attachDown defines if you want to attach events to pointerdown
  25490. * @param attachMove defines if you want to attach events to pointermove
  25491. */
  25492. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25493. var _this = this;
  25494. if (attachUp === void 0) { attachUp = true; }
  25495. if (attachDown === void 0) { attachDown = true; }
  25496. if (attachMove === void 0) { attachMove = true; }
  25497. this._initActionManager = function (act, clickInfo) {
  25498. if (!_this._meshPickProceed) {
  25499. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25500. _this._currentPickResult = pickResult;
  25501. if (pickResult) {
  25502. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25503. }
  25504. _this._meshPickProceed = true;
  25505. }
  25506. return act;
  25507. };
  25508. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25509. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25510. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25511. btn !== _this._previousButtonPressed) {
  25512. _this._doubleClickOccured = false;
  25513. clickInfo.singleClick = true;
  25514. clickInfo.ignore = false;
  25515. cb(clickInfo, _this._currentPickResult);
  25516. }
  25517. };
  25518. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25519. var clickInfo = new ClickInfo();
  25520. _this._currentPickResult = null;
  25521. var act = null;
  25522. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25523. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25524. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25525. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25526. act = _this._initActionManager(act, clickInfo);
  25527. if (act)
  25528. checkPicking = act.hasPickTriggers;
  25529. }
  25530. if (checkPicking) {
  25531. var btn = evt.button;
  25532. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25533. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25534. if (!clickInfo.hasSwiped) {
  25535. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25536. if (!checkSingleClickImmediately) {
  25537. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25538. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25539. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25540. act = _this._initActionManager(act, clickInfo);
  25541. if (act)
  25542. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25543. }
  25544. }
  25545. if (checkSingleClickImmediately) {
  25546. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25547. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25548. btn !== _this._previousButtonPressed) {
  25549. clickInfo.singleClick = true;
  25550. cb(clickInfo, _this._currentPickResult);
  25551. }
  25552. }
  25553. // at least one double click is required to be check and exclusive double click is enabled
  25554. else {
  25555. // wait that no double click has been raised during the double click delay
  25556. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25557. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25558. }
  25559. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25560. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25561. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25562. act = _this._initActionManager(act, clickInfo);
  25563. if (act)
  25564. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25565. }
  25566. if (checkDoubleClick) {
  25567. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25568. if (btn === _this._previousButtonPressed &&
  25569. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25570. !_this._doubleClickOccured) {
  25571. // pointer has not moved for 2 clicks, it's a double click
  25572. if (!clickInfo.hasSwiped &&
  25573. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25574. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25575. _this._previousStartingPointerTime = 0;
  25576. _this._doubleClickOccured = true;
  25577. clickInfo.doubleClick = true;
  25578. clickInfo.ignore = false;
  25579. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25580. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25581. }
  25582. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25583. cb(clickInfo, _this._currentPickResult);
  25584. }
  25585. // if the two successive clicks are too far, it's just two simple clicks
  25586. else {
  25587. _this._doubleClickOccured = false;
  25588. _this._previousStartingPointerTime = _this._startingPointerTime;
  25589. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25590. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25591. _this._previousButtonPressed = btn;
  25592. if (Scene.ExclusiveDoubleClickMode) {
  25593. if (_this._previousDelayedSimpleClickTimeout) {
  25594. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25595. }
  25596. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25597. cb(clickInfo, _this._previousPickResult);
  25598. }
  25599. else {
  25600. cb(clickInfo, _this._currentPickResult);
  25601. }
  25602. }
  25603. }
  25604. // just the first click of the double has been raised
  25605. else {
  25606. _this._doubleClickOccured = false;
  25607. _this._previousStartingPointerTime = _this._startingPointerTime;
  25608. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25609. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25610. _this._previousButtonPressed = btn;
  25611. }
  25612. }
  25613. }
  25614. }
  25615. clickInfo.ignore = true;
  25616. cb(clickInfo, _this._currentPickResult);
  25617. };
  25618. this._spritePredicate = function (sprite) {
  25619. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25620. };
  25621. this._onPointerMove = function (evt) {
  25622. _this._updatePointerPosition(evt);
  25623. // PreObservable support
  25624. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25625. return;
  25626. }
  25627. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25628. return;
  25629. }
  25630. if (!_this.pointerMovePredicate) {
  25631. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25632. }
  25633. // Meshes
  25634. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25635. _this._processPointerMove(pickResult, evt);
  25636. };
  25637. this._onPointerDown = function (evt) {
  25638. _this._totalPointersPressed++;
  25639. _this._pickedDownMesh = null;
  25640. _this._meshPickProceed = false;
  25641. _this._updatePointerPosition(evt);
  25642. if (_this.preventDefaultOnPointerDown && canvas) {
  25643. evt.preventDefault();
  25644. canvas.focus();
  25645. }
  25646. // PreObservable support
  25647. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25648. return;
  25649. }
  25650. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25651. return;
  25652. }
  25653. _this._pointerCaptures[evt.pointerId] = true;
  25654. _this._startingPointerPosition.x = _this._pointerX;
  25655. _this._startingPointerPosition.y = _this._pointerY;
  25656. _this._startingPointerTime = Date.now();
  25657. if (!_this.pointerDownPredicate) {
  25658. _this.pointerDownPredicate = function (mesh) {
  25659. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25660. };
  25661. }
  25662. // Meshes
  25663. _this._pickedDownMesh = null;
  25664. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25665. _this._processPointerDown(pickResult, evt);
  25666. // Sprites
  25667. _this._pickedDownSprite = null;
  25668. if (_this.spriteManagers.length > 0) {
  25669. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25670. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25671. if (pickResult.pickedSprite.actionManager) {
  25672. _this._pickedDownSprite = pickResult.pickedSprite;
  25673. switch (evt.button) {
  25674. case 0:
  25675. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25676. break;
  25677. case 1:
  25678. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25679. break;
  25680. case 2:
  25681. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25682. break;
  25683. }
  25684. if (pickResult.pickedSprite.actionManager) {
  25685. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25686. }
  25687. }
  25688. }
  25689. }
  25690. };
  25691. this._onPointerUp = function (evt) {
  25692. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25693. return; // So we need to test it the pointer down was pressed before.
  25694. }
  25695. _this._totalPointersPressed--;
  25696. _this._pickedUpMesh = null;
  25697. _this._meshPickProceed = false;
  25698. _this._updatePointerPosition(evt);
  25699. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25700. // PreObservable support
  25701. if (_this.onPrePointerObservable.hasObservers()) {
  25702. if (!clickInfo.ignore) {
  25703. if (!clickInfo.hasSwiped) {
  25704. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25705. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25706. return;
  25707. }
  25708. }
  25709. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25710. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25711. return;
  25712. }
  25713. }
  25714. }
  25715. }
  25716. else {
  25717. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25718. return;
  25719. }
  25720. }
  25721. }
  25722. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25723. return;
  25724. }
  25725. _this._pointerCaptures[evt.pointerId] = false;
  25726. if (!_this.pointerUpPredicate) {
  25727. _this.pointerUpPredicate = function (mesh) {
  25728. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25729. };
  25730. }
  25731. // Meshes
  25732. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25733. _this._initActionManager(null, clickInfo);
  25734. }
  25735. if (!pickResult) {
  25736. pickResult = _this._currentPickResult;
  25737. }
  25738. _this._processPointerUp(pickResult, evt, clickInfo);
  25739. // Sprites
  25740. if (!clickInfo.ignore) {
  25741. if (_this.spriteManagers.length > 0) {
  25742. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25743. if (spritePickResult) {
  25744. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25745. if (spritePickResult.pickedSprite.actionManager) {
  25746. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25747. if (spritePickResult.pickedSprite.actionManager) {
  25748. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25749. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25750. }
  25751. }
  25752. }
  25753. }
  25754. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25755. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25756. }
  25757. }
  25758. }
  25759. }
  25760. _this._previousPickResult = _this._currentPickResult;
  25761. });
  25762. };
  25763. this._onKeyDown = function (evt) {
  25764. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25765. if (_this.onPreKeyboardObservable.hasObservers()) {
  25766. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25767. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25768. if (pi.skipOnPointerObservable) {
  25769. return;
  25770. }
  25771. }
  25772. if (_this.onKeyboardObservable.hasObservers()) {
  25773. var pi = new BABYLON.KeyboardInfo(type, evt);
  25774. _this.onKeyboardObservable.notifyObservers(pi, type);
  25775. }
  25776. if (_this.actionManager) {
  25777. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25778. }
  25779. };
  25780. this._onKeyUp = function (evt) {
  25781. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25782. if (_this.onPreKeyboardObservable.hasObservers()) {
  25783. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25784. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25785. if (pi.skipOnPointerObservable) {
  25786. return;
  25787. }
  25788. }
  25789. if (_this.onKeyboardObservable.hasObservers()) {
  25790. var pi = new BABYLON.KeyboardInfo(type, evt);
  25791. _this.onKeyboardObservable.notifyObservers(pi, type);
  25792. }
  25793. if (_this.actionManager) {
  25794. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25795. }
  25796. };
  25797. var engine = this.getEngine();
  25798. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25799. if (!canvas) {
  25800. return;
  25801. }
  25802. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25803. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25804. });
  25805. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25806. if (!canvas) {
  25807. return;
  25808. }
  25809. canvas.removeEventListener("keydown", _this._onKeyDown);
  25810. canvas.removeEventListener("keyup", _this._onKeyUp);
  25811. });
  25812. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25813. var canvas = this._engine.getRenderingCanvas();
  25814. if (!canvas) {
  25815. return;
  25816. }
  25817. if (attachMove) {
  25818. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25819. // Wheel
  25820. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25821. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25822. }
  25823. if (attachDown) {
  25824. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25825. }
  25826. if (attachUp) {
  25827. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25828. }
  25829. canvas.tabIndex = 1;
  25830. };
  25831. /** Detaches all event handlers*/
  25832. Scene.prototype.detachControl = function () {
  25833. var engine = this.getEngine();
  25834. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25835. var canvas = engine.getRenderingCanvas();
  25836. if (!canvas) {
  25837. return;
  25838. }
  25839. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25840. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25841. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25842. if (this._onCanvasBlurObserver) {
  25843. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25844. }
  25845. if (this._onCanvasFocusObserver) {
  25846. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25847. }
  25848. // Wheel
  25849. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25850. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25851. // Keyboard
  25852. canvas.removeEventListener("keydown", this._onKeyDown);
  25853. canvas.removeEventListener("keyup", this._onKeyUp);
  25854. // Observables
  25855. this.onKeyboardObservable.clear();
  25856. this.onPreKeyboardObservable.clear();
  25857. this.onPointerObservable.clear();
  25858. this.onPrePointerObservable.clear();
  25859. };
  25860. /**
  25861. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25862. * Delay loaded resources are not taking in account
  25863. * @return true if all required resources are ready
  25864. */
  25865. Scene.prototype.isReady = function () {
  25866. if (this._isDisposed) {
  25867. return false;
  25868. }
  25869. if (this._pendingData.length > 0) {
  25870. return false;
  25871. }
  25872. var index;
  25873. var engine = this.getEngine();
  25874. // Geometries
  25875. for (index = 0; index < this._geometries.length; index++) {
  25876. var geometry = this._geometries[index];
  25877. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25878. return false;
  25879. }
  25880. }
  25881. // Meshes
  25882. for (index = 0; index < this.meshes.length; index++) {
  25883. var mesh = this.meshes[index];
  25884. if (!mesh.isEnabled()) {
  25885. continue;
  25886. }
  25887. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25888. continue;
  25889. }
  25890. if (!mesh.isReady(true)) {
  25891. return false;
  25892. }
  25893. // Effect layers
  25894. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25895. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25896. var layer = _a[_i];
  25897. if (!layer.hasMesh(mesh)) {
  25898. continue;
  25899. }
  25900. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25901. var subMesh = _c[_b];
  25902. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25903. return false;
  25904. }
  25905. }
  25906. }
  25907. }
  25908. // Post-processes
  25909. if (this.activeCameras && this.activeCameras.length > 0) {
  25910. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25911. var camera = _e[_d];
  25912. if (!camera.isReady(true)) {
  25913. return false;
  25914. }
  25915. }
  25916. }
  25917. else if (this.activeCamera) {
  25918. if (!this.activeCamera.isReady(true)) {
  25919. return false;
  25920. }
  25921. }
  25922. // Particles
  25923. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25924. var particleSystem = _g[_f];
  25925. if (!particleSystem.isReady()) {
  25926. return false;
  25927. }
  25928. }
  25929. return true;
  25930. };
  25931. /** Resets all cached information relative to material (including effect and visibility) */
  25932. Scene.prototype.resetCachedMaterial = function () {
  25933. this._cachedMaterial = null;
  25934. this._cachedEffect = null;
  25935. this._cachedVisibility = null;
  25936. };
  25937. /**
  25938. * Registers a function to be called before every frame render
  25939. * @param func defines the function to register
  25940. */
  25941. Scene.prototype.registerBeforeRender = function (func) {
  25942. this.onBeforeRenderObservable.add(func);
  25943. };
  25944. /**
  25945. * Unregisters a function called before every frame render
  25946. * @param func defines the function to unregister
  25947. */
  25948. Scene.prototype.unregisterBeforeRender = function (func) {
  25949. this.onBeforeRenderObservable.removeCallback(func);
  25950. };
  25951. /**
  25952. * Registers a function to be called after every frame render
  25953. * @param func defines the function to register
  25954. */
  25955. Scene.prototype.registerAfterRender = function (func) {
  25956. this.onAfterRenderObservable.add(func);
  25957. };
  25958. /**
  25959. * Unregisters a function called after every frame render
  25960. * @param func defines the function to unregister
  25961. */
  25962. Scene.prototype.unregisterAfterRender = function (func) {
  25963. this.onAfterRenderObservable.removeCallback(func);
  25964. };
  25965. Scene.prototype._executeOnceBeforeRender = function (func) {
  25966. var _this = this;
  25967. var execFunc = function () {
  25968. func();
  25969. setTimeout(function () {
  25970. _this.unregisterBeforeRender(execFunc);
  25971. });
  25972. };
  25973. this.registerBeforeRender(execFunc);
  25974. };
  25975. /**
  25976. * The provided function will run before render once and will be disposed afterwards.
  25977. * A timeout delay can be provided so that the function will be executed in N ms.
  25978. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25979. * @param func The function to be executed.
  25980. * @param timeout optional delay in ms
  25981. */
  25982. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25983. var _this = this;
  25984. if (timeout !== undefined) {
  25985. setTimeout(function () {
  25986. _this._executeOnceBeforeRender(func);
  25987. }, timeout);
  25988. }
  25989. else {
  25990. this._executeOnceBeforeRender(func);
  25991. }
  25992. };
  25993. /** @hidden */
  25994. Scene.prototype._addPendingData = function (data) {
  25995. this._pendingData.push(data);
  25996. };
  25997. /** @hidden */
  25998. Scene.prototype._removePendingData = function (data) {
  25999. var wasLoading = this.isLoading;
  26000. var index = this._pendingData.indexOf(data);
  26001. if (index !== -1) {
  26002. this._pendingData.splice(index, 1);
  26003. }
  26004. if (wasLoading && !this.isLoading) {
  26005. this.onDataLoadedObservable.notifyObservers(this);
  26006. }
  26007. };
  26008. /**
  26009. * Returns the number of items waiting to be loaded
  26010. * @returns the number of items waiting to be loaded
  26011. */
  26012. Scene.prototype.getWaitingItemsCount = function () {
  26013. return this._pendingData.length;
  26014. };
  26015. Object.defineProperty(Scene.prototype, "isLoading", {
  26016. /**
  26017. * Returns a boolean indicating if the scene is still loading data
  26018. */
  26019. get: function () {
  26020. return this._pendingData.length > 0;
  26021. },
  26022. enumerable: true,
  26023. configurable: true
  26024. });
  26025. /**
  26026. * Registers a function to be executed when the scene is ready
  26027. * @param {Function} func - the function to be executed
  26028. */
  26029. Scene.prototype.executeWhenReady = function (func) {
  26030. var _this = this;
  26031. this.onReadyObservable.add(func);
  26032. if (this._executeWhenReadyTimeoutId !== -1) {
  26033. return;
  26034. }
  26035. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26036. _this._checkIsReady();
  26037. }, 150);
  26038. };
  26039. /**
  26040. * Returns a promise that resolves when the scene is ready
  26041. * @returns A promise that resolves when the scene is ready
  26042. */
  26043. Scene.prototype.whenReadyAsync = function () {
  26044. var _this = this;
  26045. return new Promise(function (resolve) {
  26046. _this.executeWhenReady(function () {
  26047. resolve();
  26048. });
  26049. });
  26050. };
  26051. /** @hidden */
  26052. Scene.prototype._checkIsReady = function () {
  26053. var _this = this;
  26054. if (this.isReady()) {
  26055. this.onReadyObservable.notifyObservers(this);
  26056. this.onReadyObservable.clear();
  26057. this._executeWhenReadyTimeoutId = -1;
  26058. return;
  26059. }
  26060. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26061. _this._checkIsReady();
  26062. }, 150);
  26063. };
  26064. // Animations
  26065. /**
  26066. * Will start the animation sequence of a given target
  26067. * @param target defines the target
  26068. * @param from defines from which frame should animation start
  26069. * @param to defines until which frame should animation run.
  26070. * @param weight defines the weight to apply to the animation (1.0 by default)
  26071. * @param loop defines if the animation loops
  26072. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26073. * @param onAnimationEnd defines the function to be executed when the animation ends
  26074. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26075. * @returns the animatable object created for this animation
  26076. */
  26077. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26078. if (weight === void 0) { weight = 1.0; }
  26079. if (speedRatio === void 0) { speedRatio = 1.0; }
  26080. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26081. returnedAnimatable.weight = weight;
  26082. return returnedAnimatable;
  26083. };
  26084. /**
  26085. * Will start the animation sequence of a given target
  26086. * @param target defines the target
  26087. * @param from defines from which frame should animation start
  26088. * @param to defines until which frame should animation run.
  26089. * @param loop defines if the animation loops
  26090. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26091. * @param onAnimationEnd defines the function to be executed when the animation ends
  26092. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26093. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26094. * @returns the animatable object created for this animation
  26095. */
  26096. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26097. if (speedRatio === void 0) { speedRatio = 1.0; }
  26098. if (stopCurrent === void 0) { stopCurrent = true; }
  26099. if (from > to && speedRatio > 0) {
  26100. speedRatio *= -1;
  26101. }
  26102. if (stopCurrent) {
  26103. this.stopAnimation(target);
  26104. }
  26105. if (!animatable) {
  26106. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26107. }
  26108. // Local animations
  26109. if (target.animations) {
  26110. animatable.appendAnimations(target, target.animations);
  26111. }
  26112. // Children animations
  26113. if (target.getAnimatables) {
  26114. var animatables = target.getAnimatables();
  26115. for (var index = 0; index < animatables.length; index++) {
  26116. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26117. }
  26118. }
  26119. animatable.reset();
  26120. return animatable;
  26121. };
  26122. /**
  26123. * Begin a new animation on a given node
  26124. * @param target defines the target where the animation will take place
  26125. * @param animations defines the list of animations to start
  26126. * @param from defines the initial value
  26127. * @param to defines the final value
  26128. * @param loop defines if you want animation to loop (off by default)
  26129. * @param speedRatio defines the speed ratio to apply to all animations
  26130. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26131. * @returns the list of created animatables
  26132. */
  26133. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26134. if (speedRatio === undefined) {
  26135. speedRatio = 1.0;
  26136. }
  26137. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26138. return animatable;
  26139. };
  26140. /**
  26141. * Begin a new animation on a given node and its hierarchy
  26142. * @param target defines the root node where the animation will take place
  26143. * @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.
  26144. * @param animations defines the list of animations to start
  26145. * @param from defines the initial value
  26146. * @param to defines the final value
  26147. * @param loop defines if you want animation to loop (off by default)
  26148. * @param speedRatio defines the speed ratio to apply to all animations
  26149. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26150. * @returns the list of animatables created for all nodes
  26151. */
  26152. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26153. var children = target.getDescendants(directDescendantsOnly);
  26154. var result = [];
  26155. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26156. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26157. var child = children_1[_i];
  26158. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26159. }
  26160. return result;
  26161. };
  26162. /**
  26163. * Gets the animatable associated with a specific target
  26164. * @param target defines the target of the animatable
  26165. * @returns the required animatable if found
  26166. */
  26167. Scene.prototype.getAnimatableByTarget = function (target) {
  26168. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26169. if (this._activeAnimatables[index].target === target) {
  26170. return this._activeAnimatables[index];
  26171. }
  26172. }
  26173. return null;
  26174. };
  26175. /**
  26176. * Gets all animatables associated with a given target
  26177. * @param target defines the target to look animatables for
  26178. * @returns an array of Animatables
  26179. */
  26180. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26181. var result = [];
  26182. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26183. if (this._activeAnimatables[index].target === target) {
  26184. result.push(this._activeAnimatables[index]);
  26185. }
  26186. }
  26187. return result;
  26188. };
  26189. Object.defineProperty(Scene.prototype, "animatables", {
  26190. /**
  26191. * Gets all animatable attached to the scene
  26192. */
  26193. get: function () {
  26194. return this._activeAnimatables;
  26195. },
  26196. enumerable: true,
  26197. configurable: true
  26198. });
  26199. /**
  26200. * Will stop the animation of the given target
  26201. * @param target - the target
  26202. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26203. */
  26204. Scene.prototype.stopAnimation = function (target, animationName) {
  26205. var animatables = this.getAllAnimatablesByTarget(target);
  26206. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26207. var animatable = animatables_1[_i];
  26208. animatable.stop(animationName);
  26209. }
  26210. };
  26211. /**
  26212. * Stops and removes all animations that have been applied to the scene
  26213. */
  26214. Scene.prototype.stopAllAnimations = function () {
  26215. if (this._activeAnimatables) {
  26216. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26217. this._activeAnimatables[i].stop();
  26218. }
  26219. this._activeAnimatables = [];
  26220. }
  26221. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26222. var group = _a[_i];
  26223. group.stop();
  26224. }
  26225. };
  26226. Scene.prototype._animate = function () {
  26227. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26228. return;
  26229. }
  26230. // Getting time
  26231. var now = BABYLON.Tools.Now;
  26232. if (!this._animationTimeLast) {
  26233. if (this._pendingData.length > 0) {
  26234. return;
  26235. }
  26236. this._animationTimeLast = now;
  26237. }
  26238. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26239. this._animationTime += deltaTime;
  26240. this._animationTimeLast = now;
  26241. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26242. this._activeAnimatables[index]._animate(this._animationTime);
  26243. }
  26244. // Late animation bindings
  26245. this._processLateAnimationBindings();
  26246. };
  26247. /** @hidden */
  26248. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26249. var target = runtimeAnimation.target;
  26250. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26251. if (!target._lateAnimationHolders) {
  26252. target._lateAnimationHolders = {};
  26253. }
  26254. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26255. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26256. totalWeight: 0,
  26257. animations: [],
  26258. originalValue: originalValue
  26259. };
  26260. }
  26261. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26262. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26263. };
  26264. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26265. var normalizer = 1.0;
  26266. var finalPosition = BABYLON.Tmp.Vector3[0];
  26267. var finalScaling = BABYLON.Tmp.Vector3[1];
  26268. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26269. var startIndex = 0;
  26270. var originalAnimation = holder.animations[0];
  26271. var originalValue = holder.originalValue;
  26272. var scale = 1;
  26273. if (holder.totalWeight < 1.0) {
  26274. // We need to mix the original value in
  26275. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26276. scale = 1.0 - holder.totalWeight;
  26277. }
  26278. else {
  26279. startIndex = 1;
  26280. // We need to normalize the weights
  26281. normalizer = holder.totalWeight;
  26282. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26283. scale = originalAnimation.weight / normalizer;
  26284. if (scale == 1) {
  26285. return originalAnimation.currentValue;
  26286. }
  26287. }
  26288. finalScaling.scaleInPlace(scale);
  26289. finalPosition.scaleInPlace(scale);
  26290. finalQuaternion.scaleInPlace(scale);
  26291. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26292. var runtimeAnimation = holder.animations[animIndex];
  26293. var scale = runtimeAnimation.weight / normalizer;
  26294. var currentPosition = BABYLON.Tmp.Vector3[2];
  26295. var currentScaling = BABYLON.Tmp.Vector3[3];
  26296. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26297. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26298. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26299. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26300. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26301. }
  26302. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26303. return originalAnimation._workValue;
  26304. };
  26305. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26306. var originalAnimation = holder.animations[0];
  26307. var originalValue = holder.originalValue;
  26308. if (holder.animations.length === 1) {
  26309. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26310. }
  26311. var normalizer = 1.0;
  26312. var quaternions;
  26313. var weights;
  26314. if (holder.totalWeight < 1.0) {
  26315. var scale = 1.0 - holder.totalWeight;
  26316. quaternions = [];
  26317. weights = [];
  26318. quaternions.push(originalValue);
  26319. weights.push(scale);
  26320. }
  26321. else {
  26322. if (holder.animations.length === 2) { // Slerp as soon as we can
  26323. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26324. }
  26325. quaternions = [];
  26326. weights = [];
  26327. normalizer = holder.totalWeight;
  26328. }
  26329. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26330. var runtimeAnimation = holder.animations[animIndex];
  26331. quaternions.push(runtimeAnimation.currentValue);
  26332. weights.push(runtimeAnimation.weight / normalizer);
  26333. }
  26334. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26335. var cumulativeAmount = 0;
  26336. var cumulativeQuaternion = null;
  26337. for (var index = 0; index < quaternions.length;) {
  26338. if (!cumulativeQuaternion) {
  26339. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26340. cumulativeAmount = weights[index] + weights[index + 1];
  26341. index += 2;
  26342. continue;
  26343. }
  26344. cumulativeAmount += weights[index];
  26345. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26346. index++;
  26347. }
  26348. return cumulativeQuaternion;
  26349. };
  26350. Scene.prototype._processLateAnimationBindings = function () {
  26351. if (!this._registeredForLateAnimationBindings.length) {
  26352. return;
  26353. }
  26354. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26355. var target = this._registeredForLateAnimationBindings.data[index];
  26356. for (var path in target._lateAnimationHolders) {
  26357. var holder = target._lateAnimationHolders[path];
  26358. var originalAnimation = holder.animations[0];
  26359. var originalValue = holder.originalValue;
  26360. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26361. var finalValue = void 0;
  26362. if (matrixDecomposeMode) {
  26363. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26364. }
  26365. else {
  26366. var quaternionMode = originalValue.w !== undefined;
  26367. if (quaternionMode) {
  26368. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26369. }
  26370. else {
  26371. var startIndex = 0;
  26372. var normalizer = 1.0;
  26373. if (holder.totalWeight < 1.0) {
  26374. // We need to mix the original value in
  26375. if (originalValue.scale) {
  26376. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26377. }
  26378. else {
  26379. finalValue = originalValue * (1.0 - holder.totalWeight);
  26380. }
  26381. }
  26382. else {
  26383. // We need to normalize the weights
  26384. normalizer = holder.totalWeight;
  26385. var scale_1 = originalAnimation.weight / normalizer;
  26386. if (scale_1 !== 1) {
  26387. if (originalAnimation.currentValue.scale) {
  26388. finalValue = originalAnimation.currentValue.scale(scale_1);
  26389. }
  26390. else {
  26391. finalValue = originalAnimation.currentValue * scale_1;
  26392. }
  26393. }
  26394. else {
  26395. finalValue = originalAnimation.currentValue;
  26396. }
  26397. startIndex = 1;
  26398. }
  26399. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26400. var runtimeAnimation = holder.animations[animIndex];
  26401. var scale = runtimeAnimation.weight / normalizer;
  26402. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26403. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26404. }
  26405. else {
  26406. finalValue += runtimeAnimation.currentValue * scale;
  26407. }
  26408. }
  26409. }
  26410. }
  26411. target[path] = finalValue;
  26412. }
  26413. target._lateAnimationHolders = {};
  26414. }
  26415. this._registeredForLateAnimationBindings.reset();
  26416. };
  26417. // Matrix
  26418. /** @hidden */
  26419. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26420. this._useAlternateCameraConfiguration = active;
  26421. };
  26422. /**
  26423. * Gets the current view matrix
  26424. * @returns a Matrix
  26425. */
  26426. Scene.prototype.getViewMatrix = function () {
  26427. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26428. };
  26429. /**
  26430. * Gets the current projection matrix
  26431. * @returns a Matrix
  26432. */
  26433. Scene.prototype.getProjectionMatrix = function () {
  26434. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26435. };
  26436. /**
  26437. * Gets the current transform matrix
  26438. * @returns a Matrix made of View * Projection
  26439. */
  26440. Scene.prototype.getTransformMatrix = function () {
  26441. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26442. };
  26443. /**
  26444. * Sets the current transform matrix
  26445. * @param view defines the View matrix to use
  26446. * @param projection defines the Projection matrix to use
  26447. */
  26448. Scene.prototype.setTransformMatrix = function (view, projection) {
  26449. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26450. return;
  26451. }
  26452. this._viewUpdateFlag = view.updateFlag;
  26453. this._projectionUpdateFlag = projection.updateFlag;
  26454. this._viewMatrix = view;
  26455. this._projectionMatrix = projection;
  26456. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26457. // Update frustum
  26458. if (!this._frustumPlanes) {
  26459. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26460. }
  26461. else {
  26462. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26463. }
  26464. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26465. var otherCamera = this.activeCamera._alternateCamera;
  26466. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26467. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26468. }
  26469. if (this._sceneUbo.useUbo) {
  26470. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26471. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26472. this._sceneUbo.update();
  26473. }
  26474. };
  26475. /** @hidden */
  26476. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26477. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26478. return;
  26479. }
  26480. this._alternateViewUpdateFlag = view.updateFlag;
  26481. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26482. this._alternateViewMatrix = view;
  26483. this._alternateProjectionMatrix = projection;
  26484. if (!this._alternateTransformMatrix) {
  26485. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26486. }
  26487. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26488. if (!this._alternateSceneUbo) {
  26489. this._createAlternateUbo();
  26490. }
  26491. if (this._alternateSceneUbo.useUbo) {
  26492. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26493. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26494. this._alternateSceneUbo.update();
  26495. }
  26496. };
  26497. /**
  26498. * Gets the uniform buffer used to store scene data
  26499. * @returns a UniformBuffer
  26500. */
  26501. Scene.prototype.getSceneUniformBuffer = function () {
  26502. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26503. };
  26504. /**
  26505. * Gets an unique (relatively to the current scene) Id
  26506. * @returns an unique number for the scene
  26507. */
  26508. Scene.prototype.getUniqueId = function () {
  26509. var result = Scene._uniqueIdCounter;
  26510. Scene._uniqueIdCounter++;
  26511. return result;
  26512. };
  26513. /**
  26514. * Add a mesh to the list of scene's meshes
  26515. * @param newMesh defines the mesh to add
  26516. * @param recursive if all child meshes should also be added to the scene
  26517. */
  26518. Scene.prototype.addMesh = function (newMesh, recursive) {
  26519. var _this = this;
  26520. if (recursive === void 0) { recursive = false; }
  26521. this.meshes.push(newMesh);
  26522. //notify the collision coordinator
  26523. if (this.collisionCoordinator) {
  26524. this.collisionCoordinator.onMeshAdded(newMesh);
  26525. }
  26526. newMesh._resyncLightSources();
  26527. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26528. if (recursive) {
  26529. newMesh.getChildMeshes().forEach(function (m) {
  26530. _this.addMesh(m);
  26531. });
  26532. }
  26533. };
  26534. /**
  26535. * Remove a mesh for the list of scene's meshes
  26536. * @param toRemove defines the mesh to remove
  26537. * @param recursive if all child meshes should also be removed from the scene
  26538. * @returns the index where the mesh was in the mesh list
  26539. */
  26540. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26541. var _this = this;
  26542. if (recursive === void 0) { recursive = false; }
  26543. var index = this.meshes.indexOf(toRemove);
  26544. if (index !== -1) {
  26545. // Remove from the scene if mesh found
  26546. this.meshes.splice(index, 1);
  26547. }
  26548. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26549. if (recursive) {
  26550. toRemove.getChildMeshes().forEach(function (m) {
  26551. _this.removeMesh(m);
  26552. });
  26553. }
  26554. return index;
  26555. };
  26556. /**
  26557. * Add a transform node to the list of scene's transform nodes
  26558. * @param newTransformNode defines the transform node to add
  26559. */
  26560. Scene.prototype.addTransformNode = function (newTransformNode) {
  26561. this.transformNodes.push(newTransformNode);
  26562. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26563. };
  26564. /**
  26565. * Remove a transform node for the list of scene's transform nodes
  26566. * @param toRemove defines the transform node to remove
  26567. * @returns the index where the transform node was in the transform node list
  26568. */
  26569. Scene.prototype.removeTransformNode = function (toRemove) {
  26570. var index = this.transformNodes.indexOf(toRemove);
  26571. if (index !== -1) {
  26572. // Remove from the scene if found
  26573. this.transformNodes.splice(index, 1);
  26574. }
  26575. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26576. return index;
  26577. };
  26578. /**
  26579. * Remove a skeleton for the list of scene's skeletons
  26580. * @param toRemove defines the skeleton to remove
  26581. * @returns the index where the skeleton was in the skeleton list
  26582. */
  26583. Scene.prototype.removeSkeleton = function (toRemove) {
  26584. var index = this.skeletons.indexOf(toRemove);
  26585. if (index !== -1) {
  26586. // Remove from the scene if found
  26587. this.skeletons.splice(index, 1);
  26588. }
  26589. return index;
  26590. };
  26591. /**
  26592. * Remove a morph target for the list of scene's morph targets
  26593. * @param toRemove defines the morph target to remove
  26594. * @returns the index where the morph target was in the morph target list
  26595. */
  26596. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26597. var index = this.morphTargetManagers.indexOf(toRemove);
  26598. if (index !== -1) {
  26599. // Remove from the scene if found
  26600. this.morphTargetManagers.splice(index, 1);
  26601. }
  26602. return index;
  26603. };
  26604. /**
  26605. * Remove a light for the list of scene's lights
  26606. * @param toRemove defines the light to remove
  26607. * @returns the index where the light was in the light list
  26608. */
  26609. Scene.prototype.removeLight = function (toRemove) {
  26610. var index = this.lights.indexOf(toRemove);
  26611. if (index !== -1) {
  26612. // Remove from meshes
  26613. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26614. var mesh = _a[_i];
  26615. mesh._removeLightSource(toRemove);
  26616. }
  26617. // Remove from the scene if mesh found
  26618. this.lights.splice(index, 1);
  26619. this.sortLightsByPriority();
  26620. }
  26621. this.onLightRemovedObservable.notifyObservers(toRemove);
  26622. return index;
  26623. };
  26624. /**
  26625. * Remove a camera for the list of scene's cameras
  26626. * @param toRemove defines the camera to remove
  26627. * @returns the index where the camera was in the camera list
  26628. */
  26629. Scene.prototype.removeCamera = function (toRemove) {
  26630. var index = this.cameras.indexOf(toRemove);
  26631. if (index !== -1) {
  26632. // Remove from the scene if mesh found
  26633. this.cameras.splice(index, 1);
  26634. }
  26635. // Remove from activeCameras
  26636. var index2 = this.activeCameras.indexOf(toRemove);
  26637. if (index2 !== -1) {
  26638. // Remove from the scene if mesh found
  26639. this.activeCameras.splice(index2, 1);
  26640. }
  26641. // Reset the activeCamera
  26642. if (this.activeCamera === toRemove) {
  26643. if (this.cameras.length > 0) {
  26644. this.activeCamera = this.cameras[0];
  26645. }
  26646. else {
  26647. this.activeCamera = null;
  26648. }
  26649. }
  26650. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26651. return index;
  26652. };
  26653. /**
  26654. * Remove a particle system for the list of scene's particle systems
  26655. * @param toRemove defines the particle system to remove
  26656. * @returns the index where the particle system was in the particle system list
  26657. */
  26658. Scene.prototype.removeParticleSystem = function (toRemove) {
  26659. var index = this.particleSystems.indexOf(toRemove);
  26660. if (index !== -1) {
  26661. this.particleSystems.splice(index, 1);
  26662. }
  26663. return index;
  26664. };
  26665. /**
  26666. * Remove a animation for the list of scene's animations
  26667. * @param toRemove defines the animation to remove
  26668. * @returns the index where the animation was in the animation list
  26669. */
  26670. Scene.prototype.removeAnimation = function (toRemove) {
  26671. var index = this.animations.indexOf(toRemove);
  26672. if (index !== -1) {
  26673. this.animations.splice(index, 1);
  26674. }
  26675. return index;
  26676. };
  26677. /**
  26678. * Removes the given animation group from this scene.
  26679. * @param toRemove The animation group to remove
  26680. * @returns The index of the removed animation group
  26681. */
  26682. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26683. var index = this.animationGroups.indexOf(toRemove);
  26684. if (index !== -1) {
  26685. this.animationGroups.splice(index, 1);
  26686. }
  26687. return index;
  26688. };
  26689. /**
  26690. * Removes the given multi-material from this scene.
  26691. * @param toRemove The multi-material to remove
  26692. * @returns The index of the removed multi-material
  26693. */
  26694. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26695. var index = this.multiMaterials.indexOf(toRemove);
  26696. if (index !== -1) {
  26697. this.multiMaterials.splice(index, 1);
  26698. }
  26699. return index;
  26700. };
  26701. /**
  26702. * Removes the given material from this scene.
  26703. * @param toRemove The material to remove
  26704. * @returns The index of the removed material
  26705. */
  26706. Scene.prototype.removeMaterial = function (toRemove) {
  26707. var index = this.materials.indexOf(toRemove);
  26708. if (index !== -1) {
  26709. this.materials.splice(index, 1);
  26710. }
  26711. return index;
  26712. };
  26713. /**
  26714. * Removes the given lens flare system from this scene.
  26715. * @param toRemove The lens flare system to remove
  26716. * @returns The index of the removed lens flare system
  26717. */
  26718. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26719. var index = this.lensFlareSystems.indexOf(toRemove);
  26720. if (index !== -1) {
  26721. this.lensFlareSystems.splice(index, 1);
  26722. }
  26723. return index;
  26724. };
  26725. /**
  26726. * Removes the given action manager from this scene.
  26727. * @param toRemove The action manager to remove
  26728. * @returns The index of the removed action manager
  26729. */
  26730. Scene.prototype.removeActionManager = function (toRemove) {
  26731. var index = this._actionManagers.indexOf(toRemove);
  26732. if (index !== -1) {
  26733. this._actionManagers.splice(index, 1);
  26734. }
  26735. return index;
  26736. };
  26737. /**
  26738. * Removes the given effect layer from this scene.
  26739. * @param toRemove defines the effect layer to remove
  26740. * @returns the index of the removed effect layer
  26741. */
  26742. Scene.prototype.removeEffectLayer = function (toRemove) {
  26743. var index = this.effectLayers.indexOf(toRemove);
  26744. if (index !== -1) {
  26745. this.effectLayers.splice(index, 1);
  26746. }
  26747. return index;
  26748. };
  26749. /**
  26750. * Removes the given texture from this scene.
  26751. * @param toRemove The texture to remove
  26752. * @returns The index of the removed texture
  26753. */
  26754. Scene.prototype.removeTexture = function (toRemove) {
  26755. var index = this.textures.indexOf(toRemove);
  26756. if (index !== -1) {
  26757. this.textures.splice(index, 1);
  26758. }
  26759. return index;
  26760. };
  26761. /**
  26762. * Adds the given light to this scene
  26763. * @param newLight The light to add
  26764. */
  26765. Scene.prototype.addLight = function (newLight) {
  26766. this.lights.push(newLight);
  26767. this.sortLightsByPriority();
  26768. // Add light to all meshes (To support if the light is removed and then readded)
  26769. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26770. var mesh = _a[_i];
  26771. if (mesh._lightSources.indexOf(newLight) === -1) {
  26772. mesh._lightSources.push(newLight);
  26773. mesh._resyncLightSources();
  26774. }
  26775. }
  26776. this.onNewLightAddedObservable.notifyObservers(newLight);
  26777. };
  26778. /**
  26779. * Sorts the list list based on light priorities
  26780. */
  26781. Scene.prototype.sortLightsByPriority = function () {
  26782. if (this.requireLightSorting) {
  26783. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26784. }
  26785. };
  26786. /**
  26787. * Adds the given camera to this scene
  26788. * @param newCamera The camera to add
  26789. */
  26790. Scene.prototype.addCamera = function (newCamera) {
  26791. this.cameras.push(newCamera);
  26792. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26793. };
  26794. /**
  26795. * Adds the given skeleton to this scene
  26796. * @param newSkeleton The skeleton to add
  26797. */
  26798. Scene.prototype.addSkeleton = function (newSkeleton) {
  26799. this.skeletons.push(newSkeleton);
  26800. };
  26801. /**
  26802. * Adds the given particle system to this scene
  26803. * @param newParticleSystem The particle system to add
  26804. */
  26805. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26806. this.particleSystems.push(newParticleSystem);
  26807. };
  26808. /**
  26809. * Adds the given animation to this scene
  26810. * @param newAnimation The animation to add
  26811. */
  26812. Scene.prototype.addAnimation = function (newAnimation) {
  26813. this.animations.push(newAnimation);
  26814. };
  26815. /**
  26816. * Adds the given animation group to this scene.
  26817. * @param newAnimationGroup The animation group to add
  26818. */
  26819. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26820. this.animationGroups.push(newAnimationGroup);
  26821. };
  26822. /**
  26823. * Adds the given multi-material to this scene
  26824. * @param newMultiMaterial The multi-material to add
  26825. */
  26826. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26827. this.multiMaterials.push(newMultiMaterial);
  26828. };
  26829. /**
  26830. * Adds the given material to this scene
  26831. * @param newMaterial The material to add
  26832. */
  26833. Scene.prototype.addMaterial = function (newMaterial) {
  26834. this.materials.push(newMaterial);
  26835. };
  26836. /**
  26837. * Adds the given morph target to this scene
  26838. * @param newMorphTargetManager The morph target to add
  26839. */
  26840. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26841. this.morphTargetManagers.push(newMorphTargetManager);
  26842. };
  26843. /**
  26844. * Adds the given geometry to this scene
  26845. * @param newGeometry The geometry to add
  26846. */
  26847. Scene.prototype.addGeometry = function (newGeometry) {
  26848. this._geometries.push(newGeometry);
  26849. };
  26850. /**
  26851. * Adds the given lens flare system to this scene
  26852. * @param newLensFlareSystem The lens flare system to add
  26853. */
  26854. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26855. this.lensFlareSystems.push(newLensFlareSystem);
  26856. };
  26857. /**
  26858. * Adds the given effect layer to this scene
  26859. * @param newEffectLayer defines the effect layer to add
  26860. */
  26861. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26862. this.effectLayers.push(newEffectLayer);
  26863. };
  26864. /**
  26865. * Adds the given action manager to this scene
  26866. * @param newActionManager The action manager to add
  26867. */
  26868. Scene.prototype.addActionManager = function (newActionManager) {
  26869. this._actionManagers.push(newActionManager);
  26870. };
  26871. /**
  26872. * Adds the given texture to this scene.
  26873. * @param newTexture The texture to add
  26874. */
  26875. Scene.prototype.addTexture = function (newTexture) {
  26876. this.textures.push(newTexture);
  26877. };
  26878. /**
  26879. * Switch active camera
  26880. * @param newCamera defines the new active camera
  26881. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26882. */
  26883. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26884. if (attachControl === void 0) { attachControl = true; }
  26885. var canvas = this._engine.getRenderingCanvas();
  26886. if (!canvas) {
  26887. return;
  26888. }
  26889. if (this.activeCamera) {
  26890. this.activeCamera.detachControl(canvas);
  26891. }
  26892. this.activeCamera = newCamera;
  26893. if (attachControl) {
  26894. newCamera.attachControl(canvas);
  26895. }
  26896. };
  26897. /**
  26898. * sets the active camera of the scene using its ID
  26899. * @param id defines the camera's ID
  26900. * @return the new active camera or null if none found.
  26901. */
  26902. Scene.prototype.setActiveCameraByID = function (id) {
  26903. var camera = this.getCameraByID(id);
  26904. if (camera) {
  26905. this.activeCamera = camera;
  26906. return camera;
  26907. }
  26908. return null;
  26909. };
  26910. /**
  26911. * sets the active camera of the scene using its name
  26912. * @param name defines the camera's name
  26913. * @returns the new active camera or null if none found.
  26914. */
  26915. Scene.prototype.setActiveCameraByName = function (name) {
  26916. var camera = this.getCameraByName(name);
  26917. if (camera) {
  26918. this.activeCamera = camera;
  26919. return camera;
  26920. }
  26921. return null;
  26922. };
  26923. /**
  26924. * get an animation group using its name
  26925. * @param name defines the material's name
  26926. * @return the animation group or null if none found.
  26927. */
  26928. Scene.prototype.getAnimationGroupByName = function (name) {
  26929. for (var index = 0; index < this.animationGroups.length; index++) {
  26930. if (this.animationGroups[index].name === name) {
  26931. return this.animationGroups[index];
  26932. }
  26933. }
  26934. return null;
  26935. };
  26936. /**
  26937. * get a material using its id
  26938. * @param id defines the material's ID
  26939. * @return the material or null if none found.
  26940. */
  26941. Scene.prototype.getMaterialByID = function (id) {
  26942. for (var index = 0; index < this.materials.length; index++) {
  26943. if (this.materials[index].id === id) {
  26944. return this.materials[index];
  26945. }
  26946. }
  26947. return null;
  26948. };
  26949. /**
  26950. * Gets a material using its name
  26951. * @param name defines the material's name
  26952. * @return the material or null if none found.
  26953. */
  26954. Scene.prototype.getMaterialByName = function (name) {
  26955. for (var index = 0; index < this.materials.length; index++) {
  26956. if (this.materials[index].name === name) {
  26957. return this.materials[index];
  26958. }
  26959. }
  26960. return null;
  26961. };
  26962. /**
  26963. * Gets a lens flare system using its name
  26964. * @param name defines the name to look for
  26965. * @returns the lens flare system or null if not found
  26966. */
  26967. Scene.prototype.getLensFlareSystemByName = function (name) {
  26968. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26969. if (this.lensFlareSystems[index].name === name) {
  26970. return this.lensFlareSystems[index];
  26971. }
  26972. }
  26973. return null;
  26974. };
  26975. /**
  26976. * Gets a lens flare system using its id
  26977. * @param id defines the id to look for
  26978. * @returns the lens flare system or null if not found
  26979. */
  26980. Scene.prototype.getLensFlareSystemByID = function (id) {
  26981. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26982. if (this.lensFlareSystems[index].id === id) {
  26983. return this.lensFlareSystems[index];
  26984. }
  26985. }
  26986. return null;
  26987. };
  26988. /**
  26989. * Gets a camera using its id
  26990. * @param id defines the id to look for
  26991. * @returns the camera or null if not found
  26992. */
  26993. Scene.prototype.getCameraByID = function (id) {
  26994. for (var index = 0; index < this.cameras.length; index++) {
  26995. if (this.cameras[index].id === id) {
  26996. return this.cameras[index];
  26997. }
  26998. }
  26999. return null;
  27000. };
  27001. /**
  27002. * Gets a camera using its unique id
  27003. * @param uniqueId defines the unique id to look for
  27004. * @returns the camera or null if not found
  27005. */
  27006. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27007. for (var index = 0; index < this.cameras.length; index++) {
  27008. if (this.cameras[index].uniqueId === uniqueId) {
  27009. return this.cameras[index];
  27010. }
  27011. }
  27012. return null;
  27013. };
  27014. /**
  27015. * Gets a camera using its name
  27016. * @param name defines the camera's name
  27017. * @return the camera or null if none found.
  27018. */
  27019. Scene.prototype.getCameraByName = function (name) {
  27020. for (var index = 0; index < this.cameras.length; index++) {
  27021. if (this.cameras[index].name === name) {
  27022. return this.cameras[index];
  27023. }
  27024. }
  27025. return null;
  27026. };
  27027. /**
  27028. * Gets a bone using its id
  27029. * @param id defines the bone's id
  27030. * @return the bone or null if not found
  27031. */
  27032. Scene.prototype.getBoneByID = function (id) {
  27033. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27034. var skeleton = this.skeletons[skeletonIndex];
  27035. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27036. if (skeleton.bones[boneIndex].id === id) {
  27037. return skeleton.bones[boneIndex];
  27038. }
  27039. }
  27040. }
  27041. return null;
  27042. };
  27043. /**
  27044. * Gets a bone using its id
  27045. * @param name defines the bone's name
  27046. * @return the bone or null if not found
  27047. */
  27048. Scene.prototype.getBoneByName = function (name) {
  27049. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27050. var skeleton = this.skeletons[skeletonIndex];
  27051. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27052. if (skeleton.bones[boneIndex].name === name) {
  27053. return skeleton.bones[boneIndex];
  27054. }
  27055. }
  27056. }
  27057. return null;
  27058. };
  27059. /**
  27060. * Gets a light node using its name
  27061. * @param name defines the the light's name
  27062. * @return the light or null if none found.
  27063. */
  27064. Scene.prototype.getLightByName = function (name) {
  27065. for (var index = 0; index < this.lights.length; index++) {
  27066. if (this.lights[index].name === name) {
  27067. return this.lights[index];
  27068. }
  27069. }
  27070. return null;
  27071. };
  27072. /**
  27073. * Gets a light node using its id
  27074. * @param id defines the light's id
  27075. * @return the light or null if none found.
  27076. */
  27077. Scene.prototype.getLightByID = function (id) {
  27078. for (var index = 0; index < this.lights.length; index++) {
  27079. if (this.lights[index].id === id) {
  27080. return this.lights[index];
  27081. }
  27082. }
  27083. return null;
  27084. };
  27085. /**
  27086. * Gets a light node using its scene-generated unique ID
  27087. * @param uniqueId defines the light's unique id
  27088. * @return the light or null if none found.
  27089. */
  27090. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27091. for (var index = 0; index < this.lights.length; index++) {
  27092. if (this.lights[index].uniqueId === uniqueId) {
  27093. return this.lights[index];
  27094. }
  27095. }
  27096. return null;
  27097. };
  27098. /**
  27099. * Gets a particle system by id
  27100. * @param id defines the particle system id
  27101. * @return the corresponding system or null if none found
  27102. */
  27103. Scene.prototype.getParticleSystemByID = function (id) {
  27104. for (var index = 0; index < this.particleSystems.length; index++) {
  27105. if (this.particleSystems[index].id === id) {
  27106. return this.particleSystems[index];
  27107. }
  27108. }
  27109. return null;
  27110. };
  27111. /**
  27112. * Gets a geometry using its ID
  27113. * @param id defines the geometry's id
  27114. * @return the geometry or null if none found.
  27115. */
  27116. Scene.prototype.getGeometryByID = function (id) {
  27117. for (var index = 0; index < this._geometries.length; index++) {
  27118. if (this._geometries[index].id === id) {
  27119. return this._geometries[index];
  27120. }
  27121. }
  27122. return null;
  27123. };
  27124. /**
  27125. * Add a new geometry to this scene
  27126. * @param geometry defines the geometry to be added to the scene.
  27127. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27128. * @return a boolean defining if the geometry was added or not
  27129. */
  27130. Scene.prototype.pushGeometry = function (geometry, force) {
  27131. if (!force && this.getGeometryByID(geometry.id)) {
  27132. return false;
  27133. }
  27134. this._geometries.push(geometry);
  27135. //notify the collision coordinator
  27136. if (this.collisionCoordinator) {
  27137. this.collisionCoordinator.onGeometryAdded(geometry);
  27138. }
  27139. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27140. return true;
  27141. };
  27142. /**
  27143. * Removes an existing geometry
  27144. * @param geometry defines the geometry to be removed from the scene
  27145. * @return a boolean defining if the geometry was removed or not
  27146. */
  27147. Scene.prototype.removeGeometry = function (geometry) {
  27148. var index = this._geometries.indexOf(geometry);
  27149. if (index > -1) {
  27150. this._geometries.splice(index, 1);
  27151. //notify the collision coordinator
  27152. if (this.collisionCoordinator) {
  27153. this.collisionCoordinator.onGeometryDeleted(geometry);
  27154. }
  27155. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27156. return true;
  27157. }
  27158. return false;
  27159. };
  27160. /**
  27161. * Gets the list of geometries attached to the scene
  27162. * @returns an array of Geometry
  27163. */
  27164. Scene.prototype.getGeometries = function () {
  27165. return this._geometries;
  27166. };
  27167. /**
  27168. * Gets the first added mesh found of a given ID
  27169. * @param id defines the id to search for
  27170. * @return the mesh found or null if not found at all
  27171. */
  27172. Scene.prototype.getMeshByID = function (id) {
  27173. for (var index = 0; index < this.meshes.length; index++) {
  27174. if (this.meshes[index].id === id) {
  27175. return this.meshes[index];
  27176. }
  27177. }
  27178. return null;
  27179. };
  27180. /**
  27181. * Gets a list of meshes using their id
  27182. * @param id defines the id to search for
  27183. * @returns a list of meshes
  27184. */
  27185. Scene.prototype.getMeshesByID = function (id) {
  27186. return this.meshes.filter(function (m) {
  27187. return m.id === id;
  27188. });
  27189. };
  27190. /**
  27191. * Gets the first added transform node found of a given ID
  27192. * @param id defines the id to search for
  27193. * @return the found transform node or null if not found at all.
  27194. */
  27195. Scene.prototype.getTransformNodeByID = function (id) {
  27196. for (var index = 0; index < this.transformNodes.length; index++) {
  27197. if (this.transformNodes[index].id === id) {
  27198. return this.transformNodes[index];
  27199. }
  27200. }
  27201. return null;
  27202. };
  27203. /**
  27204. * Gets a list of transform nodes using their id
  27205. * @param id defines the id to search for
  27206. * @returns a list of transform nodes
  27207. */
  27208. Scene.prototype.getTransformNodesByID = function (id) {
  27209. return this.transformNodes.filter(function (m) {
  27210. return m.id === id;
  27211. });
  27212. };
  27213. /**
  27214. * Gets a mesh with its auto-generated unique id
  27215. * @param uniqueId defines the unique id to search for
  27216. * @return the found mesh or null if not found at all.
  27217. */
  27218. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27219. for (var index = 0; index < this.meshes.length; index++) {
  27220. if (this.meshes[index].uniqueId === uniqueId) {
  27221. return this.meshes[index];
  27222. }
  27223. }
  27224. return null;
  27225. };
  27226. /**
  27227. * Gets a the last added mesh using a given id
  27228. * @param id defines the id to search for
  27229. * @return the found mesh or null if not found at all.
  27230. */
  27231. Scene.prototype.getLastMeshByID = function (id) {
  27232. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27233. if (this.meshes[index].id === id) {
  27234. return this.meshes[index];
  27235. }
  27236. }
  27237. return null;
  27238. };
  27239. /**
  27240. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27241. * @param id defines the id to search for
  27242. * @return the found node or null if not found at all
  27243. */
  27244. Scene.prototype.getLastEntryByID = function (id) {
  27245. var index;
  27246. for (index = this.meshes.length - 1; index >= 0; index--) {
  27247. if (this.meshes[index].id === id) {
  27248. return this.meshes[index];
  27249. }
  27250. }
  27251. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27252. if (this.transformNodes[index].id === id) {
  27253. return this.transformNodes[index];
  27254. }
  27255. }
  27256. for (index = this.cameras.length - 1; index >= 0; index--) {
  27257. if (this.cameras[index].id === id) {
  27258. return this.cameras[index];
  27259. }
  27260. }
  27261. for (index = this.lights.length - 1; index >= 0; index--) {
  27262. if (this.lights[index].id === id) {
  27263. return this.lights[index];
  27264. }
  27265. }
  27266. return null;
  27267. };
  27268. /**
  27269. * Gets a node (Mesh, Camera, Light) using a given id
  27270. * @param id defines the id to search for
  27271. * @return the found node or null if not found at all
  27272. */
  27273. Scene.prototype.getNodeByID = function (id) {
  27274. var mesh = this.getMeshByID(id);
  27275. if (mesh) {
  27276. return mesh;
  27277. }
  27278. var light = this.getLightByID(id);
  27279. if (light) {
  27280. return light;
  27281. }
  27282. var camera = this.getCameraByID(id);
  27283. if (camera) {
  27284. return camera;
  27285. }
  27286. var bone = this.getBoneByID(id);
  27287. return bone;
  27288. };
  27289. /**
  27290. * Gets a node (Mesh, Camera, Light) using a given name
  27291. * @param name defines the name to search for
  27292. * @return the found node or null if not found at all.
  27293. */
  27294. Scene.prototype.getNodeByName = function (name) {
  27295. var mesh = this.getMeshByName(name);
  27296. if (mesh) {
  27297. return mesh;
  27298. }
  27299. var light = this.getLightByName(name);
  27300. if (light) {
  27301. return light;
  27302. }
  27303. var camera = this.getCameraByName(name);
  27304. if (camera) {
  27305. return camera;
  27306. }
  27307. var bone = this.getBoneByName(name);
  27308. return bone;
  27309. };
  27310. /**
  27311. * Gets a mesh using a given name
  27312. * @param name defines the name to search for
  27313. * @return the found mesh or null if not found at all.
  27314. */
  27315. Scene.prototype.getMeshByName = function (name) {
  27316. for (var index = 0; index < this.meshes.length; index++) {
  27317. if (this.meshes[index].name === name) {
  27318. return this.meshes[index];
  27319. }
  27320. }
  27321. return null;
  27322. };
  27323. /**
  27324. * Gets a transform node using a given name
  27325. * @param name defines the name to search for
  27326. * @return the found transform node or null if not found at all.
  27327. */
  27328. Scene.prototype.getTransformNodeByName = function (name) {
  27329. for (var index = 0; index < this.transformNodes.length; index++) {
  27330. if (this.transformNodes[index].name === name) {
  27331. return this.transformNodes[index];
  27332. }
  27333. }
  27334. return null;
  27335. };
  27336. /**
  27337. * Gets a sound using a given name
  27338. * @param name defines the name to search for
  27339. * @return the found sound or null if not found at all.
  27340. */
  27341. Scene.prototype.getSoundByName = function (name) {
  27342. var index;
  27343. if (BABYLON.AudioEngine) {
  27344. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27345. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27346. return this.mainSoundTrack.soundCollection[index];
  27347. }
  27348. }
  27349. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27350. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27351. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27352. return this.soundTracks[sdIndex].soundCollection[index];
  27353. }
  27354. }
  27355. }
  27356. }
  27357. return null;
  27358. };
  27359. /**
  27360. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27361. * @param id defines the id to search for
  27362. * @return the found skeleton or null if not found at all.
  27363. */
  27364. Scene.prototype.getLastSkeletonByID = function (id) {
  27365. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27366. if (this.skeletons[index].id === id) {
  27367. return this.skeletons[index];
  27368. }
  27369. }
  27370. return null;
  27371. };
  27372. /**
  27373. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27374. * @param id defines the id to search for
  27375. * @return the found skeleton or null if not found at all.
  27376. */
  27377. Scene.prototype.getSkeletonById = function (id) {
  27378. for (var index = 0; index < this.skeletons.length; index++) {
  27379. if (this.skeletons[index].id === id) {
  27380. return this.skeletons[index];
  27381. }
  27382. }
  27383. return null;
  27384. };
  27385. /**
  27386. * Gets a skeleton using a given name
  27387. * @param name defines the name to search for
  27388. * @return the found skeleton or null if not found at all.
  27389. */
  27390. Scene.prototype.getSkeletonByName = function (name) {
  27391. for (var index = 0; index < this.skeletons.length; index++) {
  27392. if (this.skeletons[index].name === name) {
  27393. return this.skeletons[index];
  27394. }
  27395. }
  27396. return null;
  27397. };
  27398. /**
  27399. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27400. * @param id defines the id to search for
  27401. * @return the found morph target manager or null if not found at all.
  27402. */
  27403. Scene.prototype.getMorphTargetManagerById = function (id) {
  27404. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27405. if (this.morphTargetManagers[index].uniqueId === id) {
  27406. return this.morphTargetManagers[index];
  27407. }
  27408. }
  27409. return null;
  27410. };
  27411. /**
  27412. * Gets a boolean indicating if the given mesh is active
  27413. * @param mesh defines the mesh to look for
  27414. * @returns true if the mesh is in the active list
  27415. */
  27416. Scene.prototype.isActiveMesh = function (mesh) {
  27417. return (this._activeMeshes.indexOf(mesh) !== -1);
  27418. };
  27419. /**
  27420. * Return a the first highlight layer of the scene with a given name.
  27421. * @param name The name of the highlight layer to look for.
  27422. * @return The highlight layer if found otherwise null.
  27423. */
  27424. Scene.prototype.getHighlightLayerByName = function (name) {
  27425. for (var index = 0; index < this.effectLayers.length; index++) {
  27426. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27427. return this.effectLayers[index];
  27428. }
  27429. }
  27430. return null;
  27431. };
  27432. /**
  27433. * Return a the first highlight layer of the scene with a given name.
  27434. * @param name The name of the highlight layer to look for.
  27435. * @return The highlight layer if found otherwise null.
  27436. */
  27437. Scene.prototype.getGlowLayerByName = function (name) {
  27438. for (var index = 0; index < this.effectLayers.length; index++) {
  27439. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27440. return this.effectLayers[index];
  27441. }
  27442. }
  27443. return null;
  27444. };
  27445. Object.defineProperty(Scene.prototype, "uid", {
  27446. /**
  27447. * Return a unique id as a string which can serve as an identifier for the scene
  27448. */
  27449. get: function () {
  27450. if (!this._uid) {
  27451. this._uid = BABYLON.Tools.RandomId();
  27452. }
  27453. return this._uid;
  27454. },
  27455. enumerable: true,
  27456. configurable: true
  27457. });
  27458. /**
  27459. * Add an externaly attached data from its key.
  27460. * This method call will fail and return false, if such key already exists.
  27461. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27462. * @param key the unique key that identifies the data
  27463. * @param data the data object to associate to the key for this Engine instance
  27464. * @return true if no such key were already present and the data was added successfully, false otherwise
  27465. */
  27466. Scene.prototype.addExternalData = function (key, data) {
  27467. if (!this._externalData) {
  27468. this._externalData = new BABYLON.StringDictionary();
  27469. }
  27470. return this._externalData.add(key, data);
  27471. };
  27472. /**
  27473. * Get an externaly attached data from its key
  27474. * @param key the unique key that identifies the data
  27475. * @return the associated data, if present (can be null), or undefined if not present
  27476. */
  27477. Scene.prototype.getExternalData = function (key) {
  27478. if (!this._externalData) {
  27479. return null;
  27480. }
  27481. return this._externalData.get(key);
  27482. };
  27483. /**
  27484. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27485. * @param key the unique key that identifies the data
  27486. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27487. * @return the associated data, can be null if the factory returned null.
  27488. */
  27489. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27490. if (!this._externalData) {
  27491. this._externalData = new BABYLON.StringDictionary();
  27492. }
  27493. return this._externalData.getOrAddWithFactory(key, factory);
  27494. };
  27495. /**
  27496. * Remove an externaly attached data from the Engine instance
  27497. * @param key the unique key that identifies the data
  27498. * @return true if the data was successfully removed, false if it doesn't exist
  27499. */
  27500. Scene.prototype.removeExternalData = function (key) {
  27501. return this._externalData.remove(key);
  27502. };
  27503. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27504. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27505. if (mesh.showSubMeshesBoundingBox) {
  27506. var boundingInfo = subMesh.getBoundingInfo();
  27507. if (boundingInfo !== null && boundingInfo !== undefined) {
  27508. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27509. }
  27510. }
  27511. var material = subMesh.getMaterial();
  27512. if (material !== null && material !== undefined) {
  27513. // Render targets
  27514. if (material.getRenderTargetTextures !== undefined) {
  27515. if (this._processedMaterials.indexOf(material) === -1) {
  27516. this._processedMaterials.push(material);
  27517. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27518. }
  27519. }
  27520. // Dispatch
  27521. this._activeIndices.addCount(subMesh.indexCount, false);
  27522. this._renderingManager.dispatch(subMesh, mesh, material);
  27523. }
  27524. }
  27525. };
  27526. /**
  27527. * Clear the processed materials smart array preventing retention point in material dispose.
  27528. */
  27529. Scene.prototype.freeProcessedMaterials = function () {
  27530. this._processedMaterials.dispose();
  27531. };
  27532. /**
  27533. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27534. */
  27535. Scene.prototype.freeActiveMeshes = function () {
  27536. this._activeMeshes.dispose();
  27537. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27538. this.activeCamera._activeMeshes.dispose();
  27539. }
  27540. if (this.activeCameras) {
  27541. for (var i = 0; i < this.activeCameras.length; i++) {
  27542. var activeCamera = this.activeCameras[i];
  27543. if (activeCamera && activeCamera._activeMeshes) {
  27544. activeCamera._activeMeshes.dispose();
  27545. }
  27546. }
  27547. }
  27548. };
  27549. /**
  27550. * Clear the info related to rendering groups preventing retention points during dispose.
  27551. */
  27552. Scene.prototype.freeRenderingGroups = function () {
  27553. if (this._renderingManager) {
  27554. this._renderingManager.freeRenderingGroups();
  27555. }
  27556. if (this.textures) {
  27557. for (var i = 0; i < this.textures.length; i++) {
  27558. var texture = this.textures[i];
  27559. if (texture && texture.renderList) {
  27560. texture.freeRenderingGroups();
  27561. }
  27562. }
  27563. }
  27564. };
  27565. /** @hidden */
  27566. Scene.prototype._isInIntermediateRendering = function () {
  27567. return this._intermediateRendering;
  27568. };
  27569. /**
  27570. * Defines the current active mesh candidate provider
  27571. * @param provider defines the provider to use
  27572. */
  27573. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27574. this._activeMeshCandidateProvider = provider;
  27575. };
  27576. /**
  27577. * Gets the current active mesh candidate provider
  27578. * @returns the current active mesh candidate provider
  27579. */
  27580. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27581. return this._activeMeshCandidateProvider;
  27582. };
  27583. /**
  27584. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27585. * @returns the current scene
  27586. */
  27587. Scene.prototype.freezeActiveMeshes = function () {
  27588. if (!this.activeCamera) {
  27589. return this;
  27590. }
  27591. if (!this._frustumPlanes) {
  27592. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27593. }
  27594. this._evaluateActiveMeshes();
  27595. this._activeMeshesFrozen = true;
  27596. return this;
  27597. };
  27598. /**
  27599. * Use this function to restart evaluating active meshes on every frame
  27600. * @returns the current scene
  27601. */
  27602. Scene.prototype.unfreezeActiveMeshes = function () {
  27603. this._activeMeshesFrozen = false;
  27604. return this;
  27605. };
  27606. Scene.prototype._evaluateActiveMeshes = function () {
  27607. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27608. return;
  27609. }
  27610. if (!this.activeCamera) {
  27611. return;
  27612. }
  27613. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27614. this.activeCamera._activeMeshes.reset();
  27615. this._activeMeshes.reset();
  27616. this._renderingManager.reset();
  27617. this._processedMaterials.reset();
  27618. this._activeParticleSystems.reset();
  27619. this._activeSkeletons.reset();
  27620. this._softwareSkinnedMeshes.reset();
  27621. if (this._boundingBoxRenderer) {
  27622. this._boundingBoxRenderer.reset();
  27623. }
  27624. // Meshes
  27625. var meshes;
  27626. var len;
  27627. var checkIsEnabled = true;
  27628. // Determine mesh candidates
  27629. if (this._activeMeshCandidateProvider !== undefined) {
  27630. // Use _activeMeshCandidateProvider
  27631. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27632. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27633. if (meshes !== undefined) {
  27634. len = meshes.length;
  27635. }
  27636. else {
  27637. len = 0;
  27638. }
  27639. }
  27640. else if (this._selectionOctree !== undefined) {
  27641. // Octree
  27642. var selection = this._selectionOctree.select(this._frustumPlanes);
  27643. meshes = selection.data;
  27644. len = selection.length;
  27645. }
  27646. else {
  27647. // Full scene traversal
  27648. len = this.meshes.length;
  27649. meshes = this.meshes;
  27650. }
  27651. // Check each mesh
  27652. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27653. mesh = meshes[meshIndex];
  27654. if (mesh.isBlocked) {
  27655. continue;
  27656. }
  27657. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27658. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27659. continue;
  27660. }
  27661. mesh.computeWorldMatrix();
  27662. // Intersections
  27663. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27664. this._meshesForIntersections.pushNoDuplicate(mesh);
  27665. }
  27666. // Switch to current LOD
  27667. meshLOD = mesh.getLOD(this.activeCamera);
  27668. if (meshLOD === undefined || meshLOD === null) {
  27669. continue;
  27670. }
  27671. mesh._preActivate();
  27672. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27673. this._activeMeshes.push(mesh);
  27674. this.activeCamera._activeMeshes.push(mesh);
  27675. mesh._activate(this._renderId);
  27676. if (meshLOD !== mesh) {
  27677. meshLOD._activate(this._renderId);
  27678. }
  27679. this._activeMesh(mesh, meshLOD);
  27680. }
  27681. }
  27682. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27683. // Particle systems
  27684. if (this.particlesEnabled) {
  27685. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27686. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27687. var particleSystem = this.particleSystems[particleIndex];
  27688. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27689. continue;
  27690. }
  27691. var emitter = particleSystem.emitter;
  27692. if (!emitter.position || emitter.isEnabled()) {
  27693. this._activeParticleSystems.push(particleSystem);
  27694. particleSystem.animate();
  27695. this._renderingManager.dispatchParticles(particleSystem);
  27696. }
  27697. }
  27698. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27699. }
  27700. };
  27701. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27702. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27703. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27704. mesh.skeleton.prepare();
  27705. }
  27706. if (!mesh.computeBonesUsingShaders) {
  27707. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27708. }
  27709. }
  27710. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27711. var boundingInfo = sourceMesh.getBoundingInfo();
  27712. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27713. }
  27714. if (mesh !== undefined && mesh !== null
  27715. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27716. // Submeshes Octrees
  27717. var len;
  27718. var subMeshes;
  27719. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27720. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27721. len = intersections.length;
  27722. subMeshes = intersections.data;
  27723. }
  27724. else {
  27725. subMeshes = mesh.subMeshes;
  27726. len = subMeshes.length;
  27727. }
  27728. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27729. subMesh = subMeshes[subIndex];
  27730. this._evaluateSubMesh(subMesh, mesh);
  27731. }
  27732. }
  27733. };
  27734. /**
  27735. * Update the transform matrix to update from the current active camera
  27736. * @param force defines a boolean used to force the update even if cache is up to date
  27737. */
  27738. Scene.prototype.updateTransformMatrix = function (force) {
  27739. if (!this.activeCamera) {
  27740. return;
  27741. }
  27742. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27743. };
  27744. /**
  27745. * 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)
  27746. * @param alternateCamera defines the camera to use
  27747. */
  27748. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27749. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27750. };
  27751. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27752. if (camera && camera._skipRendering) {
  27753. return;
  27754. }
  27755. var engine = this._engine;
  27756. this.activeCamera = camera;
  27757. if (!this.activeCamera)
  27758. throw new Error("Active camera not set");
  27759. // Viewport
  27760. engine.setViewport(this.activeCamera.viewport);
  27761. // Camera
  27762. this.resetCachedMaterial();
  27763. this._renderId++;
  27764. this.updateTransformMatrix();
  27765. if (camera._alternateCamera) {
  27766. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27767. this._alternateRendering = true;
  27768. }
  27769. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27770. // Meshes
  27771. this._evaluateActiveMeshes();
  27772. // Software skinning
  27773. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27774. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27775. mesh.applySkeleton(mesh.skeleton);
  27776. }
  27777. // Render targets
  27778. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27779. var needsRestoreFrameBuffer = false;
  27780. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27781. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27782. }
  27783. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27784. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27785. }
  27786. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27787. this._intermediateRendering = true;
  27788. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27789. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27790. var renderTarget = this._renderTargets.data[renderIndex];
  27791. if (renderTarget._shouldRender()) {
  27792. this._renderId++;
  27793. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27794. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27795. }
  27796. }
  27797. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27798. this._intermediateRendering = false;
  27799. this._renderId++;
  27800. needsRestoreFrameBuffer = true; // Restore back buffer
  27801. }
  27802. // Render EffectLayer Texture
  27803. var stencilState = this._engine.getStencilBuffer();
  27804. var renderEffects = false;
  27805. var needStencil = false;
  27806. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27807. this._intermediateRendering = true;
  27808. for (var i = 0; i < this.effectLayers.length; i++) {
  27809. var effectLayer = this.effectLayers[i];
  27810. if (effectLayer.shouldRender() &&
  27811. (!effectLayer.camera ||
  27812. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27813. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27814. renderEffects = true;
  27815. needStencil = needStencil || effectLayer.needStencil();
  27816. var renderTarget = effectLayer._mainTexture;
  27817. if (renderTarget._shouldRender()) {
  27818. this._renderId++;
  27819. renderTarget.render(false, false);
  27820. needsRestoreFrameBuffer = true;
  27821. }
  27822. }
  27823. }
  27824. this._intermediateRendering = false;
  27825. this._renderId++;
  27826. }
  27827. if (needsRestoreFrameBuffer) {
  27828. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27829. }
  27830. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27831. // Prepare Frame
  27832. if (this.postProcessManager) {
  27833. this.postProcessManager._prepareFrame();
  27834. }
  27835. // Backgrounds
  27836. var layerIndex;
  27837. var layer;
  27838. if (this.layers.length) {
  27839. engine.setDepthBuffer(false);
  27840. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27841. layer = this.layers[layerIndex];
  27842. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27843. layer.render();
  27844. }
  27845. }
  27846. engine.setDepthBuffer(true);
  27847. }
  27848. // Activate effect Layer stencil
  27849. if (needStencil) {
  27850. this._engine.setStencilBuffer(true);
  27851. }
  27852. // Render
  27853. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27854. this._renderingManager.render(null, null, true, true);
  27855. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27856. // Restore effect Layer stencil
  27857. if (needStencil) {
  27858. this._engine.setStencilBuffer(stencilState);
  27859. }
  27860. // Bounding boxes
  27861. if (this._boundingBoxRenderer) {
  27862. this._boundingBoxRenderer.render();
  27863. }
  27864. // Lens flares
  27865. if (this.lensFlaresEnabled) {
  27866. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27867. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27868. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27869. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27870. lensFlareSystem.render();
  27871. }
  27872. }
  27873. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27874. }
  27875. // Effect Layer
  27876. if (renderEffects) {
  27877. engine.setDepthBuffer(false);
  27878. for (var i = 0; i < this.effectLayers.length; i++) {
  27879. if (this.effectLayers[i].shouldRender()) {
  27880. this.effectLayers[i].render();
  27881. }
  27882. }
  27883. engine.setDepthBuffer(true);
  27884. }
  27885. // Foregrounds
  27886. if (this.layers.length) {
  27887. engine.setDepthBuffer(false);
  27888. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27889. layer = this.layers[layerIndex];
  27890. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27891. layer.render();
  27892. }
  27893. }
  27894. engine.setDepthBuffer(true);
  27895. }
  27896. // Finalize frame
  27897. if (this.postProcessManager) {
  27898. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27899. }
  27900. // Reset some special arrays
  27901. this._renderTargets.reset();
  27902. this._alternateRendering = false;
  27903. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27904. };
  27905. Scene.prototype._processSubCameras = function (camera) {
  27906. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27907. this._renderForCamera(camera);
  27908. return;
  27909. }
  27910. // rig cameras
  27911. for (var index = 0; index < camera._rigCameras.length; index++) {
  27912. this._renderForCamera(camera._rigCameras[index], camera);
  27913. }
  27914. this.activeCamera = camera;
  27915. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27916. };
  27917. Scene.prototype._checkIntersections = function () {
  27918. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27919. var sourceMesh = this._meshesForIntersections.data[index];
  27920. if (!sourceMesh.actionManager) {
  27921. continue;
  27922. }
  27923. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27924. var action = sourceMesh.actionManager.actions[actionIndex];
  27925. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27926. var parameters = action.getTriggerParameter();
  27927. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27928. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27929. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27930. if (areIntersecting && currentIntersectionInProgress === -1) {
  27931. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27932. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27933. sourceMesh._intersectionsInProgress.push(otherMesh);
  27934. }
  27935. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27936. sourceMesh._intersectionsInProgress.push(otherMesh);
  27937. }
  27938. }
  27939. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27940. //They intersected, and now they don't.
  27941. //is this trigger an exit trigger? execute an event.
  27942. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27943. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27944. }
  27945. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27946. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27947. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27948. return otherMesh === parameterMesh;
  27949. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27950. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27951. }
  27952. }
  27953. }
  27954. }
  27955. }
  27956. };
  27957. /**
  27958. * Render the scene
  27959. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27960. */
  27961. Scene.prototype.render = function (updateCameras) {
  27962. if (updateCameras === void 0) { updateCameras = true; }
  27963. if (this.isDisposed) {
  27964. return;
  27965. }
  27966. this._activeParticles.fetchNewFrame();
  27967. this._totalVertices.fetchNewFrame();
  27968. this._activeIndices.fetchNewFrame();
  27969. this._activeBones.fetchNewFrame();
  27970. this._meshesForIntersections.reset();
  27971. this.resetCachedMaterial();
  27972. this.onBeforeAnimationsObservable.notifyObservers(this);
  27973. // Actions
  27974. if (this.actionManager) {
  27975. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27976. }
  27977. //Simplification Queue
  27978. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27979. this.simplificationQueue.executeNext();
  27980. }
  27981. if (this._engine.isDeterministicLockStep()) {
  27982. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27983. var defaultFPS = (60.0 / 1000.0);
  27984. var defaultFrameTime = 1000 / 60; // frame time in MS
  27985. if (this._physicsEngine) {
  27986. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27987. }
  27988. var stepsTaken = 0;
  27989. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27990. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27991. internalSteps = Math.min(internalSteps, maxSubSteps);
  27992. do {
  27993. this.onBeforeStepObservable.notifyObservers(this);
  27994. // Animations
  27995. this._animationRatio = defaultFrameTime * defaultFPS;
  27996. this._animate();
  27997. this.onAfterAnimationsObservable.notifyObservers(this);
  27998. // Physics
  27999. if (this._physicsEngine) {
  28000. this.onBeforePhysicsObservable.notifyObservers(this);
  28001. this._physicsEngine._step(defaultFrameTime / 1000);
  28002. this.onAfterPhysicsObservable.notifyObservers(this);
  28003. }
  28004. this.onAfterStepObservable.notifyObservers(this);
  28005. this._currentStepId++;
  28006. stepsTaken++;
  28007. deltaTime -= defaultFrameTime;
  28008. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28009. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28010. }
  28011. else {
  28012. // Animations
  28013. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28014. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28015. this._animate();
  28016. this.onAfterAnimationsObservable.notifyObservers(this);
  28017. // Physics
  28018. if (this._physicsEngine) {
  28019. this.onBeforePhysicsObservable.notifyObservers(this);
  28020. this._physicsEngine._step(deltaTime / 1000.0);
  28021. this.onAfterPhysicsObservable.notifyObservers(this);
  28022. }
  28023. }
  28024. // update gamepad manager
  28025. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  28026. this._gamepadManager._checkGamepadsStatus();
  28027. }
  28028. // Update Cameras
  28029. if (updateCameras) {
  28030. if (this.activeCameras.length > 0) {
  28031. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28032. var camera = this.activeCameras[cameraIndex];
  28033. camera.update();
  28034. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28035. // rig cameras
  28036. for (var index = 0; index < camera._rigCameras.length; index++) {
  28037. camera._rigCameras[index].update();
  28038. }
  28039. }
  28040. }
  28041. }
  28042. else if (this.activeCamera) {
  28043. this.activeCamera.update();
  28044. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28045. // rig cameras
  28046. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28047. this.activeCamera._rigCameras[index].update();
  28048. }
  28049. }
  28050. }
  28051. }
  28052. // Before render
  28053. this.onBeforeRenderObservable.notifyObservers(this);
  28054. // Customs render targets
  28055. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28056. var engine = this.getEngine();
  28057. var currentActiveCamera = this.activeCamera;
  28058. if (this.renderTargetsEnabled) {
  28059. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28060. this._intermediateRendering = true;
  28061. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28062. var renderTarget = this.customRenderTargets[customIndex];
  28063. if (renderTarget._shouldRender()) {
  28064. this._renderId++;
  28065. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28066. if (!this.activeCamera)
  28067. throw new Error("Active camera not set");
  28068. // Viewport
  28069. engine.setViewport(this.activeCamera.viewport);
  28070. // Camera
  28071. this.updateTransformMatrix();
  28072. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28073. }
  28074. }
  28075. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28076. this._intermediateRendering = false;
  28077. this._renderId++;
  28078. }
  28079. // Restore back buffer
  28080. if (this.customRenderTargets.length > 0) {
  28081. engine.restoreDefaultFramebuffer();
  28082. }
  28083. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28084. this.activeCamera = currentActiveCamera;
  28085. // Procedural textures
  28086. if (this.proceduralTexturesEnabled) {
  28087. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28088. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28089. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28090. if (proceduralTexture._shouldRender()) {
  28091. proceduralTexture.render();
  28092. }
  28093. }
  28094. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28095. }
  28096. // Clear
  28097. if (this.autoClearDepthAndStencil || this.autoClear) {
  28098. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28099. }
  28100. // Shadows
  28101. if (this.shadowsEnabled) {
  28102. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28103. var light = this.lights[lightIndex];
  28104. var shadowGenerator = light.getShadowGenerator();
  28105. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28106. var shadowMap = (shadowGenerator.getShadowMap());
  28107. if (this.textures.indexOf(shadowMap) !== -1) {
  28108. this._renderTargets.push(shadowMap);
  28109. }
  28110. }
  28111. }
  28112. }
  28113. // Depth renderer
  28114. for (var key in this._depthRenderer) {
  28115. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28116. }
  28117. // Geometry renderer
  28118. if (this._geometryBufferRenderer) {
  28119. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28120. }
  28121. // RenderPipeline
  28122. if (this._postProcessRenderPipelineManager) {
  28123. this._postProcessRenderPipelineManager.update();
  28124. }
  28125. // Multi-cameras?
  28126. if (this.activeCameras.length > 0) {
  28127. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28128. if (cameraIndex > 0) {
  28129. this._engine.clear(null, false, true, true);
  28130. }
  28131. this._processSubCameras(this.activeCameras[cameraIndex]);
  28132. }
  28133. }
  28134. else {
  28135. if (!this.activeCamera) {
  28136. throw new Error("No camera defined");
  28137. }
  28138. this._processSubCameras(this.activeCamera);
  28139. }
  28140. // Intersection checks
  28141. this._checkIntersections();
  28142. // Update the audio listener attached to the camera
  28143. if (BABYLON.AudioEngine) {
  28144. this._updateAudioParameters();
  28145. }
  28146. // After render
  28147. if (this.afterRender) {
  28148. this.afterRender();
  28149. }
  28150. this.onAfterRenderObservable.notifyObservers(this);
  28151. // Cleaning
  28152. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28153. var data = this._toBeDisposed.data[index];
  28154. if (data) {
  28155. data.dispose();
  28156. }
  28157. this._toBeDisposed[index] = null;
  28158. }
  28159. this._toBeDisposed.reset();
  28160. if (this.dumpNextRenderTargets) {
  28161. this.dumpNextRenderTargets = false;
  28162. }
  28163. this._activeBones.addCount(0, true);
  28164. this._activeIndices.addCount(0, true);
  28165. this._activeParticles.addCount(0, true);
  28166. };
  28167. Scene.prototype._updateAudioParameters = function () {
  28168. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28169. return;
  28170. }
  28171. var listeningCamera;
  28172. var audioEngine = BABYLON.Engine.audioEngine;
  28173. if (this.activeCameras.length > 0) {
  28174. listeningCamera = this.activeCameras[0];
  28175. }
  28176. else {
  28177. listeningCamera = this.activeCamera;
  28178. }
  28179. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28180. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28181. // for VR cameras
  28182. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28183. listeningCamera = listeningCamera.rigCameras[0];
  28184. }
  28185. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28186. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28187. cameraDirection.normalize();
  28188. // To avoid some errors on GearVR
  28189. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28190. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28191. }
  28192. var i;
  28193. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28194. var sound = this.mainSoundTrack.soundCollection[i];
  28195. if (sound.useCustomAttenuation) {
  28196. sound.updateDistanceFromListener();
  28197. }
  28198. }
  28199. for (i = 0; i < this.soundTracks.length; i++) {
  28200. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28201. sound = this.soundTracks[i].soundCollection[j];
  28202. if (sound.useCustomAttenuation) {
  28203. sound.updateDistanceFromListener();
  28204. }
  28205. }
  28206. }
  28207. }
  28208. };
  28209. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28210. // Audio
  28211. /**
  28212. * Gets or sets if audio support is enabled
  28213. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28214. */
  28215. get: function () {
  28216. return this._audioEnabled;
  28217. },
  28218. set: function (value) {
  28219. this._audioEnabled = value;
  28220. if (BABYLON.AudioEngine) {
  28221. if (this._audioEnabled) {
  28222. this._enableAudio();
  28223. }
  28224. else {
  28225. this._disableAudio();
  28226. }
  28227. }
  28228. },
  28229. enumerable: true,
  28230. configurable: true
  28231. });
  28232. Scene.prototype._disableAudio = function () {
  28233. var i;
  28234. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28235. this.mainSoundTrack.soundCollection[i].pause();
  28236. }
  28237. for (i = 0; i < this.soundTracks.length; i++) {
  28238. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28239. this.soundTracks[i].soundCollection[j].pause();
  28240. }
  28241. }
  28242. };
  28243. Scene.prototype._enableAudio = function () {
  28244. var i;
  28245. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28246. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28247. this.mainSoundTrack.soundCollection[i].play();
  28248. }
  28249. }
  28250. for (i = 0; i < this.soundTracks.length; i++) {
  28251. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28252. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28253. this.soundTracks[i].soundCollection[j].play();
  28254. }
  28255. }
  28256. }
  28257. };
  28258. Object.defineProperty(Scene.prototype, "headphone", {
  28259. /**
  28260. * Gets or sets if audio will be output to headphones
  28261. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28262. */
  28263. get: function () {
  28264. return this._headphone;
  28265. },
  28266. set: function (value) {
  28267. this._headphone = value;
  28268. if (BABYLON.AudioEngine) {
  28269. if (this._headphone) {
  28270. this._switchAudioModeForHeadphones();
  28271. }
  28272. else {
  28273. this._switchAudioModeForNormalSpeakers();
  28274. }
  28275. }
  28276. },
  28277. enumerable: true,
  28278. configurable: true
  28279. });
  28280. Scene.prototype._switchAudioModeForHeadphones = function () {
  28281. this.mainSoundTrack.switchPanningModelToHRTF();
  28282. for (var i = 0; i < this.soundTracks.length; i++) {
  28283. this.soundTracks[i].switchPanningModelToHRTF();
  28284. }
  28285. };
  28286. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28287. this.mainSoundTrack.switchPanningModelToEqualPower();
  28288. for (var i = 0; i < this.soundTracks.length; i++) {
  28289. this.soundTracks[i].switchPanningModelToEqualPower();
  28290. }
  28291. };
  28292. /**
  28293. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28294. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28295. * @returns the created depth renderer
  28296. */
  28297. Scene.prototype.enableDepthRenderer = function (camera) {
  28298. camera = camera || this.activeCamera;
  28299. if (!camera) {
  28300. throw "No camera available to enable depth renderer";
  28301. }
  28302. if (!this._depthRenderer[camera.id]) {
  28303. var textureType = 0;
  28304. if (this._engine.getCaps().textureHalfFloatRender) {
  28305. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28306. }
  28307. else if (this._engine.getCaps().textureFloatRender) {
  28308. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28309. }
  28310. else {
  28311. throw "Depth renderer does not support int texture type";
  28312. }
  28313. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28314. }
  28315. return this._depthRenderer[camera.id];
  28316. };
  28317. /**
  28318. * Disables a depth renderer for a given camera
  28319. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28320. */
  28321. Scene.prototype.disableDepthRenderer = function (camera) {
  28322. camera = camera || this.activeCamera;
  28323. if (!camera || !this._depthRenderer[camera.id]) {
  28324. return;
  28325. }
  28326. this._depthRenderer[camera.id].dispose();
  28327. delete this._depthRenderer[camera.id];
  28328. };
  28329. /**
  28330. * Enables a GeometryBufferRender and associates it with the scene
  28331. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28332. * @returns the GeometryBufferRenderer
  28333. */
  28334. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28335. if (ratio === void 0) { ratio = 1; }
  28336. if (this._geometryBufferRenderer) {
  28337. return this._geometryBufferRenderer;
  28338. }
  28339. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28340. if (!this._geometryBufferRenderer.isSupported) {
  28341. this._geometryBufferRenderer = null;
  28342. }
  28343. return this._geometryBufferRenderer;
  28344. };
  28345. /**
  28346. * Disables the GeometryBufferRender associated with the scene
  28347. */
  28348. Scene.prototype.disableGeometryBufferRenderer = function () {
  28349. if (!this._geometryBufferRenderer) {
  28350. return;
  28351. }
  28352. this._geometryBufferRenderer.dispose();
  28353. this._geometryBufferRenderer = null;
  28354. };
  28355. /**
  28356. * Freeze all materials
  28357. * A frozen material will not be updatable but should be faster to render
  28358. */
  28359. Scene.prototype.freezeMaterials = function () {
  28360. for (var i = 0; i < this.materials.length; i++) {
  28361. this.materials[i].freeze();
  28362. }
  28363. };
  28364. /**
  28365. * Unfreeze all materials
  28366. * A frozen material will not be updatable but should be faster to render
  28367. */
  28368. Scene.prototype.unfreezeMaterials = function () {
  28369. for (var i = 0; i < this.materials.length; i++) {
  28370. this.materials[i].unfreeze();
  28371. }
  28372. };
  28373. /**
  28374. * Releases all held ressources
  28375. */
  28376. Scene.prototype.dispose = function () {
  28377. this.beforeRender = null;
  28378. this.afterRender = null;
  28379. this.skeletons = [];
  28380. this.morphTargetManagers = [];
  28381. this.importedMeshesFiles = new Array();
  28382. this.stopAllAnimations();
  28383. this.resetCachedMaterial();
  28384. for (var key in this._depthRenderer) {
  28385. this._depthRenderer[key].dispose();
  28386. }
  28387. if (this._gamepadManager) {
  28388. this._gamepadManager.dispose();
  28389. this._gamepadManager = null;
  28390. }
  28391. // Smart arrays
  28392. if (this.activeCamera) {
  28393. this.activeCamera._activeMeshes.dispose();
  28394. this.activeCamera = null;
  28395. }
  28396. this._activeMeshes.dispose();
  28397. this._renderingManager.dispose();
  28398. this._processedMaterials.dispose();
  28399. this._activeParticleSystems.dispose();
  28400. this._activeSkeletons.dispose();
  28401. this._softwareSkinnedMeshes.dispose();
  28402. this._renderTargets.dispose();
  28403. this._registeredForLateAnimationBindings.dispose();
  28404. if (this._boundingBoxRenderer) {
  28405. this._boundingBoxRenderer.dispose();
  28406. }
  28407. this._meshesForIntersections.dispose();
  28408. this._toBeDisposed.dispose();
  28409. // Abort active requests
  28410. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28411. var request = _a[_i];
  28412. request.abort();
  28413. }
  28414. // Debug layer
  28415. if (this._debugLayer) {
  28416. this._debugLayer.hide();
  28417. }
  28418. // Events
  28419. this.onDisposeObservable.notifyObservers(this);
  28420. this.onDisposeObservable.clear();
  28421. this.onBeforeRenderObservable.clear();
  28422. this.onAfterRenderObservable.clear();
  28423. this.onBeforeRenderTargetsRenderObservable.clear();
  28424. this.onAfterRenderTargetsRenderObservable.clear();
  28425. this.onAfterStepObservable.clear();
  28426. this.onBeforeStepObservable.clear();
  28427. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28428. this.onAfterActiveMeshesEvaluationObservable.clear();
  28429. this.onBeforeParticlesRenderingObservable.clear();
  28430. this.onAfterParticlesRenderingObservable.clear();
  28431. this.onBeforeSpritesRenderingObservable.clear();
  28432. this.onAfterSpritesRenderingObservable.clear();
  28433. this.onBeforeDrawPhaseObservable.clear();
  28434. this.onAfterDrawPhaseObservable.clear();
  28435. this.onBeforePhysicsObservable.clear();
  28436. this.onAfterPhysicsObservable.clear();
  28437. this.onBeforeAnimationsObservable.clear();
  28438. this.onAfterAnimationsObservable.clear();
  28439. this.onDataLoadedObservable.clear();
  28440. this.detachControl();
  28441. // Release sounds & sounds tracks
  28442. if (BABYLON.AudioEngine) {
  28443. this.disposeSounds();
  28444. }
  28445. // VR Helper
  28446. if (this.VRHelper) {
  28447. this.VRHelper.dispose();
  28448. }
  28449. // Detach cameras
  28450. var canvas = this._engine.getRenderingCanvas();
  28451. if (canvas) {
  28452. var index;
  28453. for (index = 0; index < this.cameras.length; index++) {
  28454. this.cameras[index].detachControl(canvas);
  28455. }
  28456. }
  28457. // Release animation groups
  28458. while (this.animationGroups.length) {
  28459. this.animationGroups[0].dispose();
  28460. }
  28461. // Release lights
  28462. while (this.lights.length) {
  28463. this.lights[0].dispose();
  28464. }
  28465. // Release meshes
  28466. while (this.meshes.length) {
  28467. this.meshes[0].dispose(true);
  28468. }
  28469. while (this.transformNodes.length) {
  28470. this.removeTransformNode(this.transformNodes[0]);
  28471. }
  28472. // Release cameras
  28473. while (this.cameras.length) {
  28474. this.cameras[0].dispose();
  28475. }
  28476. // Release materials
  28477. if (this.defaultMaterial) {
  28478. this.defaultMaterial.dispose();
  28479. }
  28480. while (this.multiMaterials.length) {
  28481. this.multiMaterials[0].dispose();
  28482. }
  28483. while (this.materials.length) {
  28484. this.materials[0].dispose();
  28485. }
  28486. // Release particles
  28487. while (this.particleSystems.length) {
  28488. this.particleSystems[0].dispose();
  28489. }
  28490. // Release sprites
  28491. while (this.spriteManagers.length) {
  28492. this.spriteManagers[0].dispose();
  28493. }
  28494. // Release postProcesses
  28495. while (this.postProcesses.length) {
  28496. this.postProcesses[0].dispose();
  28497. }
  28498. // Release layers
  28499. while (this.layers.length) {
  28500. this.layers[0].dispose();
  28501. }
  28502. while (this.effectLayers.length) {
  28503. this.effectLayers[0].dispose();
  28504. }
  28505. // Release textures
  28506. while (this.textures.length) {
  28507. this.textures[0].dispose();
  28508. }
  28509. // Release UBO
  28510. this._sceneUbo.dispose();
  28511. if (this._alternateSceneUbo) {
  28512. this._alternateSceneUbo.dispose();
  28513. }
  28514. // Post-processes
  28515. this.postProcessManager.dispose();
  28516. if (this._postProcessRenderPipelineManager) {
  28517. this._postProcessRenderPipelineManager.dispose();
  28518. }
  28519. // Physics
  28520. if (this._physicsEngine) {
  28521. this.disablePhysicsEngine();
  28522. }
  28523. // Remove from engine
  28524. index = this._engine.scenes.indexOf(this);
  28525. if (index > -1) {
  28526. this._engine.scenes.splice(index, 1);
  28527. }
  28528. this._engine.wipeCaches(true);
  28529. this._isDisposed = true;
  28530. };
  28531. Object.defineProperty(Scene.prototype, "isDisposed", {
  28532. /**
  28533. * Gets if the scene is already disposed
  28534. */
  28535. get: function () {
  28536. return this._isDisposed;
  28537. },
  28538. enumerable: true,
  28539. configurable: true
  28540. });
  28541. /**
  28542. * Releases sounds & soundtracks
  28543. */
  28544. Scene.prototype.disposeSounds = function () {
  28545. if (!this._mainSoundTrack) {
  28546. return;
  28547. }
  28548. this.mainSoundTrack.dispose();
  28549. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28550. this.soundTracks[scIndex].dispose();
  28551. }
  28552. };
  28553. /**
  28554. * Call this function to reduce memory footprint of the scene.
  28555. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28556. */
  28557. Scene.prototype.clearCachedVertexData = function () {
  28558. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28559. var mesh = this.meshes[meshIndex];
  28560. var geometry = mesh.geometry;
  28561. if (geometry) {
  28562. geometry._indices = [];
  28563. for (var vbName in geometry._vertexBuffers) {
  28564. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28565. continue;
  28566. }
  28567. geometry._vertexBuffers[vbName]._buffer._data = null;
  28568. }
  28569. }
  28570. }
  28571. };
  28572. /**
  28573. * This function will remove the local cached buffer data from texture.
  28574. * It will save memory but will prevent the texture from being rebuilt
  28575. */
  28576. Scene.prototype.cleanCachedTextureBuffer = function () {
  28577. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28578. var baseTexture = _a[_i];
  28579. var buffer = baseTexture._buffer;
  28580. if (buffer) {
  28581. baseTexture._buffer = null;
  28582. }
  28583. }
  28584. };
  28585. // Octrees
  28586. /**
  28587. * Get the world extend vectors with an optional filter
  28588. *
  28589. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28590. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28591. */
  28592. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28593. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28594. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28595. filterPredicate = filterPredicate || (function () { return true; });
  28596. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28597. mesh.computeWorldMatrix(true);
  28598. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28599. return;
  28600. }
  28601. var boundingInfo = mesh.getBoundingInfo();
  28602. var minBox = boundingInfo.boundingBox.minimumWorld;
  28603. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28604. BABYLON.Tools.CheckExtends(minBox, min, max);
  28605. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28606. });
  28607. return {
  28608. min: min,
  28609. max: max
  28610. };
  28611. };
  28612. /**
  28613. * Creates or updates the octree used to boost selection (picking)
  28614. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28615. * @param maxCapacity defines the maximum capacity per leaf
  28616. * @param maxDepth defines the maximum depth of the octree
  28617. * @returns an octree of AbstractMesh
  28618. */
  28619. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28620. if (maxCapacity === void 0) { maxCapacity = 64; }
  28621. if (maxDepth === void 0) { maxDepth = 2; }
  28622. if (!this._selectionOctree) {
  28623. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28624. }
  28625. var worldExtends = this.getWorldExtends();
  28626. // Update octree
  28627. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28628. return this._selectionOctree;
  28629. };
  28630. // Picking
  28631. /**
  28632. * Creates a ray that can be used to pick in the scene
  28633. * @param x defines the x coordinate of the origin (on-screen)
  28634. * @param y defines the y coordinate of the origin (on-screen)
  28635. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28636. * @param camera defines the camera to use for the picking
  28637. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28638. * @returns a Ray
  28639. */
  28640. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28641. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28642. var result = BABYLON.Ray.Zero();
  28643. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28644. return result;
  28645. };
  28646. /**
  28647. * Creates a ray that can be used to pick in the scene
  28648. * @param x defines the x coordinate of the origin (on-screen)
  28649. * @param y defines the y coordinate of the origin (on-screen)
  28650. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28651. * @param result defines the ray where to store the picking ray
  28652. * @param camera defines the camera to use for the picking
  28653. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28654. * @returns the current scene
  28655. */
  28656. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28657. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28658. var engine = this._engine;
  28659. if (!camera) {
  28660. if (!this.activeCamera)
  28661. throw new Error("Active camera not set");
  28662. camera = this.activeCamera;
  28663. }
  28664. var cameraViewport = camera.viewport;
  28665. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28666. // Moving coordinates to local viewport world
  28667. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28668. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28669. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28670. return this;
  28671. };
  28672. /**
  28673. * Creates a ray that can be used to pick in the scene
  28674. * @param x defines the x coordinate of the origin (on-screen)
  28675. * @param y defines the y coordinate of the origin (on-screen)
  28676. * @param camera defines the camera to use for the picking
  28677. * @returns a Ray
  28678. */
  28679. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28680. var result = BABYLON.Ray.Zero();
  28681. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28682. return result;
  28683. };
  28684. /**
  28685. * Creates a ray that can be used to pick in the scene
  28686. * @param x defines the x coordinate of the origin (on-screen)
  28687. * @param y defines the y coordinate of the origin (on-screen)
  28688. * @param result defines the ray where to store the picking ray
  28689. * @param camera defines the camera to use for the picking
  28690. * @returns the current scene
  28691. */
  28692. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28693. if (!BABYLON.PickingInfo) {
  28694. return this;
  28695. }
  28696. var engine = this._engine;
  28697. if (!camera) {
  28698. if (!this.activeCamera)
  28699. throw new Error("Active camera not set");
  28700. camera = this.activeCamera;
  28701. }
  28702. var cameraViewport = camera.viewport;
  28703. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28704. var identity = BABYLON.Matrix.Identity();
  28705. // Moving coordinates to local viewport world
  28706. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28707. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28708. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28709. return this;
  28710. };
  28711. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28712. if (!BABYLON.PickingInfo) {
  28713. return null;
  28714. }
  28715. var pickingInfo = null;
  28716. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28717. var mesh = this.meshes[meshIndex];
  28718. if (predicate) {
  28719. if (!predicate(mesh)) {
  28720. continue;
  28721. }
  28722. }
  28723. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28724. continue;
  28725. }
  28726. var world = mesh.getWorldMatrix();
  28727. var ray = rayFunction(world);
  28728. var result = mesh.intersects(ray, fastCheck);
  28729. if (!result || !result.hit)
  28730. continue;
  28731. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28732. continue;
  28733. pickingInfo = result;
  28734. if (fastCheck) {
  28735. break;
  28736. }
  28737. }
  28738. return pickingInfo || new BABYLON.PickingInfo();
  28739. };
  28740. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28741. if (!BABYLON.PickingInfo) {
  28742. return null;
  28743. }
  28744. var pickingInfos = new Array();
  28745. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28746. var mesh = this.meshes[meshIndex];
  28747. if (predicate) {
  28748. if (!predicate(mesh)) {
  28749. continue;
  28750. }
  28751. }
  28752. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28753. continue;
  28754. }
  28755. var world = mesh.getWorldMatrix();
  28756. var ray = rayFunction(world);
  28757. var result = mesh.intersects(ray, false);
  28758. if (!result || !result.hit)
  28759. continue;
  28760. pickingInfos.push(result);
  28761. }
  28762. return pickingInfos;
  28763. };
  28764. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28765. if (!BABYLON.PickingInfo) {
  28766. return null;
  28767. }
  28768. var pickingInfo = null;
  28769. if (!camera) {
  28770. if (!this.activeCamera) {
  28771. return null;
  28772. }
  28773. camera = this.activeCamera;
  28774. }
  28775. if (this.spriteManagers.length > 0) {
  28776. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28777. var spriteManager = this.spriteManagers[spriteIndex];
  28778. if (!spriteManager.isPickable) {
  28779. continue;
  28780. }
  28781. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28782. if (!result || !result.hit)
  28783. continue;
  28784. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28785. continue;
  28786. pickingInfo = result;
  28787. if (fastCheck) {
  28788. break;
  28789. }
  28790. }
  28791. }
  28792. return pickingInfo || new BABYLON.PickingInfo();
  28793. };
  28794. /** Launch a ray to try to pick a mesh in the scene
  28795. * @param x position on screen
  28796. * @param y position on screen
  28797. * @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
  28798. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28799. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28800. * @returns a PickingInfo
  28801. */
  28802. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28803. var _this = this;
  28804. if (!BABYLON.PickingInfo) {
  28805. return null;
  28806. }
  28807. var result = this._internalPick(function (world) {
  28808. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28809. return _this._tempPickingRay;
  28810. }, predicate, fastCheck);
  28811. if (result) {
  28812. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28813. }
  28814. return result;
  28815. };
  28816. /** Launch a ray to try to pick a sprite in the scene
  28817. * @param x position on screen
  28818. * @param y position on screen
  28819. * @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
  28820. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28821. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28822. * @returns a PickingInfo
  28823. */
  28824. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28825. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28826. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28827. };
  28828. /** Use the given ray to pick a mesh in the scene
  28829. * @param ray The ray to use to pick meshes
  28830. * @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
  28831. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28832. * @returns a PickingInfo
  28833. */
  28834. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28835. var _this = this;
  28836. var result = this._internalPick(function (world) {
  28837. if (!_this._pickWithRayInverseMatrix) {
  28838. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28839. }
  28840. world.invertToRef(_this._pickWithRayInverseMatrix);
  28841. if (!_this._cachedRayForTransform) {
  28842. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28843. }
  28844. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28845. return _this._cachedRayForTransform;
  28846. }, predicate, fastCheck);
  28847. if (result) {
  28848. result.ray = ray;
  28849. }
  28850. return result;
  28851. };
  28852. /**
  28853. * Launch a ray to try to pick a mesh in the scene
  28854. * @param x X position on screen
  28855. * @param y Y position on screen
  28856. * @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
  28857. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28858. * @returns an array of PickingInfo
  28859. */
  28860. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28861. var _this = this;
  28862. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28863. };
  28864. /**
  28865. * Launch a ray to try to pick a mesh in the scene
  28866. * @param ray Ray to use
  28867. * @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
  28868. * @returns an array of PickingInfo
  28869. */
  28870. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28871. var _this = this;
  28872. return this._internalMultiPick(function (world) {
  28873. if (!_this._pickWithRayInverseMatrix) {
  28874. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28875. }
  28876. world.invertToRef(_this._pickWithRayInverseMatrix);
  28877. if (!_this._cachedRayForTransform) {
  28878. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28879. }
  28880. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28881. return _this._cachedRayForTransform;
  28882. }, predicate);
  28883. };
  28884. /**
  28885. * Force the value of meshUnderPointer
  28886. * @param mesh defines the mesh to use
  28887. */
  28888. Scene.prototype.setPointerOverMesh = function (mesh) {
  28889. if (this._pointerOverMesh === mesh) {
  28890. return;
  28891. }
  28892. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28893. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28894. }
  28895. this._pointerOverMesh = mesh;
  28896. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28897. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28898. }
  28899. };
  28900. /**
  28901. * Gets the mesh under the pointer
  28902. * @returns a Mesh or null if no mesh is under the pointer
  28903. */
  28904. Scene.prototype.getPointerOverMesh = function () {
  28905. return this._pointerOverMesh;
  28906. };
  28907. /**
  28908. * Force the sprite under the pointer
  28909. * @param sprite defines the sprite to use
  28910. */
  28911. Scene.prototype.setPointerOverSprite = function (sprite) {
  28912. if (this._pointerOverSprite === sprite) {
  28913. return;
  28914. }
  28915. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28916. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28917. }
  28918. this._pointerOverSprite = sprite;
  28919. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28920. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28921. }
  28922. };
  28923. /**
  28924. * Gets the sprite under the pointer
  28925. * @returns a Sprite or null if no sprite is under the pointer
  28926. */
  28927. Scene.prototype.getPointerOverSprite = function () {
  28928. return this._pointerOverSprite;
  28929. };
  28930. // Physics
  28931. /**
  28932. * Gets the current physics engine
  28933. * @returns a PhysicsEngine or null if none attached
  28934. */
  28935. Scene.prototype.getPhysicsEngine = function () {
  28936. return this._physicsEngine;
  28937. };
  28938. /**
  28939. * Enables physics to the current scene
  28940. * @param gravity defines the scene's gravity for the physics engine
  28941. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28942. * @return a boolean indicating if the physics engine was initialized
  28943. */
  28944. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28945. if (gravity === void 0) { gravity = null; }
  28946. if (this._physicsEngine) {
  28947. return true;
  28948. }
  28949. try {
  28950. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28951. return true;
  28952. }
  28953. catch (e) {
  28954. BABYLON.Tools.Error(e.message);
  28955. return false;
  28956. }
  28957. };
  28958. /**
  28959. * Disables and disposes the physics engine associated with the scene
  28960. */
  28961. Scene.prototype.disablePhysicsEngine = function () {
  28962. if (!this._physicsEngine) {
  28963. return;
  28964. }
  28965. this._physicsEngine.dispose();
  28966. this._physicsEngine = null;
  28967. };
  28968. /**
  28969. * Gets a boolean indicating if there is an active physics engine
  28970. * @returns a boolean indicating if there is an active physics engine
  28971. */
  28972. Scene.prototype.isPhysicsEnabled = function () {
  28973. return this._physicsEngine !== undefined;
  28974. };
  28975. /**
  28976. * Deletes a physics compound impostor
  28977. * @param compound defines the compound to delete
  28978. */
  28979. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28980. var mesh = compound.parts[0].mesh;
  28981. if (mesh.physicsImpostor) {
  28982. mesh.physicsImpostor.dispose( /*true*/);
  28983. mesh.physicsImpostor = null;
  28984. }
  28985. };
  28986. // Misc.
  28987. /** @hidden */
  28988. Scene.prototype._rebuildGeometries = function () {
  28989. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28990. var geometry = _a[_i];
  28991. geometry._rebuild();
  28992. }
  28993. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28994. var mesh = _c[_b];
  28995. mesh._rebuild();
  28996. }
  28997. if (this.postProcessManager) {
  28998. this.postProcessManager._rebuild();
  28999. }
  29000. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  29001. var layer = _e[_d];
  29002. layer._rebuild();
  29003. }
  29004. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  29005. var effectLayer = _g[_f];
  29006. effectLayer._rebuild();
  29007. }
  29008. if (this._boundingBoxRenderer) {
  29009. this._boundingBoxRenderer._rebuild();
  29010. }
  29011. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  29012. var system = _j[_h];
  29013. system.rebuild();
  29014. }
  29015. if (this._postProcessRenderPipelineManager) {
  29016. this._postProcessRenderPipelineManager._rebuild();
  29017. }
  29018. };
  29019. /** @hidden */
  29020. Scene.prototype._rebuildTextures = function () {
  29021. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29022. var texture = _a[_i];
  29023. texture._rebuild();
  29024. }
  29025. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29026. };
  29027. /**
  29028. * Creates a default light for the scene.
  29029. * @param replace Whether to replace the existing lights in the scene.
  29030. */
  29031. Scene.prototype.createDefaultLight = function (replace) {
  29032. if (replace === void 0) { replace = false; }
  29033. // Dispose existing light in replace mode.
  29034. if (replace) {
  29035. if (this.lights) {
  29036. for (var i = 0; i < this.lights.length; i++) {
  29037. this.lights[i].dispose();
  29038. }
  29039. }
  29040. }
  29041. // Light
  29042. if (this.lights.length === 0) {
  29043. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29044. }
  29045. };
  29046. /**
  29047. * Creates a default camera for the scene.
  29048. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29049. * @param replace Whether to replace the existing active camera in the scene.
  29050. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29051. */
  29052. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29053. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29054. if (replace === void 0) { replace = false; }
  29055. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29056. // Dispose existing camera in replace mode.
  29057. if (replace) {
  29058. if (this.activeCamera) {
  29059. this.activeCamera.dispose();
  29060. this.activeCamera = null;
  29061. }
  29062. }
  29063. // Camera
  29064. if (!this.activeCamera) {
  29065. var worldExtends = this.getWorldExtends();
  29066. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29067. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29068. var camera;
  29069. var radius = worldSize.length() * 1.5;
  29070. // empty scene scenario!
  29071. if (!isFinite(radius)) {
  29072. radius = 1;
  29073. worldCenter.copyFromFloats(0, 0, 0);
  29074. }
  29075. if (createArcRotateCamera) {
  29076. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29077. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29078. arcRotateCamera.wheelPrecision = 100 / radius;
  29079. camera = arcRotateCamera;
  29080. }
  29081. else {
  29082. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29083. freeCamera.setTarget(worldCenter);
  29084. camera = freeCamera;
  29085. }
  29086. camera.minZ = radius * 0.01;
  29087. camera.maxZ = radius * 1000;
  29088. camera.speed = radius * 0.2;
  29089. this.activeCamera = camera;
  29090. var canvas = this.getEngine().getRenderingCanvas();
  29091. if (attachCameraControls && canvas) {
  29092. camera.attachControl(canvas);
  29093. }
  29094. }
  29095. };
  29096. /**
  29097. * Creates a default camera and a default light
  29098. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29099. * @param replace defines if the camera and/or light will replace the existing ones
  29100. * @param attachCameraControls defines if attachControl will be called on the new camera
  29101. */
  29102. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29103. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29104. if (replace === void 0) { replace = false; }
  29105. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29106. this.createDefaultLight(replace);
  29107. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29108. };
  29109. /**
  29110. * Creates a new sky box
  29111. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29112. * @param environmentTexture defines the texture to use as environment texture
  29113. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29114. * @param scale defines the overall scale of the skybox
  29115. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29116. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29117. * @returns a new mesh holding the sky box
  29118. */
  29119. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29120. if (pbr === void 0) { pbr = false; }
  29121. if (scale === void 0) { scale = 1000; }
  29122. if (blur === void 0) { blur = 0; }
  29123. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29124. if (!environmentTexture) {
  29125. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29126. return null;
  29127. }
  29128. if (setGlobalEnvTexture) {
  29129. if (environmentTexture) {
  29130. this.environmentTexture = environmentTexture;
  29131. }
  29132. }
  29133. // Skybox
  29134. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29135. if (pbr) {
  29136. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29137. hdrSkyboxMaterial.backFaceCulling = false;
  29138. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29139. if (hdrSkyboxMaterial.reflectionTexture) {
  29140. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29141. }
  29142. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29143. hdrSkyboxMaterial.disableLighting = true;
  29144. hdrSkyboxMaterial.twoSidedLighting = true;
  29145. hdrSkybox.infiniteDistance = true;
  29146. hdrSkybox.material = hdrSkyboxMaterial;
  29147. }
  29148. else {
  29149. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29150. skyboxMaterial.backFaceCulling = false;
  29151. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29152. if (skyboxMaterial.reflectionTexture) {
  29153. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29154. }
  29155. skyboxMaterial.disableLighting = true;
  29156. hdrSkybox.infiniteDistance = true;
  29157. hdrSkybox.material = skyboxMaterial;
  29158. }
  29159. return hdrSkybox;
  29160. };
  29161. /**
  29162. * Creates a new environment
  29163. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29164. * @param options defines the options you can use to configure the environment
  29165. * @returns the new EnvironmentHelper
  29166. */
  29167. Scene.prototype.createDefaultEnvironment = function (options) {
  29168. if (BABYLON.EnvironmentHelper) {
  29169. return new BABYLON.EnvironmentHelper(options, this);
  29170. }
  29171. return null;
  29172. };
  29173. /**
  29174. * Creates a new VREXperienceHelper
  29175. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29176. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29177. * @returns a new VREXperienceHelper
  29178. */
  29179. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29180. if (webVROptions === void 0) { webVROptions = {}; }
  29181. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29182. };
  29183. // Tags
  29184. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29185. if (tagsQuery === undefined) {
  29186. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29187. return list;
  29188. }
  29189. var listByTags = [];
  29190. forEach = forEach || (function (item) { return; });
  29191. for (var i in list) {
  29192. var item = list[i];
  29193. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29194. listByTags.push(item);
  29195. forEach(item);
  29196. }
  29197. }
  29198. return listByTags;
  29199. };
  29200. /**
  29201. * Get a list of meshes by tags
  29202. * @param tagsQuery defines the tags query to use
  29203. * @param forEach defines a predicate used to filter results
  29204. * @returns an array of Mesh
  29205. */
  29206. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29207. return this._getByTags(this.meshes, tagsQuery, forEach);
  29208. };
  29209. /**
  29210. * Get a list of cameras by tags
  29211. * @param tagsQuery defines the tags query to use
  29212. * @param forEach defines a predicate used to filter results
  29213. * @returns an array of Camera
  29214. */
  29215. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29216. return this._getByTags(this.cameras, tagsQuery, forEach);
  29217. };
  29218. /**
  29219. * Get a list of lights by tags
  29220. * @param tagsQuery defines the tags query to use
  29221. * @param forEach defines a predicate used to filter results
  29222. * @returns an array of Light
  29223. */
  29224. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29225. return this._getByTags(this.lights, tagsQuery, forEach);
  29226. };
  29227. /**
  29228. * Get a list of materials by tags
  29229. * @param tagsQuery defines the tags query to use
  29230. * @param forEach defines a predicate used to filter results
  29231. * @returns an array of Material
  29232. */
  29233. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29234. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29235. };
  29236. /**
  29237. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29238. * This allowed control for front to back rendering or reversly depending of the special needs.
  29239. *
  29240. * @param renderingGroupId The rendering group id corresponding to its index
  29241. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29242. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29243. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29244. */
  29245. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29246. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29247. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29248. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29249. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29250. };
  29251. /**
  29252. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29253. *
  29254. * @param renderingGroupId The rendering group id corresponding to its index
  29255. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29256. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29257. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29258. */
  29259. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29260. if (depth === void 0) { depth = true; }
  29261. if (stencil === void 0) { stencil = true; }
  29262. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29263. };
  29264. /**
  29265. * Will flag all materials as dirty to trigger new shader compilation
  29266. * @param flag defines the flag used to specify which material part must be marked as dirty
  29267. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29268. */
  29269. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29270. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29271. var material = _a[_i];
  29272. if (predicate && !predicate(material)) {
  29273. continue;
  29274. }
  29275. material.markAsDirty(flag);
  29276. }
  29277. };
  29278. /** @hidden */
  29279. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29280. var _this = this;
  29281. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29282. this._activeRequests.push(request);
  29283. request.onCompleteObservable.add(function (request) {
  29284. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29285. });
  29286. return request;
  29287. };
  29288. /** @hidden */
  29289. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29290. var _this = this;
  29291. return new Promise(function (resolve, reject) {
  29292. _this._loadFile(url, function (data) {
  29293. resolve(data);
  29294. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29295. reject(exception);
  29296. });
  29297. });
  29298. };
  29299. // Statics
  29300. Scene._FOGMODE_NONE = 0;
  29301. Scene._FOGMODE_EXP = 1;
  29302. Scene._FOGMODE_EXP2 = 2;
  29303. Scene._FOGMODE_LINEAR = 3;
  29304. Scene._uniqueIdCounter = 0;
  29305. /**
  29306. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29307. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29308. */
  29309. Scene.MinDeltaTime = 1.0;
  29310. /**
  29311. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29312. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29313. */
  29314. Scene.MaxDeltaTime = 1000.0;
  29315. /** The distance in pixel that you have to move to prevent some events */
  29316. Scene.DragMovementThreshold = 10; // in pixels
  29317. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29318. Scene.LongPressDelay = 500; // in milliseconds
  29319. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29320. Scene.DoubleClickDelay = 300; // in milliseconds
  29321. /** If you need to check double click without raising a single click at first click, enable this flag */
  29322. Scene.ExclusiveDoubleClickMode = false;
  29323. return Scene;
  29324. }());
  29325. BABYLON.Scene = Scene;
  29326. })(BABYLON || (BABYLON = {}));
  29327. //# sourceMappingURL=babylon.scene.js.map
  29328. var BABYLON;
  29329. (function (BABYLON) {
  29330. /**
  29331. * Set of assets to keep when moving a scene into an asset container.
  29332. */
  29333. var KeepAssets = /** @class */ (function () {
  29334. function KeepAssets() {
  29335. /**
  29336. * Cameras to keep.
  29337. */
  29338. this.cameras = new Array();
  29339. /**
  29340. * Lights to keep.
  29341. */
  29342. this.lights = new Array();
  29343. /**
  29344. * Meshes to keep.
  29345. */
  29346. this.meshes = new Array();
  29347. /**
  29348. * Skeletons to keep.
  29349. */
  29350. this.skeletons = new Array();
  29351. /**
  29352. * ParticleSystems to keep.
  29353. */
  29354. this.particleSystems = new Array();
  29355. /**
  29356. * Animations to keep.
  29357. */
  29358. this.animations = new Array();
  29359. /**
  29360. * AnimationGroups to keep.
  29361. */
  29362. this.animationGroups = new Array();
  29363. /**
  29364. * MultiMaterials to keep.
  29365. */
  29366. this.multiMaterials = new Array();
  29367. /**
  29368. * Materials to keep.
  29369. */
  29370. this.materials = new Array();
  29371. /**
  29372. * MorphTargetManagers to keep.
  29373. */
  29374. this.morphTargetManagers = new Array();
  29375. /**
  29376. * Geometries to keep.
  29377. */
  29378. this.geometries = new Array();
  29379. /**
  29380. * TransformNodes to keep.
  29381. */
  29382. this.transformNodes = new Array();
  29383. /**
  29384. * LensFlareSystems to keep.
  29385. */
  29386. this.lensFlareSystems = new Array();
  29387. /**
  29388. * ShadowGenerators to keep.
  29389. */
  29390. this.shadowGenerators = new Array();
  29391. /**
  29392. * ActionManagers to keep.
  29393. */
  29394. this.actionManagers = new Array();
  29395. /**
  29396. * Sounds to keep.
  29397. */
  29398. this.sounds = new Array();
  29399. /**
  29400. * Textures to keep.
  29401. */
  29402. this.textures = new Array();
  29403. /**
  29404. * Effect layers to keep.
  29405. */
  29406. this.effectLayers = new Array();
  29407. }
  29408. return KeepAssets;
  29409. }());
  29410. BABYLON.KeepAssets = KeepAssets;
  29411. /**
  29412. * Container with a set of assets that can be added or removed from a scene.
  29413. */
  29414. var AssetContainer = /** @class */ (function () {
  29415. /**
  29416. * Instantiates an AssetContainer.
  29417. * @param scene The scene the AssetContainer belongs to.
  29418. */
  29419. function AssetContainer(scene) {
  29420. // Objects
  29421. /**
  29422. * Cameras populated in the container.
  29423. */
  29424. this.cameras = new Array();
  29425. /**
  29426. * Lights populated in the container.
  29427. */
  29428. this.lights = new Array();
  29429. /**
  29430. * Meshes populated in the container.
  29431. */
  29432. this.meshes = new Array();
  29433. /**
  29434. * Skeletons populated in the container.
  29435. */
  29436. this.skeletons = new Array();
  29437. /**
  29438. * ParticleSystems populated in the container.
  29439. */
  29440. this.particleSystems = new Array();
  29441. /**
  29442. * Animations populated in the container.
  29443. */
  29444. this.animations = new Array();
  29445. /**
  29446. * AnimationGroups populated in the container.
  29447. */
  29448. this.animationGroups = new Array();
  29449. /**
  29450. * MultiMaterials populated in the container.
  29451. */
  29452. this.multiMaterials = new Array();
  29453. /**
  29454. * Materials populated in the container.
  29455. */
  29456. this.materials = new Array();
  29457. /**
  29458. * MorphTargetManagers populated in the container.
  29459. */
  29460. this.morphTargetManagers = new Array();
  29461. /**
  29462. * Geometries populated in the container.
  29463. */
  29464. this.geometries = new Array();
  29465. /**
  29466. * TransformNodes populated in the container.
  29467. */
  29468. this.transformNodes = new Array();
  29469. /**
  29470. * LensFlareSystems populated in the container.
  29471. */
  29472. this.lensFlareSystems = new Array();
  29473. /**
  29474. * ShadowGenerators populated in the container.
  29475. */
  29476. this.shadowGenerators = new Array();
  29477. /**
  29478. * ActionManagers populated in the container.
  29479. */
  29480. this.actionManagers = new Array();
  29481. /**
  29482. * Sounds populated in the container.
  29483. */
  29484. this.sounds = new Array();
  29485. /**
  29486. * Textures populated in the container.
  29487. */
  29488. this.textures = new Array();
  29489. /**
  29490. * Effect layers populated in the container.
  29491. */
  29492. this.effectLayers = new Array();
  29493. this.scene = scene;
  29494. }
  29495. /**
  29496. * Adds all the assets from the container to the scene.
  29497. */
  29498. AssetContainer.prototype.addAllToScene = function () {
  29499. var _this = this;
  29500. this.cameras.forEach(function (o) {
  29501. _this.scene.addCamera(o);
  29502. });
  29503. this.lights.forEach(function (o) {
  29504. _this.scene.addLight(o);
  29505. });
  29506. this.meshes.forEach(function (o) {
  29507. _this.scene.addMesh(o);
  29508. });
  29509. this.skeletons.forEach(function (o) {
  29510. _this.scene.addSkeleton(o);
  29511. });
  29512. this.particleSystems.forEach(function (o) {
  29513. _this.scene.addParticleSystem(o);
  29514. });
  29515. this.animations.forEach(function (o) {
  29516. _this.scene.addAnimation(o);
  29517. });
  29518. this.animationGroups.forEach(function (o) {
  29519. _this.scene.addAnimationGroup(o);
  29520. });
  29521. this.multiMaterials.forEach(function (o) {
  29522. _this.scene.addMultiMaterial(o);
  29523. });
  29524. this.materials.forEach(function (o) {
  29525. _this.scene.addMaterial(o);
  29526. });
  29527. this.morphTargetManagers.forEach(function (o) {
  29528. _this.scene.addMorphTargetManager(o);
  29529. });
  29530. this.geometries.forEach(function (o) {
  29531. _this.scene.addGeometry(o);
  29532. });
  29533. this.transformNodes.forEach(function (o) {
  29534. _this.scene.addTransformNode(o);
  29535. });
  29536. this.lensFlareSystems.forEach(function (o) {
  29537. _this.scene.addLensFlareSystem(o);
  29538. });
  29539. this.actionManagers.forEach(function (o) {
  29540. _this.scene.addActionManager(o);
  29541. });
  29542. this.sounds.forEach(function (o) {
  29543. o.play();
  29544. o.autoplay = true;
  29545. _this.scene.mainSoundTrack.AddSound(o);
  29546. });
  29547. this.textures.forEach(function (o) {
  29548. _this.scene.addTexture(o);
  29549. });
  29550. this.effectLayers.forEach(function (o) {
  29551. _this.scene.addEffectLayer(o);
  29552. });
  29553. };
  29554. /**
  29555. * Removes all the assets in the container from the scene
  29556. */
  29557. AssetContainer.prototype.removeAllFromScene = function () {
  29558. var _this = this;
  29559. this.cameras.forEach(function (o) {
  29560. _this.scene.removeCamera(o);
  29561. });
  29562. this.lights.forEach(function (o) {
  29563. _this.scene.removeLight(o);
  29564. });
  29565. this.meshes.forEach(function (o) {
  29566. _this.scene.removeMesh(o);
  29567. });
  29568. this.skeletons.forEach(function (o) {
  29569. _this.scene.removeSkeleton(o);
  29570. });
  29571. this.particleSystems.forEach(function (o) {
  29572. _this.scene.removeParticleSystem(o);
  29573. });
  29574. this.animations.forEach(function (o) {
  29575. _this.scene.removeAnimation(o);
  29576. });
  29577. this.animationGroups.forEach(function (o) {
  29578. _this.scene.removeAnimationGroup(o);
  29579. });
  29580. this.multiMaterials.forEach(function (o) {
  29581. _this.scene.removeMultiMaterial(o);
  29582. });
  29583. this.materials.forEach(function (o) {
  29584. _this.scene.removeMaterial(o);
  29585. });
  29586. this.morphTargetManagers.forEach(function (o) {
  29587. _this.scene.removeMorphTargetManager(o);
  29588. });
  29589. this.geometries.forEach(function (o) {
  29590. _this.scene.removeGeometry(o);
  29591. });
  29592. this.transformNodes.forEach(function (o) {
  29593. _this.scene.removeTransformNode(o);
  29594. });
  29595. this.lensFlareSystems.forEach(function (o) {
  29596. _this.scene.removeLensFlareSystem(o);
  29597. });
  29598. this.actionManagers.forEach(function (o) {
  29599. _this.scene.removeActionManager(o);
  29600. });
  29601. this.sounds.forEach(function (o) {
  29602. o.stop();
  29603. o.autoplay = false;
  29604. _this.scene.mainSoundTrack.RemoveSound(o);
  29605. });
  29606. this.textures.forEach(function (o) {
  29607. _this.scene.removeTexture(o);
  29608. });
  29609. this.effectLayers.forEach(function (o) {
  29610. _this.scene.removeEffectLayer(o);
  29611. });
  29612. };
  29613. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29614. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29615. var asset = sourceAssets_1[_i];
  29616. var move = true;
  29617. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29618. var keepAsset = keepAssets_1[_a];
  29619. if (asset === keepAsset) {
  29620. move = false;
  29621. break;
  29622. }
  29623. }
  29624. if (move) {
  29625. targetAssets.push(asset);
  29626. }
  29627. }
  29628. };
  29629. /**
  29630. * Removes all the assets contained in the scene and adds them to the container.
  29631. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29632. */
  29633. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29634. if (keepAssets === undefined) {
  29635. keepAssets = new KeepAssets();
  29636. }
  29637. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29638. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29639. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29640. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29641. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29642. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29643. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29644. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29645. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29646. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29647. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29648. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29649. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29650. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29651. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29652. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29653. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29654. this.removeAllFromScene();
  29655. };
  29656. /**
  29657. * 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.
  29658. * @returns the root mesh
  29659. */
  29660. AssetContainer.prototype.createRootMesh = function () {
  29661. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29662. this.meshes.forEach(function (m) {
  29663. if (!m.parent) {
  29664. rootMesh.addChild(m);
  29665. }
  29666. });
  29667. this.meshes.unshift(rootMesh);
  29668. return rootMesh;
  29669. };
  29670. return AssetContainer;
  29671. }());
  29672. BABYLON.AssetContainer = AssetContainer;
  29673. })(BABYLON || (BABYLON = {}));
  29674. //# sourceMappingURL=babylon.assetContainer.js.map
  29675. var BABYLON;
  29676. (function (BABYLON) {
  29677. var Buffer = /** @class */ (function () {
  29678. /**
  29679. * Constructor
  29680. * @param engine the engine
  29681. * @param data the data to use for this buffer
  29682. * @param updatable whether the data is updatable
  29683. * @param stride the stride (optional)
  29684. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29685. * @param instanced whether the buffer is instanced (optional)
  29686. * @param useBytes set to true if the stride in in bytes (optional)
  29687. */
  29688. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29689. if (stride === void 0) { stride = 0; }
  29690. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29691. if (instanced === void 0) { instanced = false; }
  29692. if (useBytes === void 0) { useBytes = false; }
  29693. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29694. this._engine = engine.getScene().getEngine();
  29695. }
  29696. else {
  29697. this._engine = engine;
  29698. }
  29699. this._updatable = updatable;
  29700. this._instanced = instanced;
  29701. this._data = data;
  29702. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29703. if (!postponeInternalCreation) { // by default
  29704. this.create();
  29705. }
  29706. }
  29707. /**
  29708. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29709. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29710. * @param offset defines offset in the buffer (0 by default)
  29711. * @param size defines the size in floats of attributes (position is 3 for instance)
  29712. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29713. * @param instanced defines if the vertex buffer contains indexed data
  29714. * @param useBytes defines if the offset and stride are in bytes
  29715. * @returns the new vertex buffer
  29716. */
  29717. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29718. if (useBytes === void 0) { useBytes = false; }
  29719. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29720. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29721. // a lot of these parameters are ignored as they are overriden by the buffer
  29722. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29723. };
  29724. // Properties
  29725. Buffer.prototype.isUpdatable = function () {
  29726. return this._updatable;
  29727. };
  29728. Buffer.prototype.getData = function () {
  29729. return this._data;
  29730. };
  29731. Buffer.prototype.getBuffer = function () {
  29732. return this._buffer;
  29733. };
  29734. /**
  29735. * Gets the stride in float32 units (i.e. byte stride / 4).
  29736. * May not be an integer if the byte stride is not divisible by 4.
  29737. * DEPRECATED. Use byteStride instead.
  29738. * @returns the stride in float32 units
  29739. */
  29740. Buffer.prototype.getStrideSize = function () {
  29741. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29742. };
  29743. // Methods
  29744. Buffer.prototype.create = function (data) {
  29745. if (data === void 0) { data = null; }
  29746. if (!data && this._buffer) {
  29747. return; // nothing to do
  29748. }
  29749. data = data || this._data;
  29750. if (!data) {
  29751. return;
  29752. }
  29753. if (!this._buffer) { // create buffer
  29754. if (this._updatable) {
  29755. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29756. this._data = data;
  29757. }
  29758. else {
  29759. this._buffer = this._engine.createVertexBuffer(data);
  29760. }
  29761. }
  29762. else if (this._updatable) { // update buffer
  29763. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29764. this._data = data;
  29765. }
  29766. };
  29767. Buffer.prototype._rebuild = function () {
  29768. this._buffer = null;
  29769. this.create(this._data);
  29770. };
  29771. Buffer.prototype.update = function (data) {
  29772. this.create(data);
  29773. };
  29774. /**
  29775. * Updates the data directly.
  29776. * @param data the new data
  29777. * @param offset the new offset
  29778. * @param vertexCount the vertex count (optional)
  29779. * @param useBytes set to true if the offset is in bytes
  29780. */
  29781. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29782. if (useBytes === void 0) { useBytes = false; }
  29783. if (!this._buffer) {
  29784. return;
  29785. }
  29786. if (this._updatable) { // update buffer
  29787. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29788. this._data = null;
  29789. }
  29790. };
  29791. Buffer.prototype.dispose = function () {
  29792. if (!this._buffer) {
  29793. return;
  29794. }
  29795. if (this._engine._releaseBuffer(this._buffer)) {
  29796. this._buffer = null;
  29797. }
  29798. };
  29799. return Buffer;
  29800. }());
  29801. BABYLON.Buffer = Buffer;
  29802. })(BABYLON || (BABYLON = {}));
  29803. //# sourceMappingURL=babylon.buffer.js.map
  29804. var BABYLON;
  29805. (function (BABYLON) {
  29806. var VertexBuffer = /** @class */ (function () {
  29807. /**
  29808. * Constructor
  29809. * @param engine the engine
  29810. * @param data the data to use for this vertex buffer
  29811. * @param kind the vertex buffer kind
  29812. * @param updatable whether the data is updatable
  29813. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29814. * @param stride the stride (optional)
  29815. * @param instanced whether the buffer is instanced (optional)
  29816. * @param offset the offset of the data (optional)
  29817. * @param size the number of components (optional)
  29818. * @param type the type of the component (optional)
  29819. * @param normalized whether the data contains normalized data (optional)
  29820. * @param useBytes set to true if stride and offset are in bytes (optional)
  29821. */
  29822. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29823. if (normalized === void 0) { normalized = false; }
  29824. if (useBytes === void 0) { useBytes = false; }
  29825. if (data instanceof BABYLON.Buffer) {
  29826. this._buffer = data;
  29827. this._ownsBuffer = false;
  29828. }
  29829. else {
  29830. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29831. this._ownsBuffer = true;
  29832. }
  29833. this._kind = kind;
  29834. if (type == undefined) {
  29835. var data_1 = this.getData();
  29836. this.type = VertexBuffer.FLOAT;
  29837. if (data_1 instanceof Int8Array)
  29838. this.type = VertexBuffer.BYTE;
  29839. else if (data_1 instanceof Uint8Array)
  29840. this.type = VertexBuffer.UNSIGNED_BYTE;
  29841. else if (data_1 instanceof Int16Array)
  29842. this.type = VertexBuffer.SHORT;
  29843. else if (data_1 instanceof Uint16Array)
  29844. this.type = VertexBuffer.UNSIGNED_SHORT;
  29845. else if (data_1 instanceof Int32Array)
  29846. this.type = VertexBuffer.INT;
  29847. else if (data_1 instanceof Uint32Array)
  29848. this.type = VertexBuffer.UNSIGNED_INT;
  29849. }
  29850. else {
  29851. this.type = type;
  29852. }
  29853. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29854. if (useBytes) {
  29855. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29856. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29857. this.byteOffset = offset || 0;
  29858. }
  29859. else {
  29860. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29861. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29862. this.byteOffset = (offset || 0) * typeByteLength;
  29863. }
  29864. this.normalized = normalized;
  29865. this._instanced = instanced !== undefined ? instanced : false;
  29866. this._instanceDivisor = instanced ? 1 : 0;
  29867. }
  29868. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29869. /**
  29870. * Gets or sets the instance divisor when in instanced mode
  29871. */
  29872. get: function () {
  29873. return this._instanceDivisor;
  29874. },
  29875. set: function (value) {
  29876. this._instanceDivisor = value;
  29877. if (value == 0) {
  29878. this._instanced = false;
  29879. }
  29880. else {
  29881. this._instanced = true;
  29882. }
  29883. },
  29884. enumerable: true,
  29885. configurable: true
  29886. });
  29887. VertexBuffer.prototype._rebuild = function () {
  29888. if (!this._buffer) {
  29889. return;
  29890. }
  29891. this._buffer._rebuild();
  29892. };
  29893. /**
  29894. * Returns the kind of the VertexBuffer (string).
  29895. */
  29896. VertexBuffer.prototype.getKind = function () {
  29897. return this._kind;
  29898. };
  29899. // Properties
  29900. /**
  29901. * Boolean : is the VertexBuffer updatable ?
  29902. */
  29903. VertexBuffer.prototype.isUpdatable = function () {
  29904. return this._buffer.isUpdatable();
  29905. };
  29906. /**
  29907. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29908. */
  29909. VertexBuffer.prototype.getData = function () {
  29910. return this._buffer.getData();
  29911. };
  29912. /**
  29913. * Returns the WebGLBuffer associated to the VertexBuffer.
  29914. */
  29915. VertexBuffer.prototype.getBuffer = function () {
  29916. return this._buffer.getBuffer();
  29917. };
  29918. /**
  29919. * Returns the stride as a multiple of the type byte length.
  29920. * DEPRECATED. Use byteStride instead.
  29921. */
  29922. VertexBuffer.prototype.getStrideSize = function () {
  29923. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29924. };
  29925. /**
  29926. * Returns the offset as a multiple of the type byte length.
  29927. * DEPRECATED. Use byteOffset instead.
  29928. */
  29929. VertexBuffer.prototype.getOffset = function () {
  29930. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29931. };
  29932. /**
  29933. * Returns the number of components per vertex attribute (integer).
  29934. */
  29935. VertexBuffer.prototype.getSize = function () {
  29936. return this._size;
  29937. };
  29938. /**
  29939. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29940. */
  29941. VertexBuffer.prototype.getIsInstanced = function () {
  29942. return this._instanced;
  29943. };
  29944. /**
  29945. * Returns the instancing divisor, zero for non-instanced (integer).
  29946. */
  29947. VertexBuffer.prototype.getInstanceDivisor = function () {
  29948. return this._instanceDivisor;
  29949. };
  29950. // Methods
  29951. /**
  29952. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29953. * Returns the created WebGLBuffer.
  29954. */
  29955. VertexBuffer.prototype.create = function (data) {
  29956. return this._buffer.create(data);
  29957. };
  29958. /**
  29959. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29960. * This function will create a new buffer if the current one is not updatable
  29961. * Returns the updated WebGLBuffer.
  29962. */
  29963. VertexBuffer.prototype.update = function (data) {
  29964. return this._buffer.update(data);
  29965. };
  29966. /**
  29967. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29968. * Returns the directly updated WebGLBuffer.
  29969. * @param data the new data
  29970. * @param offset the new offset
  29971. * @param useBytes set to true if the offset is in bytes
  29972. */
  29973. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29974. if (useBytes === void 0) { useBytes = false; }
  29975. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29976. };
  29977. /**
  29978. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29979. */
  29980. VertexBuffer.prototype.dispose = function () {
  29981. if (this._ownsBuffer) {
  29982. this._buffer.dispose();
  29983. }
  29984. };
  29985. /**
  29986. * Enumerates each value of this vertex buffer as numbers.
  29987. * @param count the number of values to enumerate
  29988. * @param callback the callback function called for each value
  29989. */
  29990. VertexBuffer.prototype.forEach = function (count, callback) {
  29991. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29992. };
  29993. Object.defineProperty(VertexBuffer, "PositionKind", {
  29994. get: function () {
  29995. return VertexBuffer._PositionKind;
  29996. },
  29997. enumerable: true,
  29998. configurable: true
  29999. });
  30000. Object.defineProperty(VertexBuffer, "NormalKind", {
  30001. get: function () {
  30002. return VertexBuffer._NormalKind;
  30003. },
  30004. enumerable: true,
  30005. configurable: true
  30006. });
  30007. Object.defineProperty(VertexBuffer, "TangentKind", {
  30008. get: function () {
  30009. return VertexBuffer._TangentKind;
  30010. },
  30011. enumerable: true,
  30012. configurable: true
  30013. });
  30014. Object.defineProperty(VertexBuffer, "UVKind", {
  30015. get: function () {
  30016. return VertexBuffer._UVKind;
  30017. },
  30018. enumerable: true,
  30019. configurable: true
  30020. });
  30021. Object.defineProperty(VertexBuffer, "UV2Kind", {
  30022. get: function () {
  30023. return VertexBuffer._UV2Kind;
  30024. },
  30025. enumerable: true,
  30026. configurable: true
  30027. });
  30028. Object.defineProperty(VertexBuffer, "UV3Kind", {
  30029. get: function () {
  30030. return VertexBuffer._UV3Kind;
  30031. },
  30032. enumerable: true,
  30033. configurable: true
  30034. });
  30035. Object.defineProperty(VertexBuffer, "UV4Kind", {
  30036. get: function () {
  30037. return VertexBuffer._UV4Kind;
  30038. },
  30039. enumerable: true,
  30040. configurable: true
  30041. });
  30042. Object.defineProperty(VertexBuffer, "UV5Kind", {
  30043. get: function () {
  30044. return VertexBuffer._UV5Kind;
  30045. },
  30046. enumerable: true,
  30047. configurable: true
  30048. });
  30049. Object.defineProperty(VertexBuffer, "UV6Kind", {
  30050. get: function () {
  30051. return VertexBuffer._UV6Kind;
  30052. },
  30053. enumerable: true,
  30054. configurable: true
  30055. });
  30056. Object.defineProperty(VertexBuffer, "ColorKind", {
  30057. get: function () {
  30058. return VertexBuffer._ColorKind;
  30059. },
  30060. enumerable: true,
  30061. configurable: true
  30062. });
  30063. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  30064. get: function () {
  30065. return VertexBuffer._MatricesIndicesKind;
  30066. },
  30067. enumerable: true,
  30068. configurable: true
  30069. });
  30070. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  30071. get: function () {
  30072. return VertexBuffer._MatricesWeightsKind;
  30073. },
  30074. enumerable: true,
  30075. configurable: true
  30076. });
  30077. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  30078. get: function () {
  30079. return VertexBuffer._MatricesIndicesExtraKind;
  30080. },
  30081. enumerable: true,
  30082. configurable: true
  30083. });
  30084. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  30085. get: function () {
  30086. return VertexBuffer._MatricesWeightsExtraKind;
  30087. },
  30088. enumerable: true,
  30089. configurable: true
  30090. });
  30091. /**
  30092. * Deduces the stride given a kind.
  30093. * @param kind The kind string to deduce
  30094. * @returns The deduced stride
  30095. */
  30096. VertexBuffer.DeduceStride = function (kind) {
  30097. switch (kind) {
  30098. case VertexBuffer.UVKind:
  30099. case VertexBuffer.UV2Kind:
  30100. case VertexBuffer.UV3Kind:
  30101. case VertexBuffer.UV4Kind:
  30102. case VertexBuffer.UV5Kind:
  30103. case VertexBuffer.UV6Kind:
  30104. return 2;
  30105. case VertexBuffer.NormalKind:
  30106. case VertexBuffer.PositionKind:
  30107. return 3;
  30108. case VertexBuffer.ColorKind:
  30109. case VertexBuffer.MatricesIndicesKind:
  30110. case VertexBuffer.MatricesIndicesExtraKind:
  30111. case VertexBuffer.MatricesWeightsKind:
  30112. case VertexBuffer.MatricesWeightsExtraKind:
  30113. case VertexBuffer.TangentKind:
  30114. return 4;
  30115. default:
  30116. throw new Error("Invalid kind '" + kind + "'");
  30117. }
  30118. };
  30119. /**
  30120. * Gets the byte length of the given type.
  30121. * @param type the type
  30122. * @returns the number of bytes
  30123. */
  30124. VertexBuffer.GetTypeByteLength = function (type) {
  30125. switch (type) {
  30126. case VertexBuffer.BYTE:
  30127. case VertexBuffer.UNSIGNED_BYTE:
  30128. return 1;
  30129. case VertexBuffer.SHORT:
  30130. case VertexBuffer.UNSIGNED_SHORT:
  30131. return 2;
  30132. case VertexBuffer.INT:
  30133. case VertexBuffer.FLOAT:
  30134. return 4;
  30135. default:
  30136. throw new Error("Invalid type '" + type + "'");
  30137. }
  30138. };
  30139. /**
  30140. * Enumerates each value of the given parameters as numbers.
  30141. * @param data the data to enumerate
  30142. * @param byteOffset the byte offset of the data
  30143. * @param byteStride the byte stride of the data
  30144. * @param componentCount the number of components per element
  30145. * @param componentType the type of the component
  30146. * @param count the total number of components
  30147. * @param normalized whether the data is normalized
  30148. * @param callback the callback function called for each value
  30149. */
  30150. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30151. if (data instanceof Array) {
  30152. var offset = byteOffset / 4;
  30153. var stride = byteStride / 4;
  30154. for (var index = 0; index < count; index += componentCount) {
  30155. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30156. callback(data[offset + componentIndex], index + componentIndex);
  30157. }
  30158. offset += stride;
  30159. }
  30160. }
  30161. else {
  30162. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30163. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30164. for (var index = 0; index < count; index += componentCount) {
  30165. var componentByteOffset = byteOffset;
  30166. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30167. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30168. callback(value, index + componentIndex);
  30169. componentByteOffset += componentByteLength;
  30170. }
  30171. byteOffset += byteStride;
  30172. }
  30173. }
  30174. };
  30175. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30176. switch (type) {
  30177. case VertexBuffer.BYTE: {
  30178. var value = dataView.getInt8(byteOffset);
  30179. if (normalized) {
  30180. value = Math.max(value / 127, -1);
  30181. }
  30182. return value;
  30183. }
  30184. case VertexBuffer.UNSIGNED_BYTE: {
  30185. var value = dataView.getUint8(byteOffset);
  30186. if (normalized) {
  30187. value = value / 255;
  30188. }
  30189. return value;
  30190. }
  30191. case VertexBuffer.SHORT: {
  30192. var value = dataView.getInt16(byteOffset, true);
  30193. if (normalized) {
  30194. value = Math.max(value / 16383, -1);
  30195. }
  30196. return value;
  30197. }
  30198. case VertexBuffer.UNSIGNED_SHORT: {
  30199. var value = dataView.getUint16(byteOffset, true);
  30200. if (normalized) {
  30201. value = value / 65535;
  30202. }
  30203. return value;
  30204. }
  30205. case VertexBuffer.FLOAT: {
  30206. return dataView.getFloat32(byteOffset, true);
  30207. }
  30208. default: {
  30209. throw new Error("Invalid component type " + type);
  30210. }
  30211. }
  30212. };
  30213. /**
  30214. * The byte type.
  30215. */
  30216. VertexBuffer.BYTE = 5120;
  30217. /**
  30218. * The unsigned byte type.
  30219. */
  30220. VertexBuffer.UNSIGNED_BYTE = 5121;
  30221. /**
  30222. * The short type.
  30223. */
  30224. VertexBuffer.SHORT = 5122;
  30225. /**
  30226. * The unsigned short type.
  30227. */
  30228. VertexBuffer.UNSIGNED_SHORT = 5123;
  30229. /**
  30230. * The integer type.
  30231. */
  30232. VertexBuffer.INT = 5124;
  30233. /**
  30234. * The unsigned integer type.
  30235. */
  30236. VertexBuffer.UNSIGNED_INT = 5125;
  30237. /**
  30238. * The float type.
  30239. */
  30240. VertexBuffer.FLOAT = 5126;
  30241. // Enums
  30242. VertexBuffer._PositionKind = "position";
  30243. VertexBuffer._NormalKind = "normal";
  30244. VertexBuffer._TangentKind = "tangent";
  30245. VertexBuffer._UVKind = "uv";
  30246. VertexBuffer._UV2Kind = "uv2";
  30247. VertexBuffer._UV3Kind = "uv3";
  30248. VertexBuffer._UV4Kind = "uv4";
  30249. VertexBuffer._UV5Kind = "uv5";
  30250. VertexBuffer._UV6Kind = "uv6";
  30251. VertexBuffer._ColorKind = "color";
  30252. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30253. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30254. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30255. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30256. return VertexBuffer;
  30257. }());
  30258. BABYLON.VertexBuffer = VertexBuffer;
  30259. })(BABYLON || (BABYLON = {}));
  30260. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30261. var BABYLON;
  30262. (function (BABYLON) {
  30263. /**
  30264. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30265. */
  30266. var DummyInternalTextureTracker = /** @class */ (function () {
  30267. function DummyInternalTextureTracker() {
  30268. /**
  30269. * Gets or set the previous tracker in the list
  30270. */
  30271. this.previous = null;
  30272. /**
  30273. * Gets or set the next tracker in the list
  30274. */
  30275. this.next = null;
  30276. }
  30277. return DummyInternalTextureTracker;
  30278. }());
  30279. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30280. })(BABYLON || (BABYLON = {}));
  30281. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30282. var BABYLON;
  30283. (function (BABYLON) {
  30284. /**
  30285. * Class used to store data associated with WebGL texture data for the engine
  30286. * This class should not be used directly
  30287. */
  30288. var InternalTexture = /** @class */ (function () {
  30289. /**
  30290. * Creates a new InternalTexture
  30291. * @param engine defines the engine to use
  30292. * @param dataSource defines the type of data that will be used
  30293. */
  30294. function InternalTexture(engine, dataSource) {
  30295. /**
  30296. * Observable called when the texture is loaded
  30297. */
  30298. this.onLoadedObservable = new BABYLON.Observable();
  30299. /**
  30300. * Gets or set the previous tracker in the list
  30301. */
  30302. this.previous = null;
  30303. /**
  30304. * Gets or set the next tracker in the list
  30305. */
  30306. this.next = null;
  30307. // Private
  30308. /** @hidden */
  30309. this._initialSlot = -1;
  30310. /** @hidden */
  30311. this._designatedSlot = -1;
  30312. /** @hidden */
  30313. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30314. /** @hidden */
  30315. this._comparisonFunction = 0;
  30316. /** @hidden */
  30317. this._lodGenerationScale = 0;
  30318. /** @hidden */
  30319. this._lodGenerationOffset = 0;
  30320. /** @hidden */
  30321. this._isRGBD = false;
  30322. /** @hidden */
  30323. this._references = 1;
  30324. this._engine = engine;
  30325. this._dataSource = dataSource;
  30326. this._webGLTexture = engine._createTexture();
  30327. }
  30328. /**
  30329. * Gets the Engine the texture belongs to.
  30330. * @returns The babylon engine
  30331. */
  30332. InternalTexture.prototype.getEngine = function () {
  30333. return this._engine;
  30334. };
  30335. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30336. /**
  30337. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30338. */
  30339. get: function () {
  30340. return this._dataSource;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. /**
  30346. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30347. */
  30348. InternalTexture.prototype.incrementReferences = function () {
  30349. this._references++;
  30350. };
  30351. /**
  30352. * Change the size of the texture (not the size of the content)
  30353. * @param width defines the new width
  30354. * @param height defines the new height
  30355. * @param depth defines the new depth (1 by default)
  30356. */
  30357. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30358. if (depth === void 0) { depth = 1; }
  30359. this.width = width;
  30360. this.height = height;
  30361. this.depth = depth;
  30362. this.baseWidth = width;
  30363. this.baseHeight = height;
  30364. this.baseDepth = depth;
  30365. this._size = width * height * depth;
  30366. };
  30367. /** @hidden */
  30368. InternalTexture.prototype._rebuild = function () {
  30369. var _this = this;
  30370. var proxy;
  30371. this.isReady = false;
  30372. this._cachedCoordinatesMode = null;
  30373. this._cachedWrapU = null;
  30374. this._cachedWrapV = null;
  30375. this._cachedAnisotropicFilteringLevel = null;
  30376. switch (this._dataSource) {
  30377. case InternalTexture.DATASOURCE_TEMP:
  30378. return;
  30379. case InternalTexture.DATASOURCE_URL:
  30380. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30381. _this.isReady = true;
  30382. }, null, this._buffer, undefined, this.format);
  30383. proxy._swapAndDie(this);
  30384. return;
  30385. case InternalTexture.DATASOURCE_RAW:
  30386. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30387. proxy._swapAndDie(this);
  30388. this.isReady = true;
  30389. return;
  30390. case InternalTexture.DATASOURCE_RAW3D:
  30391. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30392. proxy._swapAndDie(this);
  30393. this.isReady = true;
  30394. return;
  30395. case InternalTexture.DATASOURCE_DYNAMIC:
  30396. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30397. proxy._swapAndDie(this);
  30398. // The engine will make sure to update content so no need to flag it as isReady = true
  30399. return;
  30400. case InternalTexture.DATASOURCE_RENDERTARGET:
  30401. var options = new BABYLON.RenderTargetCreationOptions();
  30402. options.generateDepthBuffer = this._generateDepthBuffer;
  30403. options.generateMipMaps = this.generateMipMaps;
  30404. options.generateStencilBuffer = this._generateStencilBuffer;
  30405. options.samplingMode = this.samplingMode;
  30406. options.type = this.type;
  30407. if (this.isCube) {
  30408. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30409. }
  30410. else {
  30411. var size = {
  30412. width: this.width,
  30413. height: this.height
  30414. };
  30415. proxy = this._engine.createRenderTargetTexture(size, options);
  30416. }
  30417. proxy._swapAndDie(this);
  30418. this.isReady = true;
  30419. return;
  30420. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30421. var depthTextureOptions = {
  30422. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30423. comparisonFunction: this._comparisonFunction,
  30424. generateStencil: this._generateStencilBuffer,
  30425. isCube: this.isCube
  30426. };
  30427. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30428. proxy._swapAndDie(this);
  30429. this.isReady = true;
  30430. return;
  30431. case InternalTexture.DATASOURCE_CUBE:
  30432. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30433. _this.isReady = true;
  30434. }, null, this.format, this._extension);
  30435. proxy._swapAndDie(this);
  30436. return;
  30437. case InternalTexture.DATASOURCE_CUBERAW:
  30438. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30439. proxy._swapAndDie(this);
  30440. this.isReady = true;
  30441. return;
  30442. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30443. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30444. if (proxy) {
  30445. proxy._swapAndDie(_this);
  30446. }
  30447. _this.isReady = true;
  30448. }, null, this.format, this._extension);
  30449. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30450. return;
  30451. }
  30452. };
  30453. InternalTexture.prototype._swapAndDie = function (target) {
  30454. target._webGLTexture = this._webGLTexture;
  30455. if (this._framebuffer) {
  30456. target._framebuffer = this._framebuffer;
  30457. }
  30458. if (this._depthStencilBuffer) {
  30459. target._depthStencilBuffer = this._depthStencilBuffer;
  30460. }
  30461. if (this._lodTextureHigh) {
  30462. if (target._lodTextureHigh) {
  30463. target._lodTextureHigh.dispose();
  30464. }
  30465. target._lodTextureHigh = this._lodTextureHigh;
  30466. }
  30467. if (this._lodTextureMid) {
  30468. if (target._lodTextureMid) {
  30469. target._lodTextureMid.dispose();
  30470. }
  30471. target._lodTextureMid = this._lodTextureMid;
  30472. }
  30473. if (this._lodTextureLow) {
  30474. if (target._lodTextureLow) {
  30475. target._lodTextureLow.dispose();
  30476. }
  30477. target._lodTextureLow = this._lodTextureLow;
  30478. }
  30479. var cache = this._engine.getLoadedTexturesCache();
  30480. var index = cache.indexOf(this);
  30481. if (index !== -1) {
  30482. cache.splice(index, 1);
  30483. }
  30484. };
  30485. /**
  30486. * Dispose the current allocated resources
  30487. */
  30488. InternalTexture.prototype.dispose = function () {
  30489. if (!this._webGLTexture) {
  30490. return;
  30491. }
  30492. this._references--;
  30493. if (this._references === 0) {
  30494. this._engine._releaseTexture(this);
  30495. this._webGLTexture = null;
  30496. this.previous = null;
  30497. this.next = null;
  30498. }
  30499. };
  30500. /**
  30501. * The source of the texture data is unknown
  30502. */
  30503. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30504. /**
  30505. * Texture data comes from an URL
  30506. */
  30507. InternalTexture.DATASOURCE_URL = 1;
  30508. /**
  30509. * Texture data is only used for temporary storage
  30510. */
  30511. InternalTexture.DATASOURCE_TEMP = 2;
  30512. /**
  30513. * Texture data comes from raw data (ArrayBuffer)
  30514. */
  30515. InternalTexture.DATASOURCE_RAW = 3;
  30516. /**
  30517. * Texture content is dynamic (video or dynamic texture)
  30518. */
  30519. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30520. /**
  30521. * Texture content is generated by rendering to it
  30522. */
  30523. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30524. /**
  30525. * Texture content is part of a multi render target process
  30526. */
  30527. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30528. /**
  30529. * Texture data comes from a cube data file
  30530. */
  30531. InternalTexture.DATASOURCE_CUBE = 7;
  30532. /**
  30533. * Texture data comes from a raw cube data
  30534. */
  30535. InternalTexture.DATASOURCE_CUBERAW = 8;
  30536. /**
  30537. * Texture data come from a prefiltered cube data file
  30538. */
  30539. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30540. /**
  30541. * Texture content is raw 3D data
  30542. */
  30543. InternalTexture.DATASOURCE_RAW3D = 10;
  30544. /**
  30545. * Texture content is a depth texture
  30546. */
  30547. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30548. return InternalTexture;
  30549. }());
  30550. BABYLON.InternalTexture = InternalTexture;
  30551. })(BABYLON || (BABYLON = {}));
  30552. //# sourceMappingURL=babylon.internalTexture.js.map
  30553. var BABYLON;
  30554. (function (BABYLON) {
  30555. var BaseTexture = /** @class */ (function () {
  30556. function BaseTexture(scene) {
  30557. this._hasAlpha = false;
  30558. this.getAlphaFromRGB = false;
  30559. this.level = 1;
  30560. this.coordinatesIndex = 0;
  30561. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30562. /**
  30563. * | Value | Type | Description |
  30564. * | ----- | ------------------ | ----------- |
  30565. * | 0 | CLAMP_ADDRESSMODE | |
  30566. * | 1 | WRAP_ADDRESSMODE | |
  30567. * | 2 | MIRROR_ADDRESSMODE | |
  30568. */
  30569. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30570. /**
  30571. * | Value | Type | Description |
  30572. * | ----- | ------------------ | ----------- |
  30573. * | 0 | CLAMP_ADDRESSMODE | |
  30574. * | 1 | WRAP_ADDRESSMODE | |
  30575. * | 2 | MIRROR_ADDRESSMODE | |
  30576. */
  30577. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30578. /**
  30579. * | Value | Type | Description |
  30580. * | ----- | ------------------ | ----------- |
  30581. * | 0 | CLAMP_ADDRESSMODE | |
  30582. * | 1 | WRAP_ADDRESSMODE | |
  30583. * | 2 | MIRROR_ADDRESSMODE | |
  30584. */
  30585. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30586. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30587. this.isCube = false;
  30588. this.is3D = false;
  30589. this.gammaSpace = true;
  30590. this.invertZ = false;
  30591. this.lodLevelInAlpha = false;
  30592. this.isRenderTarget = false;
  30593. this.animations = new Array();
  30594. /**
  30595. * An event triggered when the texture is disposed.
  30596. */
  30597. this.onDisposeObservable = new BABYLON.Observable();
  30598. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30599. this._cachedSize = BABYLON.Size.Zero();
  30600. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30601. if (this._scene) {
  30602. this._scene.textures.push(this);
  30603. }
  30604. this._uid = null;
  30605. }
  30606. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30607. get: function () {
  30608. return this._hasAlpha;
  30609. },
  30610. set: function (value) {
  30611. if (this._hasAlpha === value) {
  30612. return;
  30613. }
  30614. this._hasAlpha = value;
  30615. if (this._scene) {
  30616. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30617. }
  30618. },
  30619. enumerable: true,
  30620. configurable: true
  30621. });
  30622. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30623. get: function () {
  30624. return this._coordinatesMode;
  30625. },
  30626. /**
  30627. * How a texture is mapped.
  30628. *
  30629. * | Value | Type | Description |
  30630. * | ----- | ----------------------------------- | ----------- |
  30631. * | 0 | EXPLICIT_MODE | |
  30632. * | 1 | SPHERICAL_MODE | |
  30633. * | 2 | PLANAR_MODE | |
  30634. * | 3 | CUBIC_MODE | |
  30635. * | 4 | PROJECTION_MODE | |
  30636. * | 5 | SKYBOX_MODE | |
  30637. * | 6 | INVCUBIC_MODE | |
  30638. * | 7 | EQUIRECTANGULAR_MODE | |
  30639. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30640. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30641. */
  30642. set: function (value) {
  30643. if (this._coordinatesMode === value) {
  30644. return;
  30645. }
  30646. this._coordinatesMode = value;
  30647. if (this._scene) {
  30648. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30649. }
  30650. },
  30651. enumerable: true,
  30652. configurable: true
  30653. });
  30654. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30655. /**
  30656. * Gets whether or not the texture contains RGBD data.
  30657. */
  30658. get: function () {
  30659. return this._texture != null && this._texture._isRGBD;
  30660. },
  30661. enumerable: true,
  30662. configurable: true
  30663. });
  30664. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30665. get: function () {
  30666. if (this._texture)
  30667. return this._texture._lodGenerationOffset;
  30668. return 0.0;
  30669. },
  30670. set: function (value) {
  30671. if (this._texture)
  30672. this._texture._lodGenerationOffset = value;
  30673. },
  30674. enumerable: true,
  30675. configurable: true
  30676. });
  30677. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30678. get: function () {
  30679. if (this._texture)
  30680. return this._texture._lodGenerationScale;
  30681. return 0.0;
  30682. },
  30683. set: function (value) {
  30684. if (this._texture)
  30685. this._texture._lodGenerationScale = value;
  30686. },
  30687. enumerable: true,
  30688. configurable: true
  30689. });
  30690. Object.defineProperty(BaseTexture.prototype, "uid", {
  30691. get: function () {
  30692. if (!this._uid) {
  30693. this._uid = BABYLON.Tools.RandomId();
  30694. }
  30695. return this._uid;
  30696. },
  30697. enumerable: true,
  30698. configurable: true
  30699. });
  30700. BaseTexture.prototype.toString = function () {
  30701. return this.name;
  30702. };
  30703. BaseTexture.prototype.getClassName = function () {
  30704. return "BaseTexture";
  30705. };
  30706. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30707. set: function (callback) {
  30708. if (this._onDisposeObserver) {
  30709. this.onDisposeObservable.remove(this._onDisposeObserver);
  30710. }
  30711. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30712. },
  30713. enumerable: true,
  30714. configurable: true
  30715. });
  30716. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30717. get: function () {
  30718. return true;
  30719. },
  30720. enumerable: true,
  30721. configurable: true
  30722. });
  30723. BaseTexture.prototype.getScene = function () {
  30724. return this._scene;
  30725. };
  30726. BaseTexture.prototype.getTextureMatrix = function () {
  30727. return BABYLON.Matrix.IdentityReadOnly;
  30728. };
  30729. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30730. return BABYLON.Matrix.IdentityReadOnly;
  30731. };
  30732. BaseTexture.prototype.getInternalTexture = function () {
  30733. return this._texture;
  30734. };
  30735. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30736. return !this.isBlocking || this.isReady();
  30737. };
  30738. BaseTexture.prototype.isReady = function () {
  30739. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30740. this.delayLoad();
  30741. return false;
  30742. }
  30743. if (this._texture) {
  30744. return this._texture.isReady;
  30745. }
  30746. return false;
  30747. };
  30748. BaseTexture.prototype.getSize = function () {
  30749. if (this._texture) {
  30750. if (this._texture.width) {
  30751. this._cachedSize.width = this._texture.width;
  30752. this._cachedSize.height = this._texture.height;
  30753. return this._cachedSize;
  30754. }
  30755. if (this._texture._size) {
  30756. this._cachedSize.width = this._texture._size;
  30757. this._cachedSize.height = this._texture._size;
  30758. return this._cachedSize;
  30759. }
  30760. }
  30761. return this._cachedSize;
  30762. };
  30763. BaseTexture.prototype.getBaseSize = function () {
  30764. if (!this.isReady() || !this._texture)
  30765. return BABYLON.Size.Zero();
  30766. if (this._texture._size) {
  30767. return new BABYLON.Size(this._texture._size, this._texture._size);
  30768. }
  30769. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30770. };
  30771. BaseTexture.prototype.scale = function (ratio) {
  30772. };
  30773. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30774. get: function () {
  30775. return false;
  30776. },
  30777. enumerable: true,
  30778. configurable: true
  30779. });
  30780. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30781. if (!this._scene) {
  30782. return null;
  30783. }
  30784. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30785. for (var index = 0; index < texturesCache.length; index++) {
  30786. var texturesCacheEntry = texturesCache[index];
  30787. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30788. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30789. texturesCacheEntry.incrementReferences();
  30790. return texturesCacheEntry;
  30791. }
  30792. }
  30793. }
  30794. return null;
  30795. };
  30796. BaseTexture.prototype._rebuild = function () {
  30797. };
  30798. BaseTexture.prototype.delayLoad = function () {
  30799. };
  30800. BaseTexture.prototype.clone = function () {
  30801. return null;
  30802. };
  30803. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30804. get: function () {
  30805. if (!this._texture) {
  30806. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30807. }
  30808. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30809. },
  30810. enumerable: true,
  30811. configurable: true
  30812. });
  30813. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30814. get: function () {
  30815. if (!this._texture) {
  30816. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30817. }
  30818. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30819. },
  30820. enumerable: true,
  30821. configurable: true
  30822. });
  30823. /**
  30824. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30825. * This will returns an RGBA array buffer containing either in values (0-255) or
  30826. * float values (0-1) depending of the underlying buffer type.
  30827. * @param faceIndex The face of the texture to read (in case of cube texture)
  30828. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30829. * @returns The Array buffer containing the pixels data.
  30830. */
  30831. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30832. if (faceIndex === void 0) { faceIndex = 0; }
  30833. if (level === void 0) { level = 0; }
  30834. if (!this._texture) {
  30835. return null;
  30836. }
  30837. var size = this.getSize();
  30838. var width = size.width;
  30839. var height = size.height;
  30840. var scene = this.getScene();
  30841. if (!scene) {
  30842. return null;
  30843. }
  30844. var engine = scene.getEngine();
  30845. if (level != 0) {
  30846. width = width / Math.pow(2, level);
  30847. height = height / Math.pow(2, level);
  30848. width = Math.round(width);
  30849. height = Math.round(height);
  30850. }
  30851. if (this._texture.isCube) {
  30852. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30853. }
  30854. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30855. };
  30856. BaseTexture.prototype.releaseInternalTexture = function () {
  30857. if (this._texture) {
  30858. this._texture.dispose();
  30859. this._texture = null;
  30860. }
  30861. };
  30862. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30863. get: function () {
  30864. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30865. return null;
  30866. }
  30867. if (!this._texture._sphericalPolynomial) {
  30868. this._texture._sphericalPolynomial =
  30869. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30870. }
  30871. return this._texture._sphericalPolynomial;
  30872. },
  30873. set: function (value) {
  30874. if (this._texture) {
  30875. this._texture._sphericalPolynomial = value;
  30876. }
  30877. },
  30878. enumerable: true,
  30879. configurable: true
  30880. });
  30881. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30882. get: function () {
  30883. if (this._texture) {
  30884. return this._texture._lodTextureHigh;
  30885. }
  30886. return null;
  30887. },
  30888. enumerable: true,
  30889. configurable: true
  30890. });
  30891. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30892. get: function () {
  30893. if (this._texture) {
  30894. return this._texture._lodTextureMid;
  30895. }
  30896. return null;
  30897. },
  30898. enumerable: true,
  30899. configurable: true
  30900. });
  30901. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30902. get: function () {
  30903. if (this._texture) {
  30904. return this._texture._lodTextureLow;
  30905. }
  30906. return null;
  30907. },
  30908. enumerable: true,
  30909. configurable: true
  30910. });
  30911. BaseTexture.prototype.dispose = function () {
  30912. if (!this._scene) {
  30913. return;
  30914. }
  30915. // Animations
  30916. this._scene.stopAnimation(this);
  30917. // Remove from scene
  30918. this._scene._removePendingData(this);
  30919. var index = this._scene.textures.indexOf(this);
  30920. if (index >= 0) {
  30921. this._scene.textures.splice(index, 1);
  30922. }
  30923. if (this._texture === undefined) {
  30924. return;
  30925. }
  30926. // Release
  30927. this.releaseInternalTexture();
  30928. // Callback
  30929. this.onDisposeObservable.notifyObservers(this);
  30930. this.onDisposeObservable.clear();
  30931. };
  30932. BaseTexture.prototype.serialize = function () {
  30933. if (!this.name) {
  30934. return null;
  30935. }
  30936. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30937. // Animations
  30938. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30939. return serializationObject;
  30940. };
  30941. BaseTexture.WhenAllReady = function (textures, callback) {
  30942. var numRemaining = textures.length;
  30943. if (numRemaining === 0) {
  30944. callback();
  30945. return;
  30946. }
  30947. var _loop_1 = function () {
  30948. texture = textures[i];
  30949. if (texture.isReady()) {
  30950. if (--numRemaining === 0) {
  30951. callback();
  30952. }
  30953. }
  30954. else {
  30955. onLoadObservable = texture.onLoadObservable;
  30956. var onLoadCallback_1 = function () {
  30957. onLoadObservable.removeCallback(onLoadCallback_1);
  30958. if (--numRemaining === 0) {
  30959. callback();
  30960. }
  30961. };
  30962. onLoadObservable.add(onLoadCallback_1);
  30963. }
  30964. };
  30965. var texture, onLoadObservable;
  30966. for (var i = 0; i < textures.length; i++) {
  30967. _loop_1();
  30968. }
  30969. };
  30970. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30971. __decorate([
  30972. BABYLON.serialize()
  30973. ], BaseTexture.prototype, "name", void 0);
  30974. __decorate([
  30975. BABYLON.serialize("hasAlpha")
  30976. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30977. __decorate([
  30978. BABYLON.serialize()
  30979. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30980. __decorate([
  30981. BABYLON.serialize()
  30982. ], BaseTexture.prototype, "level", void 0);
  30983. __decorate([
  30984. BABYLON.serialize()
  30985. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30986. __decorate([
  30987. BABYLON.serialize("coordinatesMode")
  30988. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30989. __decorate([
  30990. BABYLON.serialize()
  30991. ], BaseTexture.prototype, "wrapU", void 0);
  30992. __decorate([
  30993. BABYLON.serialize()
  30994. ], BaseTexture.prototype, "wrapV", void 0);
  30995. __decorate([
  30996. BABYLON.serialize()
  30997. ], BaseTexture.prototype, "wrapR", void 0);
  30998. __decorate([
  30999. BABYLON.serialize()
  31000. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31001. __decorate([
  31002. BABYLON.serialize()
  31003. ], BaseTexture.prototype, "isCube", void 0);
  31004. __decorate([
  31005. BABYLON.serialize()
  31006. ], BaseTexture.prototype, "is3D", void 0);
  31007. __decorate([
  31008. BABYLON.serialize()
  31009. ], BaseTexture.prototype, "gammaSpace", void 0);
  31010. __decorate([
  31011. BABYLON.serialize()
  31012. ], BaseTexture.prototype, "invertZ", void 0);
  31013. __decorate([
  31014. BABYLON.serialize()
  31015. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31016. __decorate([
  31017. BABYLON.serialize()
  31018. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31019. __decorate([
  31020. BABYLON.serialize()
  31021. ], BaseTexture.prototype, "lodGenerationScale", null);
  31022. __decorate([
  31023. BABYLON.serialize()
  31024. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31025. return BaseTexture;
  31026. }());
  31027. BABYLON.BaseTexture = BaseTexture;
  31028. })(BABYLON || (BABYLON = {}));
  31029. //# sourceMappingURL=babylon.baseTexture.js.map
  31030. var BABYLON;
  31031. (function (BABYLON) {
  31032. var Texture = /** @class */ (function (_super) {
  31033. __extends(Texture, _super);
  31034. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31035. if (noMipmap === void 0) { noMipmap = false; }
  31036. if (invertY === void 0) { invertY = true; }
  31037. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31038. if (onLoad === void 0) { onLoad = null; }
  31039. if (onError === void 0) { onError = null; }
  31040. if (buffer === void 0) { buffer = null; }
  31041. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31042. var _this = _super.call(this, scene) || this;
  31043. _this.uOffset = 0;
  31044. _this.vOffset = 0;
  31045. _this.uScale = 1.0;
  31046. _this.vScale = 1.0;
  31047. _this.uAng = 0;
  31048. _this.vAng = 0;
  31049. _this.wAng = 0;
  31050. /**
  31051. * Defines the center of rotation (U)
  31052. */
  31053. _this.uRotationCenter = 0.5;
  31054. /**
  31055. * Defines the center of rotation (V)
  31056. */
  31057. _this.vRotationCenter = 0.5;
  31058. /**
  31059. * Defines the center of rotation (W)
  31060. */
  31061. _this.wRotationCenter = 0.5;
  31062. _this._isBlocking = true;
  31063. _this.name = url || "";
  31064. _this.url = url;
  31065. _this._noMipmap = noMipmap;
  31066. _this._invertY = invertY;
  31067. _this._samplingMode = samplingMode;
  31068. _this._buffer = buffer;
  31069. _this._deleteBuffer = deleteBuffer;
  31070. if (format) {
  31071. _this._format = format;
  31072. }
  31073. scene = _this.getScene();
  31074. if (!scene) {
  31075. return _this;
  31076. }
  31077. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31078. var load = function () {
  31079. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31080. _this.onLoadObservable.notifyObservers(_this);
  31081. }
  31082. if (onLoad) {
  31083. onLoad();
  31084. }
  31085. if (!_this.isBlocking && scene) {
  31086. scene.resetCachedMaterial();
  31087. }
  31088. };
  31089. if (!_this.url) {
  31090. _this._delayedOnLoad = load;
  31091. _this._delayedOnError = onError;
  31092. return _this;
  31093. }
  31094. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31095. if (!_this._texture) {
  31096. if (!scene.useDelayedTextureLoading) {
  31097. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31098. if (deleteBuffer) {
  31099. delete _this._buffer;
  31100. }
  31101. }
  31102. else {
  31103. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31104. _this._delayedOnLoad = load;
  31105. _this._delayedOnError = onError;
  31106. }
  31107. }
  31108. else {
  31109. if (_this._texture.isReady) {
  31110. BABYLON.Tools.SetImmediate(function () { return load(); });
  31111. }
  31112. else {
  31113. _this._texture.onLoadedObservable.add(load);
  31114. }
  31115. }
  31116. return _this;
  31117. }
  31118. Object.defineProperty(Texture.prototype, "noMipmap", {
  31119. get: function () {
  31120. return this._noMipmap;
  31121. },
  31122. enumerable: true,
  31123. configurable: true
  31124. });
  31125. Object.defineProperty(Texture.prototype, "isBlocking", {
  31126. get: function () {
  31127. return this._isBlocking;
  31128. },
  31129. set: function (value) {
  31130. this._isBlocking = value;
  31131. },
  31132. enumerable: true,
  31133. configurable: true
  31134. });
  31135. Object.defineProperty(Texture.prototype, "samplingMode", {
  31136. get: function () {
  31137. return this._samplingMode;
  31138. },
  31139. enumerable: true,
  31140. configurable: true
  31141. });
  31142. /**
  31143. * Update the url (and optional buffer) of this texture if url was null during construction.
  31144. * @param url the url of the texture
  31145. * @param buffer the buffer of the texture (defaults to null)
  31146. */
  31147. Texture.prototype.updateURL = function (url, buffer) {
  31148. if (buffer === void 0) { buffer = null; }
  31149. if (this.url) {
  31150. throw new Error("URL is already set");
  31151. }
  31152. this.url = url;
  31153. this._buffer = buffer;
  31154. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31155. this.delayLoad();
  31156. };
  31157. Texture.prototype.delayLoad = function () {
  31158. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31159. return;
  31160. }
  31161. var scene = this.getScene();
  31162. if (!scene) {
  31163. return;
  31164. }
  31165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31166. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31167. if (!this._texture) {
  31168. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31169. if (this._deleteBuffer) {
  31170. delete this._buffer;
  31171. }
  31172. }
  31173. else {
  31174. if (this._delayedOnLoad) {
  31175. if (this._texture.isReady) {
  31176. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31177. }
  31178. else {
  31179. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31180. }
  31181. }
  31182. }
  31183. this._delayedOnLoad = null;
  31184. this._delayedOnError = null;
  31185. };
  31186. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31187. if (!this._texture) {
  31188. return;
  31189. }
  31190. var scene = this.getScene();
  31191. if (!scene) {
  31192. return;
  31193. }
  31194. this._samplingMode = samplingMode;
  31195. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31196. };
  31197. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31198. x *= this.uScale;
  31199. y *= this.vScale;
  31200. x -= this.uRotationCenter * this.uScale;
  31201. y -= this.vRotationCenter * this.vScale;
  31202. z -= this.wRotationCenter;
  31203. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31204. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31205. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31206. t.z += this.wRotationCenter;
  31207. };
  31208. Texture.prototype.getTextureMatrix = function () {
  31209. var _this = this;
  31210. if (this.uOffset === this._cachedUOffset &&
  31211. this.vOffset === this._cachedVOffset &&
  31212. this.uScale === this._cachedUScale &&
  31213. this.vScale === this._cachedVScale &&
  31214. this.uAng === this._cachedUAng &&
  31215. this.vAng === this._cachedVAng &&
  31216. this.wAng === this._cachedWAng) {
  31217. return this._cachedTextureMatrix;
  31218. }
  31219. this._cachedUOffset = this.uOffset;
  31220. this._cachedVOffset = this.vOffset;
  31221. this._cachedUScale = this.uScale;
  31222. this._cachedVScale = this.vScale;
  31223. this._cachedUAng = this.uAng;
  31224. this._cachedVAng = this.vAng;
  31225. this._cachedWAng = this.wAng;
  31226. if (!this._cachedTextureMatrix) {
  31227. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31228. this._rowGenerationMatrix = new BABYLON.Matrix();
  31229. this._t0 = BABYLON.Vector3.Zero();
  31230. this._t1 = BABYLON.Vector3.Zero();
  31231. this._t2 = BABYLON.Vector3.Zero();
  31232. }
  31233. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31234. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31235. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31236. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31237. this._t1.subtractInPlace(this._t0);
  31238. this._t2.subtractInPlace(this._t0);
  31239. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31240. this._cachedTextureMatrix.m[0] = this._t1.x;
  31241. this._cachedTextureMatrix.m[1] = this._t1.y;
  31242. this._cachedTextureMatrix.m[2] = this._t1.z;
  31243. this._cachedTextureMatrix.m[4] = this._t2.x;
  31244. this._cachedTextureMatrix.m[5] = this._t2.y;
  31245. this._cachedTextureMatrix.m[6] = this._t2.z;
  31246. this._cachedTextureMatrix.m[8] = this._t0.x;
  31247. this._cachedTextureMatrix.m[9] = this._t0.y;
  31248. this._cachedTextureMatrix.m[10] = this._t0.z;
  31249. var scene = this.getScene();
  31250. if (!scene) {
  31251. return this._cachedTextureMatrix;
  31252. }
  31253. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31254. return mat.hasTexture(_this);
  31255. });
  31256. return this._cachedTextureMatrix;
  31257. };
  31258. Texture.prototype.getReflectionTextureMatrix = function () {
  31259. var _this = this;
  31260. var scene = this.getScene();
  31261. if (!scene) {
  31262. return this._cachedTextureMatrix;
  31263. }
  31264. if (this.uOffset === this._cachedUOffset &&
  31265. this.vOffset === this._cachedVOffset &&
  31266. this.uScale === this._cachedUScale &&
  31267. this.vScale === this._cachedVScale &&
  31268. this.coordinatesMode === this._cachedCoordinatesMode) {
  31269. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31270. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31271. return this._cachedTextureMatrix;
  31272. }
  31273. }
  31274. else {
  31275. return this._cachedTextureMatrix;
  31276. }
  31277. }
  31278. if (!this._cachedTextureMatrix) {
  31279. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31280. }
  31281. if (!this._projectionModeMatrix) {
  31282. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31283. }
  31284. this._cachedUOffset = this.uOffset;
  31285. this._cachedVOffset = this.vOffset;
  31286. this._cachedUScale = this.uScale;
  31287. this._cachedVScale = this.vScale;
  31288. this._cachedCoordinatesMode = this.coordinatesMode;
  31289. switch (this.coordinatesMode) {
  31290. case Texture.PLANAR_MODE:
  31291. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31292. this._cachedTextureMatrix[0] = this.uScale;
  31293. this._cachedTextureMatrix[5] = this.vScale;
  31294. this._cachedTextureMatrix[12] = this.uOffset;
  31295. this._cachedTextureMatrix[13] = this.vOffset;
  31296. break;
  31297. case Texture.PROJECTION_MODE:
  31298. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31299. this._projectionModeMatrix.m[0] = 0.5;
  31300. this._projectionModeMatrix.m[5] = -0.5;
  31301. this._projectionModeMatrix.m[10] = 0.0;
  31302. this._projectionModeMatrix.m[12] = 0.5;
  31303. this._projectionModeMatrix.m[13] = 0.5;
  31304. this._projectionModeMatrix.m[14] = 1.0;
  31305. this._projectionModeMatrix.m[15] = 1.0;
  31306. var projectionMatrix = scene.getProjectionMatrix();
  31307. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31308. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31309. break;
  31310. default:
  31311. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31312. break;
  31313. }
  31314. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31315. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31316. });
  31317. return this._cachedTextureMatrix;
  31318. };
  31319. Texture.prototype.clone = function () {
  31320. var _this = this;
  31321. return BABYLON.SerializationHelper.Clone(function () {
  31322. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31323. }, this);
  31324. };
  31325. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31326. get: function () {
  31327. if (!this._onLoadObservable) {
  31328. this._onLoadObservable = new BABYLON.Observable();
  31329. }
  31330. return this._onLoadObservable;
  31331. },
  31332. enumerable: true,
  31333. configurable: true
  31334. });
  31335. Texture.prototype.serialize = function () {
  31336. var serializationObject = _super.prototype.serialize.call(this);
  31337. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31338. serializationObject.base64String = this._buffer;
  31339. serializationObject.name = serializationObject.name.replace("data:", "");
  31340. }
  31341. serializationObject.invertY = this._invertY;
  31342. serializationObject.samplingMode = this.samplingMode;
  31343. return serializationObject;
  31344. };
  31345. Texture.prototype.getClassName = function () {
  31346. return "Texture";
  31347. };
  31348. Texture.prototype.dispose = function () {
  31349. _super.prototype.dispose.call(this);
  31350. if (this._onLoadObservable) {
  31351. this._onLoadObservable.clear();
  31352. this._onLoadObservable = null;
  31353. }
  31354. this._delayedOnLoad = null;
  31355. this._delayedOnError = null;
  31356. };
  31357. // Statics
  31358. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31359. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31360. if (onLoad === void 0) { onLoad = null; }
  31361. if (onError === void 0) { onError = null; }
  31362. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31363. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31364. };
  31365. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31366. if (parsedTexture.customType) {
  31367. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31368. // Update Sampling Mode
  31369. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31370. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31371. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31372. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31373. }
  31374. }
  31375. return parsedCustomTexture;
  31376. }
  31377. if (parsedTexture.isCube) {
  31378. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31379. }
  31380. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31381. return null;
  31382. }
  31383. var texture = BABYLON.SerializationHelper.Parse(function () {
  31384. var generateMipMaps = true;
  31385. if (parsedTexture.noMipmap) {
  31386. generateMipMaps = false;
  31387. }
  31388. if (parsedTexture.mirrorPlane) {
  31389. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31390. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31391. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31392. return mirrorTexture;
  31393. }
  31394. else if (parsedTexture.isRenderTarget) {
  31395. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31396. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31397. return renderTargetTexture;
  31398. }
  31399. else {
  31400. var texture;
  31401. if (parsedTexture.base64String) {
  31402. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31403. }
  31404. else {
  31405. var url = rootUrl + parsedTexture.name;
  31406. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31407. url = parsedTexture.url;
  31408. }
  31409. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31410. }
  31411. return texture;
  31412. }
  31413. }, parsedTexture, scene);
  31414. // Update Sampling Mode
  31415. if (parsedTexture.samplingMode) {
  31416. var sampling = parsedTexture.samplingMode;
  31417. if (texture._samplingMode !== sampling) {
  31418. texture.updateSamplingMode(sampling);
  31419. }
  31420. }
  31421. // Animations
  31422. if (parsedTexture.animations) {
  31423. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31424. var parsedAnimation = parsedTexture.animations[animationIndex];
  31425. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31426. }
  31427. }
  31428. return texture;
  31429. };
  31430. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31431. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31432. if (noMipmap === void 0) { noMipmap = false; }
  31433. if (invertY === void 0) { invertY = true; }
  31434. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31435. if (onLoad === void 0) { onLoad = null; }
  31436. if (onError === void 0) { onError = null; }
  31437. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31438. if (name.substr(0, 5) !== "data:") {
  31439. name = "data:" + name;
  31440. }
  31441. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31442. };
  31443. // Constants
  31444. Texture.NEAREST_SAMPLINGMODE = 1;
  31445. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31446. Texture.BILINEAR_SAMPLINGMODE = 2;
  31447. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31448. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31449. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31450. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31451. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31452. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31453. Texture.NEAREST_LINEAR = 7;
  31454. Texture.NEAREST_NEAREST = 8;
  31455. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31456. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31457. Texture.LINEAR_LINEAR = 11;
  31458. Texture.LINEAR_NEAREST = 12;
  31459. Texture.EXPLICIT_MODE = 0;
  31460. Texture.SPHERICAL_MODE = 1;
  31461. Texture.PLANAR_MODE = 2;
  31462. Texture.CUBIC_MODE = 3;
  31463. Texture.PROJECTION_MODE = 4;
  31464. Texture.SKYBOX_MODE = 5;
  31465. Texture.INVCUBIC_MODE = 6;
  31466. Texture.EQUIRECTANGULAR_MODE = 7;
  31467. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31468. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31469. Texture.CLAMP_ADDRESSMODE = 0;
  31470. Texture.WRAP_ADDRESSMODE = 1;
  31471. Texture.MIRROR_ADDRESSMODE = 2;
  31472. /**
  31473. * 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
  31474. */
  31475. Texture.UseSerializedUrlIfAny = false;
  31476. __decorate([
  31477. BABYLON.serialize()
  31478. ], Texture.prototype, "url", void 0);
  31479. __decorate([
  31480. BABYLON.serialize()
  31481. ], Texture.prototype, "uOffset", void 0);
  31482. __decorate([
  31483. BABYLON.serialize()
  31484. ], Texture.prototype, "vOffset", void 0);
  31485. __decorate([
  31486. BABYLON.serialize()
  31487. ], Texture.prototype, "uScale", void 0);
  31488. __decorate([
  31489. BABYLON.serialize()
  31490. ], Texture.prototype, "vScale", void 0);
  31491. __decorate([
  31492. BABYLON.serialize()
  31493. ], Texture.prototype, "uAng", void 0);
  31494. __decorate([
  31495. BABYLON.serialize()
  31496. ], Texture.prototype, "vAng", void 0);
  31497. __decorate([
  31498. BABYLON.serialize()
  31499. ], Texture.prototype, "wAng", void 0);
  31500. __decorate([
  31501. BABYLON.serialize()
  31502. ], Texture.prototype, "uRotationCenter", void 0);
  31503. __decorate([
  31504. BABYLON.serialize()
  31505. ], Texture.prototype, "vRotationCenter", void 0);
  31506. __decorate([
  31507. BABYLON.serialize()
  31508. ], Texture.prototype, "wRotationCenter", void 0);
  31509. __decorate([
  31510. BABYLON.serialize()
  31511. ], Texture.prototype, "isBlocking", null);
  31512. return Texture;
  31513. }(BABYLON.BaseTexture));
  31514. BABYLON.Texture = Texture;
  31515. })(BABYLON || (BABYLON = {}));
  31516. //# sourceMappingURL=babylon.texture.js.map
  31517. var BABYLON;
  31518. (function (BABYLON) {
  31519. /**
  31520. * @hidden
  31521. **/
  31522. var _InstancesBatch = /** @class */ (function () {
  31523. function _InstancesBatch() {
  31524. this.mustReturn = false;
  31525. this.visibleInstances = new Array();
  31526. this.renderSelf = new Array();
  31527. }
  31528. return _InstancesBatch;
  31529. }());
  31530. BABYLON._InstancesBatch = _InstancesBatch;
  31531. var Mesh = /** @class */ (function (_super) {
  31532. __extends(Mesh, _super);
  31533. /**
  31534. * @constructor
  31535. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31536. * @param {Scene} scene The scene to add this mesh to.
  31537. * @param {Node} parent The parent of this mesh, if it has one
  31538. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31539. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31540. * When false, achieved by calling a clone(), also passing False.
  31541. * This will make creation of children, recursive.
  31542. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31543. */
  31544. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31545. if (scene === void 0) { scene = null; }
  31546. if (parent === void 0) { parent = null; }
  31547. if (source === void 0) { source = null; }
  31548. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31549. var _this = _super.call(this, name, scene) || this;
  31550. // Events
  31551. /**
  31552. * An event triggered before rendering the mesh
  31553. */
  31554. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31555. /**
  31556. * An event triggered after rendering the mesh
  31557. */
  31558. _this.onAfterRenderObservable = new BABYLON.Observable();
  31559. /**
  31560. * An event triggered before drawing the mesh
  31561. */
  31562. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31563. // Members
  31564. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31565. _this.instances = new Array();
  31566. _this._LODLevels = new Array();
  31567. _this._visibleInstances = {};
  31568. _this._renderIdForInstances = new Array();
  31569. _this._batchCache = new _InstancesBatch();
  31570. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31571. // Use by builder only to know what orientation were the mesh build in.
  31572. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31573. _this.overrideMaterialSideOrientation = null;
  31574. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31575. // Will be used to save a source mesh reference, If any
  31576. _this._source = null;
  31577. scene = _this.getScene();
  31578. if (source) {
  31579. // Geometry
  31580. if (source._geometry) {
  31581. source._geometry.applyToMesh(_this);
  31582. }
  31583. // Deep copy
  31584. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31585. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31586. // Source mesh
  31587. _this._source = source;
  31588. // Metadata
  31589. if (source.metadata && source.metadata.clone) {
  31590. _this.metadata = source.metadata.clone();
  31591. }
  31592. else {
  31593. _this.metadata = source.metadata;
  31594. }
  31595. // Tags
  31596. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31597. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31598. }
  31599. // Parent
  31600. _this.parent = source.parent;
  31601. // Pivot
  31602. _this.setPivotMatrix(source.getPivotMatrix());
  31603. _this.id = name + "." + source.id;
  31604. // Material
  31605. _this.material = source.material;
  31606. var index;
  31607. if (!doNotCloneChildren) {
  31608. // Children
  31609. var directDescendants = source.getDescendants(true);
  31610. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31611. var child = directDescendants[index_1];
  31612. if (child.clone) {
  31613. child.clone(name + "." + child.name, _this);
  31614. }
  31615. }
  31616. }
  31617. // Physics clone
  31618. var physicsEngine = _this.getScene().getPhysicsEngine();
  31619. if (clonePhysicsImpostor && physicsEngine) {
  31620. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31621. if (impostor) {
  31622. _this.physicsImpostor = impostor.clone(_this);
  31623. }
  31624. }
  31625. // Particles
  31626. for (index = 0; index < scene.particleSystems.length; index++) {
  31627. var system = scene.particleSystems[index];
  31628. if (system.emitter === source) {
  31629. system.clone(system.name, _this);
  31630. }
  31631. }
  31632. _this.refreshBoundingInfo();
  31633. _this.computeWorldMatrix(true);
  31634. }
  31635. // Parent
  31636. if (parent !== null) {
  31637. _this.parent = parent;
  31638. }
  31639. return _this;
  31640. }
  31641. Object.defineProperty(Mesh, "FRONTSIDE", {
  31642. /**
  31643. * Mesh side orientation : usually the external or front surface
  31644. */
  31645. get: function () {
  31646. return Mesh._FRONTSIDE;
  31647. },
  31648. enumerable: true,
  31649. configurable: true
  31650. });
  31651. Object.defineProperty(Mesh, "BACKSIDE", {
  31652. /**
  31653. * Mesh side orientation : usually the internal or back surface
  31654. */
  31655. get: function () {
  31656. return Mesh._BACKSIDE;
  31657. },
  31658. enumerable: true,
  31659. configurable: true
  31660. });
  31661. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31662. /**
  31663. * Mesh side orientation : both internal and external or front and back surfaces
  31664. */
  31665. get: function () {
  31666. return Mesh._DOUBLESIDE;
  31667. },
  31668. enumerable: true,
  31669. configurable: true
  31670. });
  31671. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31672. /**
  31673. * Mesh side orientation : by default, `FRONTSIDE`
  31674. */
  31675. get: function () {
  31676. return Mesh._DEFAULTSIDE;
  31677. },
  31678. enumerable: true,
  31679. configurable: true
  31680. });
  31681. Object.defineProperty(Mesh, "NO_CAP", {
  31682. /**
  31683. * Mesh cap setting : no cap
  31684. */
  31685. get: function () {
  31686. return Mesh._NO_CAP;
  31687. },
  31688. enumerable: true,
  31689. configurable: true
  31690. });
  31691. Object.defineProperty(Mesh, "CAP_START", {
  31692. /**
  31693. * Mesh cap setting : one cap at the beginning of the mesh
  31694. */
  31695. get: function () {
  31696. return Mesh._CAP_START;
  31697. },
  31698. enumerable: true,
  31699. configurable: true
  31700. });
  31701. Object.defineProperty(Mesh, "CAP_END", {
  31702. /**
  31703. * Mesh cap setting : one cap at the end of the mesh
  31704. */
  31705. get: function () {
  31706. return Mesh._CAP_END;
  31707. },
  31708. enumerable: true,
  31709. configurable: true
  31710. });
  31711. Object.defineProperty(Mesh, "CAP_ALL", {
  31712. /**
  31713. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31714. */
  31715. get: function () {
  31716. return Mesh._CAP_ALL;
  31717. },
  31718. enumerable: true,
  31719. configurable: true
  31720. });
  31721. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31722. set: function (callback) {
  31723. if (this._onBeforeDrawObserver) {
  31724. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31725. }
  31726. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31727. },
  31728. enumerable: true,
  31729. configurable: true
  31730. });
  31731. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31732. get: function () {
  31733. return this._morphTargetManager;
  31734. },
  31735. set: function (value) {
  31736. if (this._morphTargetManager === value) {
  31737. return;
  31738. }
  31739. this._morphTargetManager = value;
  31740. this._syncGeometryWithMorphTargetManager();
  31741. },
  31742. enumerable: true,
  31743. configurable: true
  31744. });
  31745. Object.defineProperty(Mesh.prototype, "source", {
  31746. get: function () {
  31747. return this._source;
  31748. },
  31749. enumerable: true,
  31750. configurable: true
  31751. });
  31752. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31753. get: function () {
  31754. return this._unIndexed;
  31755. },
  31756. set: function (value) {
  31757. if (this._unIndexed !== value) {
  31758. this._unIndexed = value;
  31759. this._markSubMeshesAsAttributesDirty();
  31760. }
  31761. },
  31762. enumerable: true,
  31763. configurable: true
  31764. });
  31765. // Methods
  31766. /**
  31767. * Returns the string "Mesh".
  31768. */
  31769. Mesh.prototype.getClassName = function () {
  31770. return "Mesh";
  31771. };
  31772. /**
  31773. * Returns a string.
  31774. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31775. */
  31776. Mesh.prototype.toString = function (fullDetails) {
  31777. var ret = _super.prototype.toString.call(this, fullDetails);
  31778. ret += ", n vertices: " + this.getTotalVertices();
  31779. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31780. if (this.animations) {
  31781. for (var i = 0; i < this.animations.length; i++) {
  31782. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31783. }
  31784. }
  31785. if (fullDetails) {
  31786. if (this._geometry) {
  31787. var ib = this.getIndices();
  31788. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31789. if (vb && ib) {
  31790. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31791. }
  31792. }
  31793. else {
  31794. ret += ", flat shading: UNKNOWN";
  31795. }
  31796. }
  31797. return ret;
  31798. };
  31799. Mesh.prototype._unBindEffect = function () {
  31800. _super.prototype._unBindEffect.call(this);
  31801. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31802. var instance = _a[_i];
  31803. instance._unBindEffect();
  31804. }
  31805. };
  31806. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31807. /**
  31808. * True if the mesh has some Levels Of Details (LOD).
  31809. * Returns a boolean.
  31810. */
  31811. get: function () {
  31812. return this._LODLevels.length > 0;
  31813. },
  31814. enumerable: true,
  31815. configurable: true
  31816. });
  31817. /**
  31818. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31819. * @returns an array of {BABYLON.MeshLODLevel}
  31820. */
  31821. Mesh.prototype.getLODLevels = function () {
  31822. return this._LODLevels;
  31823. };
  31824. Mesh.prototype._sortLODLevels = function () {
  31825. this._LODLevels.sort(function (a, b) {
  31826. if (a.distance < b.distance) {
  31827. return 1;
  31828. }
  31829. if (a.distance > b.distance) {
  31830. return -1;
  31831. }
  31832. return 0;
  31833. });
  31834. };
  31835. /**
  31836. * Add a mesh as LOD level triggered at the given distance.
  31837. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31838. * @param distance The distance from the center of the object to show this level
  31839. * @param mesh The mesh to be added as LOD level (can be null)
  31840. * @return This mesh (for chaining)
  31841. */
  31842. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31843. if (mesh && mesh._masterMesh) {
  31844. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31845. return this;
  31846. }
  31847. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31848. this._LODLevels.push(level);
  31849. if (mesh) {
  31850. mesh._masterMesh = this;
  31851. }
  31852. this._sortLODLevels();
  31853. return this;
  31854. };
  31855. /**
  31856. * Returns the LOD level mesh at the passed distance or null if not found.
  31857. * It is related to the method `addLODLevel(distance, mesh)`.
  31858. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31859. * Returns an object Mesh or `null`.
  31860. */
  31861. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31862. for (var index = 0; index < this._LODLevels.length; index++) {
  31863. var level = this._LODLevels[index];
  31864. if (level.distance === distance) {
  31865. return level.mesh;
  31866. }
  31867. }
  31868. return null;
  31869. };
  31870. /**
  31871. * Remove a mesh from the LOD array
  31872. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31873. * @param {Mesh} mesh The mesh to be removed.
  31874. * @return {Mesh} This mesh (for chaining)
  31875. */
  31876. Mesh.prototype.removeLODLevel = function (mesh) {
  31877. for (var index = 0; index < this._LODLevels.length; index++) {
  31878. if (this._LODLevels[index].mesh === mesh) {
  31879. this._LODLevels.splice(index, 1);
  31880. if (mesh) {
  31881. mesh._masterMesh = null;
  31882. }
  31883. }
  31884. }
  31885. this._sortLODLevels();
  31886. return this;
  31887. };
  31888. /**
  31889. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31890. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31891. */
  31892. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31893. if (!this._LODLevels || this._LODLevels.length === 0) {
  31894. return this;
  31895. }
  31896. var bSphere;
  31897. if (boundingSphere) {
  31898. bSphere = boundingSphere;
  31899. }
  31900. else {
  31901. var boundingInfo = this.getBoundingInfo();
  31902. bSphere = boundingInfo.boundingSphere;
  31903. }
  31904. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31905. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31906. if (this.onLODLevelSelection) {
  31907. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31908. }
  31909. return this;
  31910. }
  31911. for (var index = 0; index < this._LODLevels.length; index++) {
  31912. var level = this._LODLevels[index];
  31913. if (level.distance < distanceToCamera) {
  31914. if (level.mesh) {
  31915. level.mesh._preActivate();
  31916. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31917. }
  31918. if (this.onLODLevelSelection) {
  31919. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31920. }
  31921. return level.mesh;
  31922. }
  31923. }
  31924. if (this.onLODLevelSelection) {
  31925. this.onLODLevelSelection(distanceToCamera, this, this);
  31926. }
  31927. return this;
  31928. };
  31929. Object.defineProperty(Mesh.prototype, "geometry", {
  31930. /**
  31931. * Returns the mesh internal Geometry object.
  31932. */
  31933. get: function () {
  31934. return this._geometry;
  31935. },
  31936. enumerable: true,
  31937. configurable: true
  31938. });
  31939. /**
  31940. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31941. */
  31942. Mesh.prototype.getTotalVertices = function () {
  31943. if (this._geometry === null || this._geometry === undefined) {
  31944. return 0;
  31945. }
  31946. return this._geometry.getTotalVertices();
  31947. };
  31948. /**
  31949. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31950. * 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.
  31951. * You can force the copy with forceCopy === true
  31952. * Returns null if the mesh has no geometry or no vertex buffer.
  31953. * Possible `kind` values :
  31954. * - BABYLON.VertexBuffer.PositionKind
  31955. * - BABYLON.VertexBuffer.UVKind
  31956. * - BABYLON.VertexBuffer.UV2Kind
  31957. * - BABYLON.VertexBuffer.UV3Kind
  31958. * - BABYLON.VertexBuffer.UV4Kind
  31959. * - BABYLON.VertexBuffer.UV5Kind
  31960. * - BABYLON.VertexBuffer.UV6Kind
  31961. * - BABYLON.VertexBuffer.ColorKind
  31962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31966. */
  31967. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31968. if (!this._geometry) {
  31969. return null;
  31970. }
  31971. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31972. };
  31973. /**
  31974. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31975. * Returns `null` if the mesh has no geometry.
  31976. * Possible `kind` values :
  31977. * - BABYLON.VertexBuffer.PositionKind
  31978. * - BABYLON.VertexBuffer.UVKind
  31979. * - BABYLON.VertexBuffer.UV2Kind
  31980. * - BABYLON.VertexBuffer.UV3Kind
  31981. * - BABYLON.VertexBuffer.UV4Kind
  31982. * - BABYLON.VertexBuffer.UV5Kind
  31983. * - BABYLON.VertexBuffer.UV6Kind
  31984. * - BABYLON.VertexBuffer.ColorKind
  31985. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31986. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31987. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31988. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31989. */
  31990. Mesh.prototype.getVertexBuffer = function (kind) {
  31991. if (!this._geometry) {
  31992. return null;
  31993. }
  31994. return this._geometry.getVertexBuffer(kind);
  31995. };
  31996. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31997. if (!this._geometry) {
  31998. if (this._delayInfo) {
  31999. return this._delayInfo.indexOf(kind) !== -1;
  32000. }
  32001. return false;
  32002. }
  32003. return this._geometry.isVerticesDataPresent(kind);
  32004. };
  32005. /**
  32006. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32007. * Possible `kind` values :
  32008. * - BABYLON.VertexBuffer.PositionKind
  32009. * - BABYLON.VertexBuffer.UVKind
  32010. * - BABYLON.VertexBuffer.UV2Kind
  32011. * - BABYLON.VertexBuffer.UV3Kind
  32012. * - BABYLON.VertexBuffer.UV4Kind
  32013. * - BABYLON.VertexBuffer.UV5Kind
  32014. * - BABYLON.VertexBuffer.UV6Kind
  32015. * - BABYLON.VertexBuffer.ColorKind
  32016. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32017. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32018. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32019. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32020. */
  32021. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32022. if (!this._geometry) {
  32023. if (this._delayInfo) {
  32024. return this._delayInfo.indexOf(kind) !== -1;
  32025. }
  32026. return false;
  32027. }
  32028. return this._geometry.isVertexBufferUpdatable(kind);
  32029. };
  32030. /**
  32031. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  32032. * Possible `kind` values :
  32033. * - BABYLON.VertexBuffer.PositionKind
  32034. * - BABYLON.VertexBuffer.UVKind
  32035. * - BABYLON.VertexBuffer.UV2Kind
  32036. * - BABYLON.VertexBuffer.UV3Kind
  32037. * - BABYLON.VertexBuffer.UV4Kind
  32038. * - BABYLON.VertexBuffer.UV5Kind
  32039. * - BABYLON.VertexBuffer.UV6Kind
  32040. * - BABYLON.VertexBuffer.ColorKind
  32041. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32042. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32043. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32044. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32045. */
  32046. Mesh.prototype.getVerticesDataKinds = function () {
  32047. if (!this._geometry) {
  32048. var result = new Array();
  32049. if (this._delayInfo) {
  32050. this._delayInfo.forEach(function (kind, index, array) {
  32051. result.push(kind);
  32052. });
  32053. }
  32054. return result;
  32055. }
  32056. return this._geometry.getVerticesDataKinds();
  32057. };
  32058. /**
  32059. * Returns a positive integer : the total number of indices in this mesh geometry.
  32060. * Returns zero if the mesh has no geometry.
  32061. */
  32062. Mesh.prototype.getTotalIndices = function () {
  32063. if (!this._geometry) {
  32064. return 0;
  32065. }
  32066. return this._geometry.getTotalIndices();
  32067. };
  32068. /**
  32069. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32070. * 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.
  32071. * Returns an empty array if the mesh has no geometry.
  32072. */
  32073. Mesh.prototype.getIndices = function (copyWhenShared) {
  32074. if (!this._geometry) {
  32075. return [];
  32076. }
  32077. return this._geometry.getIndices(copyWhenShared);
  32078. };
  32079. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32080. get: function () {
  32081. return this._masterMesh !== null && this._masterMesh !== undefined;
  32082. },
  32083. enumerable: true,
  32084. configurable: true
  32085. });
  32086. /**
  32087. * Determine if the current mesh is ready to be rendered
  32088. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32089. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32090. * @returns true if all associated assets are ready (material, textures, shaders)
  32091. */
  32092. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32093. if (completeCheck === void 0) { completeCheck = false; }
  32094. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32095. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32096. return false;
  32097. }
  32098. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32099. return false;
  32100. }
  32101. if (!this.subMeshes || this.subMeshes.length === 0) {
  32102. return true;
  32103. }
  32104. if (!completeCheck) {
  32105. return true;
  32106. }
  32107. var engine = this.getEngine();
  32108. var scene = this.getScene();
  32109. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32110. this.computeWorldMatrix();
  32111. var mat = this.material || scene.defaultMaterial;
  32112. if (mat) {
  32113. if (mat.storeEffectOnSubMeshes) {
  32114. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32115. var subMesh = _a[_i];
  32116. var effectiveMaterial = subMesh.getMaterial();
  32117. if (effectiveMaterial) {
  32118. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32119. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32120. return false;
  32121. }
  32122. }
  32123. else {
  32124. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32125. return false;
  32126. }
  32127. }
  32128. }
  32129. }
  32130. }
  32131. else {
  32132. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32133. return false;
  32134. }
  32135. }
  32136. }
  32137. // Shadows
  32138. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32139. var light = _c[_b];
  32140. var generator = light.getShadowGenerator();
  32141. if (generator) {
  32142. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32143. var subMesh = _e[_d];
  32144. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32145. return false;
  32146. }
  32147. }
  32148. }
  32149. }
  32150. // LOD
  32151. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32152. var lod = _g[_f];
  32153. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32154. return false;
  32155. }
  32156. }
  32157. return true;
  32158. };
  32159. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32160. /**
  32161. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32162. * This property is pertinent only for updatable parametric shapes.
  32163. */
  32164. get: function () {
  32165. return this._areNormalsFrozen;
  32166. },
  32167. enumerable: true,
  32168. configurable: true
  32169. });
  32170. /**
  32171. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32172. * It has no effect at all on other shapes.
  32173. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32174. * Returns the Mesh.
  32175. */
  32176. Mesh.prototype.freezeNormals = function () {
  32177. this._areNormalsFrozen = true;
  32178. return this;
  32179. };
  32180. /**
  32181. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32182. * It has no effect at all on other shapes.
  32183. * It reactivates the mesh normals computation if it was previously frozen.
  32184. * Returns the Mesh.
  32185. */
  32186. Mesh.prototype.unfreezeNormals = function () {
  32187. this._areNormalsFrozen = false;
  32188. return this;
  32189. };
  32190. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32191. /**
  32192. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32193. */
  32194. set: function (count) {
  32195. this._overridenInstanceCount = count;
  32196. },
  32197. enumerable: true,
  32198. configurable: true
  32199. });
  32200. // Methods
  32201. Mesh.prototype._preActivate = function () {
  32202. var sceneRenderId = this.getScene().getRenderId();
  32203. if (this._preActivateId === sceneRenderId) {
  32204. return this;
  32205. }
  32206. this._preActivateId = sceneRenderId;
  32207. this._visibleInstances = null;
  32208. return this;
  32209. };
  32210. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32211. if (this._visibleInstances) {
  32212. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32213. }
  32214. return this;
  32215. };
  32216. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32217. if (!this._visibleInstances) {
  32218. this._visibleInstances = {};
  32219. this._visibleInstances.defaultRenderId = renderId;
  32220. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32221. }
  32222. if (!this._visibleInstances[renderId]) {
  32223. this._visibleInstances[renderId] = new Array();
  32224. }
  32225. this._visibleInstances[renderId].push(instance);
  32226. return this;
  32227. };
  32228. /**
  32229. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32230. * This means the mesh underlying bounding box and sphere are recomputed.
  32231. * Returns the Mesh.
  32232. */
  32233. Mesh.prototype.refreshBoundingInfo = function () {
  32234. return this._refreshBoundingInfo(false);
  32235. };
  32236. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32237. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32238. return this;
  32239. }
  32240. var data = this._getPositionData(applySkeleton);
  32241. if (data) {
  32242. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32243. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32244. }
  32245. if (this.subMeshes) {
  32246. for (var index = 0; index < this.subMeshes.length; index++) {
  32247. this.subMeshes[index].refreshBoundingInfo();
  32248. }
  32249. }
  32250. this._updateBoundingInfo();
  32251. return this;
  32252. };
  32253. Mesh.prototype._getPositionData = function (applySkeleton) {
  32254. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32255. if (data && applySkeleton && this.skeleton) {
  32256. data = BABYLON.Tools.Slice(data);
  32257. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32258. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32259. if (matricesWeightsData && matricesIndicesData) {
  32260. var needExtras = this.numBoneInfluencers > 4;
  32261. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32262. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32263. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32264. var tempVector = BABYLON.Tmp.Vector3[0];
  32265. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32266. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32267. var matWeightIdx = 0;
  32268. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32269. finalMatrix.reset();
  32270. var inf;
  32271. var weight;
  32272. for (inf = 0; inf < 4; inf++) {
  32273. weight = matricesWeightsData[matWeightIdx + inf];
  32274. if (weight <= 0)
  32275. break;
  32276. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32277. finalMatrix.addToSelf(tempMatrix);
  32278. }
  32279. if (needExtras) {
  32280. for (inf = 0; inf < 4; inf++) {
  32281. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32282. if (weight <= 0)
  32283. break;
  32284. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32285. finalMatrix.addToSelf(tempMatrix);
  32286. }
  32287. }
  32288. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32289. tempVector.toArray(data, index);
  32290. }
  32291. }
  32292. }
  32293. return data;
  32294. };
  32295. Mesh.prototype._createGlobalSubMesh = function (force) {
  32296. var totalVertices = this.getTotalVertices();
  32297. if (!totalVertices || !this.getIndices()) {
  32298. return null;
  32299. }
  32300. // Check if we need to recreate the submeshes
  32301. if (this.subMeshes && this.subMeshes.length > 0) {
  32302. var ib = this.getIndices();
  32303. if (!ib) {
  32304. return null;
  32305. }
  32306. var totalIndices = ib.length;
  32307. var needToRecreate = false;
  32308. if (force) {
  32309. needToRecreate = true;
  32310. }
  32311. else {
  32312. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32313. var submesh = _a[_i];
  32314. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32315. needToRecreate = true;
  32316. break;
  32317. }
  32318. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32319. needToRecreate = true;
  32320. break;
  32321. }
  32322. }
  32323. }
  32324. if (!needToRecreate) {
  32325. return this.subMeshes[0];
  32326. }
  32327. }
  32328. this.releaseSubMeshes();
  32329. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32330. };
  32331. Mesh.prototype.subdivide = function (count) {
  32332. if (count < 1) {
  32333. return;
  32334. }
  32335. var totalIndices = this.getTotalIndices();
  32336. var subdivisionSize = (totalIndices / count) | 0;
  32337. var offset = 0;
  32338. // Ensure that subdivisionSize is a multiple of 3
  32339. while (subdivisionSize % 3 !== 0) {
  32340. subdivisionSize++;
  32341. }
  32342. this.releaseSubMeshes();
  32343. for (var index = 0; index < count; index++) {
  32344. if (offset >= totalIndices) {
  32345. break;
  32346. }
  32347. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32348. offset += subdivisionSize;
  32349. }
  32350. this.synchronizeInstances();
  32351. };
  32352. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32353. if (updatable === void 0) { updatable = false; }
  32354. if (!this._geometry) {
  32355. var vertexData = new BABYLON.VertexData();
  32356. vertexData.set(data, kind);
  32357. var scene = this.getScene();
  32358. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32359. }
  32360. else {
  32361. this._geometry.setVerticesData(kind, data, updatable, stride);
  32362. }
  32363. return this;
  32364. };
  32365. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32366. if (updatable === void 0) { updatable = true; }
  32367. var vb = this.getVertexBuffer(kind);
  32368. if (!vb || vb.isUpdatable() === updatable) {
  32369. return;
  32370. }
  32371. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32372. };
  32373. /**
  32374. * Sets the mesh VertexBuffer.
  32375. * Returns the Mesh.
  32376. */
  32377. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32378. if (!this._geometry) {
  32379. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32380. }
  32381. this._geometry.setVerticesBuffer(buffer);
  32382. return this;
  32383. };
  32384. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32385. if (!this._geometry) {
  32386. return this;
  32387. }
  32388. if (!makeItUnique) {
  32389. this._geometry.updateVerticesData(kind, data, updateExtends);
  32390. }
  32391. else {
  32392. this.makeGeometryUnique();
  32393. this.updateVerticesData(kind, data, updateExtends, false);
  32394. }
  32395. return this;
  32396. };
  32397. /**
  32398. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32399. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32400. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32401. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32402. * Returns the Mesh.
  32403. */
  32404. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32405. if (computeNormals === void 0) { computeNormals = true; }
  32406. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32407. if (!positions) {
  32408. return this;
  32409. }
  32410. positionFunction(positions);
  32411. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32412. if (computeNormals) {
  32413. var indices = this.getIndices();
  32414. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32415. if (!normals) {
  32416. return this;
  32417. }
  32418. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32419. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32420. }
  32421. return this;
  32422. };
  32423. /**
  32424. * Creates a un-shared specific occurence of the geometry for the mesh.
  32425. * Returns the Mesh.
  32426. */
  32427. Mesh.prototype.makeGeometryUnique = function () {
  32428. if (!this._geometry) {
  32429. return this;
  32430. }
  32431. var oldGeometry = this._geometry;
  32432. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32433. oldGeometry.releaseForMesh(this, true);
  32434. geometry.applyToMesh(this);
  32435. return this;
  32436. };
  32437. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32438. if (totalVertices === void 0) { totalVertices = null; }
  32439. if (updatable === void 0) { updatable = false; }
  32440. if (!this._geometry) {
  32441. var vertexData = new BABYLON.VertexData();
  32442. vertexData.indices = indices;
  32443. var scene = this.getScene();
  32444. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32445. }
  32446. else {
  32447. this._geometry.setIndices(indices, totalVertices, updatable);
  32448. }
  32449. return this;
  32450. };
  32451. /**
  32452. * Update the current index buffer
  32453. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32454. * Returns the Mesh.
  32455. */
  32456. Mesh.prototype.updateIndices = function (indices, offset) {
  32457. if (!this._geometry) {
  32458. return this;
  32459. }
  32460. this._geometry.updateIndices(indices, offset);
  32461. return this;
  32462. };
  32463. /**
  32464. * Invert the geometry to move from a right handed system to a left handed one.
  32465. * Returns the Mesh.
  32466. */
  32467. Mesh.prototype.toLeftHanded = function () {
  32468. if (!this._geometry) {
  32469. return this;
  32470. }
  32471. this._geometry.toLeftHanded();
  32472. return this;
  32473. };
  32474. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32475. if (!this._geometry) {
  32476. return this;
  32477. }
  32478. var engine = this.getScene().getEngine();
  32479. // Wireframe
  32480. var indexToBind;
  32481. if (this._unIndexed) {
  32482. indexToBind = null;
  32483. }
  32484. else {
  32485. switch (fillMode) {
  32486. case BABYLON.Material.PointFillMode:
  32487. indexToBind = null;
  32488. break;
  32489. case BABYLON.Material.WireFrameFillMode:
  32490. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32491. break;
  32492. default:
  32493. case BABYLON.Material.TriangleFillMode:
  32494. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32495. break;
  32496. }
  32497. }
  32498. // VBOs
  32499. this._geometry._bind(effect, indexToBind);
  32500. return this;
  32501. };
  32502. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32503. if (alternate === void 0) { alternate = false; }
  32504. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32505. return this;
  32506. }
  32507. this.onBeforeDrawObservable.notifyObservers(this);
  32508. var scene = this.getScene();
  32509. var engine = scene.getEngine();
  32510. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32511. // or triangles as points
  32512. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32513. }
  32514. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32515. // Triangles as wireframe
  32516. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32517. }
  32518. else {
  32519. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32520. }
  32521. if (scene._isAlternateRenderingEnabled && !alternate) {
  32522. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32523. if (!effect || !scene.activeCamera) {
  32524. return this;
  32525. }
  32526. scene._switchToAlternateCameraConfiguration(true);
  32527. this._effectiveMaterial.bindView(effect);
  32528. this._effectiveMaterial.bindViewProjection(effect);
  32529. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32530. this._draw(subMesh, fillMode, instancesCount, true);
  32531. engine.setViewport(scene.activeCamera.viewport);
  32532. scene._switchToAlternateCameraConfiguration(false);
  32533. this._effectiveMaterial.bindView(effect);
  32534. this._effectiveMaterial.bindViewProjection(effect);
  32535. }
  32536. return this;
  32537. };
  32538. /**
  32539. * Registers for this mesh a javascript function called just before the rendering process.
  32540. * This function is passed the current mesh.
  32541. * Return the Mesh.
  32542. */
  32543. Mesh.prototype.registerBeforeRender = function (func) {
  32544. this.onBeforeRenderObservable.add(func);
  32545. return this;
  32546. };
  32547. /**
  32548. * Disposes a previously registered javascript function called before the rendering.
  32549. * This function is passed the current mesh.
  32550. * Returns the Mesh.
  32551. */
  32552. Mesh.prototype.unregisterBeforeRender = function (func) {
  32553. this.onBeforeRenderObservable.removeCallback(func);
  32554. return this;
  32555. };
  32556. /**
  32557. * Registers for this mesh a javascript function called just after the rendering is complete.
  32558. * This function is passed the current mesh.
  32559. * Returns the Mesh.
  32560. */
  32561. Mesh.prototype.registerAfterRender = function (func) {
  32562. this.onAfterRenderObservable.add(func);
  32563. return this;
  32564. };
  32565. /**
  32566. * Disposes a previously registered javascript function called after the rendering.
  32567. * This function is passed the current mesh.
  32568. * Return the Mesh.
  32569. */
  32570. Mesh.prototype.unregisterAfterRender = function (func) {
  32571. this.onAfterRenderObservable.removeCallback(func);
  32572. return this;
  32573. };
  32574. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32575. var scene = this.getScene();
  32576. this._batchCache.mustReturn = false;
  32577. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32578. this._batchCache.visibleInstances[subMeshId] = null;
  32579. if (this._visibleInstances) {
  32580. var currentRenderId = scene.getRenderId();
  32581. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32582. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32583. var selfRenderId = this._renderId;
  32584. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32585. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32586. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32587. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32588. }
  32589. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32590. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32591. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32592. this._batchCache.mustReturn = true;
  32593. return this._batchCache;
  32594. }
  32595. if (currentRenderId !== selfRenderId) {
  32596. this._batchCache.renderSelf[subMeshId] = false;
  32597. }
  32598. }
  32599. this._renderIdForInstances[subMeshId] = currentRenderId;
  32600. }
  32601. return this._batchCache;
  32602. };
  32603. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32604. var visibleInstances = batch.visibleInstances[subMesh._id];
  32605. if (!visibleInstances) {
  32606. return this;
  32607. }
  32608. var matricesCount = visibleInstances.length + 1;
  32609. var bufferSize = matricesCount * 16 * 4;
  32610. var currentInstancesBufferSize = this._instancesBufferSize;
  32611. var instancesBuffer = this._instancesBuffer;
  32612. while (this._instancesBufferSize < bufferSize) {
  32613. this._instancesBufferSize *= 2;
  32614. }
  32615. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32616. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32617. }
  32618. var offset = 0;
  32619. var instancesCount = 0;
  32620. var world = this.getWorldMatrix();
  32621. if (batch.renderSelf[subMesh._id]) {
  32622. world.copyToArray(this._instancesData, offset);
  32623. offset += 16;
  32624. instancesCount++;
  32625. }
  32626. if (visibleInstances) {
  32627. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32628. var instance = visibleInstances[instanceIndex];
  32629. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32630. offset += 16;
  32631. instancesCount++;
  32632. }
  32633. }
  32634. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32635. if (instancesBuffer) {
  32636. instancesBuffer.dispose();
  32637. }
  32638. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32639. this._instancesBuffer = instancesBuffer;
  32640. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32641. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32642. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32643. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32644. }
  32645. else {
  32646. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32647. }
  32648. this._bind(subMesh, effect, fillMode);
  32649. this._draw(subMesh, fillMode, instancesCount);
  32650. engine.unbindInstanceAttributes();
  32651. return this;
  32652. };
  32653. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32654. var scene = this.getScene();
  32655. var engine = scene.getEngine();
  32656. if (hardwareInstancedRendering) {
  32657. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32658. }
  32659. else {
  32660. if (batch.renderSelf[subMesh._id]) {
  32661. // Draw
  32662. if (onBeforeDraw) {
  32663. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32664. }
  32665. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32666. }
  32667. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32668. if (visibleInstancesForSubMesh) {
  32669. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32670. var instance = visibleInstancesForSubMesh[instanceIndex];
  32671. // World
  32672. var world = instance.getWorldMatrix();
  32673. if (onBeforeDraw) {
  32674. onBeforeDraw(true, world, effectiveMaterial);
  32675. }
  32676. // Draw
  32677. this._draw(subMesh, fillMode);
  32678. }
  32679. }
  32680. }
  32681. return this;
  32682. };
  32683. /**
  32684. * Triggers the draw call for the mesh.
  32685. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32686. * Returns the Mesh.
  32687. */
  32688. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32689. this._checkOcclusionQuery();
  32690. if (this._isOccluded) {
  32691. return this;
  32692. }
  32693. var scene = this.getScene();
  32694. // Managing instances
  32695. var batch = this._getInstancesRenderList(subMesh._id);
  32696. if (batch.mustReturn) {
  32697. return this;
  32698. }
  32699. // Checking geometry state
  32700. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32701. return this;
  32702. }
  32703. this.onBeforeRenderObservable.notifyObservers(this);
  32704. var engine = scene.getEngine();
  32705. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32706. // Material
  32707. var material = subMesh.getMaterial();
  32708. if (!material) {
  32709. return this;
  32710. }
  32711. this._effectiveMaterial = material;
  32712. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32713. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32714. return this;
  32715. }
  32716. }
  32717. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32718. return this;
  32719. }
  32720. // Alpha mode
  32721. if (enableAlphaMode) {
  32722. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32723. }
  32724. // Outline - step 1
  32725. var savedDepthWrite = engine.getDepthWrite();
  32726. if (this.renderOutline) {
  32727. engine.setDepthWrite(false);
  32728. scene.getOutlineRenderer().render(subMesh, batch);
  32729. engine.setDepthWrite(savedDepthWrite);
  32730. }
  32731. var effect;
  32732. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32733. effect = subMesh.effect;
  32734. }
  32735. else {
  32736. effect = this._effectiveMaterial.getEffect();
  32737. }
  32738. if (!effect) {
  32739. return this;
  32740. }
  32741. var sideOrientation = this.overrideMaterialSideOrientation;
  32742. if (sideOrientation == null) {
  32743. sideOrientation = this._effectiveMaterial.sideOrientation;
  32744. if (this._getWorldMatrixDeterminant() < 0) {
  32745. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32746. }
  32747. }
  32748. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32749. if (this._effectiveMaterial.forceDepthWrite) {
  32750. engine.setDepthWrite(true);
  32751. }
  32752. // Bind
  32753. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32754. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32755. this._bind(subMesh, effect, fillMode);
  32756. }
  32757. var world = this.getWorldMatrix();
  32758. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32759. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32760. }
  32761. else {
  32762. this._effectiveMaterial.bind(world, this);
  32763. }
  32764. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32765. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32766. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32767. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32768. }
  32769. // Draw
  32770. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32771. // Unbind
  32772. this._effectiveMaterial.unbind();
  32773. // Outline - step 2
  32774. if (this.renderOutline && savedDepthWrite) {
  32775. engine.setDepthWrite(true);
  32776. engine.setColorWrite(false);
  32777. scene.getOutlineRenderer().render(subMesh, batch);
  32778. engine.setColorWrite(true);
  32779. }
  32780. // Overlay
  32781. if (this.renderOverlay) {
  32782. var currentMode = engine.getAlphaMode();
  32783. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32784. scene.getOutlineRenderer().render(subMesh, batch, true);
  32785. engine.setAlphaMode(currentMode);
  32786. }
  32787. this.onAfterRenderObservable.notifyObservers(this);
  32788. return this;
  32789. };
  32790. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32791. if (isInstance && effectiveMaterial) {
  32792. effectiveMaterial.bindOnlyWorldMatrix(world);
  32793. }
  32794. };
  32795. /**
  32796. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32797. */
  32798. Mesh.prototype.getEmittedParticleSystems = function () {
  32799. var results = new Array();
  32800. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32801. var particleSystem = this.getScene().particleSystems[index];
  32802. if (particleSystem.emitter === this) {
  32803. results.push(particleSystem);
  32804. }
  32805. }
  32806. return results;
  32807. };
  32808. /**
  32809. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32810. */
  32811. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32812. var results = new Array();
  32813. var descendants = this.getDescendants();
  32814. descendants.push(this);
  32815. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32816. var particleSystem = this.getScene().particleSystems[index];
  32817. var emitter = particleSystem.emitter;
  32818. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32819. results.push(particleSystem);
  32820. }
  32821. }
  32822. return results;
  32823. };
  32824. /**
  32825. * Normalize matrix weights so that all vertices have a total weight set to 1
  32826. */
  32827. Mesh.prototype.cleanMatrixWeights = function () {
  32828. var epsilon = 1e-3;
  32829. var noInfluenceBoneIndex = 0.0;
  32830. if (this.skeleton) {
  32831. noInfluenceBoneIndex = this.skeleton.bones.length;
  32832. }
  32833. else {
  32834. return;
  32835. }
  32836. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32837. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32838. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32839. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32840. var influencers = this.numBoneInfluencers;
  32841. var size = matricesWeights.length;
  32842. for (var i = 0; i < size; i += 4) {
  32843. var weight = 0.0;
  32844. var firstZeroWeight = -1;
  32845. for (var j = 0; j < 4; j++) {
  32846. var w = matricesWeights[i + j];
  32847. weight += w;
  32848. if (w < epsilon && firstZeroWeight < 0) {
  32849. firstZeroWeight = j;
  32850. }
  32851. }
  32852. if (matricesWeightsExtra) {
  32853. for (var j = 0; j < 4; j++) {
  32854. var w = matricesWeightsExtra[i + j];
  32855. weight += w;
  32856. if (w < epsilon && firstZeroWeight < 0) {
  32857. firstZeroWeight = j + 4;
  32858. }
  32859. }
  32860. }
  32861. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32862. firstZeroWeight = influencers - 1;
  32863. }
  32864. if (weight > epsilon) {
  32865. var mweight = 1.0 / weight;
  32866. for (var j = 0; j < 4; j++) {
  32867. matricesWeights[i + j] *= mweight;
  32868. }
  32869. if (matricesWeightsExtra) {
  32870. for (var j = 0; j < 4; j++) {
  32871. matricesWeightsExtra[i + j] *= mweight;
  32872. }
  32873. }
  32874. }
  32875. else {
  32876. if (firstZeroWeight >= 4) {
  32877. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32878. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32879. }
  32880. else {
  32881. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32882. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32883. }
  32884. }
  32885. }
  32886. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32887. if (matricesIndicesExtra) {
  32888. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32889. }
  32890. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32891. if (matricesWeightsExtra) {
  32892. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32893. }
  32894. };
  32895. Mesh.prototype._checkDelayState = function () {
  32896. var scene = this.getScene();
  32897. if (this._geometry) {
  32898. this._geometry.load(scene);
  32899. }
  32900. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32901. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32902. this._queueLoad(scene);
  32903. }
  32904. return this;
  32905. };
  32906. Mesh.prototype._queueLoad = function (scene) {
  32907. var _this = this;
  32908. scene._addPendingData(this);
  32909. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32910. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32911. if (data instanceof ArrayBuffer) {
  32912. _this._delayLoadingFunction(data, _this);
  32913. }
  32914. else {
  32915. _this._delayLoadingFunction(JSON.parse(data), _this);
  32916. }
  32917. _this.instances.forEach(function (instance) {
  32918. instance._syncSubMeshes();
  32919. });
  32920. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32921. scene._removePendingData(_this);
  32922. }, function () { }, scene.database, getBinaryData);
  32923. return this;
  32924. };
  32925. /**
  32926. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32927. */
  32928. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32929. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32930. return false;
  32931. }
  32932. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32933. return false;
  32934. }
  32935. this._checkDelayState();
  32936. return true;
  32937. };
  32938. /**
  32939. * Sets the mesh material by the material or multiMaterial `id` property.
  32940. * The material `id` is a string identifying the material or the multiMaterial.
  32941. * This method returns the Mesh.
  32942. */
  32943. Mesh.prototype.setMaterialByID = function (id) {
  32944. var materials = this.getScene().materials;
  32945. var index;
  32946. for (index = materials.length - 1; index > -1; index--) {
  32947. if (materials[index].id === id) {
  32948. this.material = materials[index];
  32949. return this;
  32950. }
  32951. }
  32952. // Multi
  32953. var multiMaterials = this.getScene().multiMaterials;
  32954. for (index = multiMaterials.length - 1; index > -1; index--) {
  32955. if (multiMaterials[index].id === id) {
  32956. this.material = multiMaterials[index];
  32957. return this;
  32958. }
  32959. }
  32960. return this;
  32961. };
  32962. /**
  32963. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32964. */
  32965. Mesh.prototype.getAnimatables = function () {
  32966. var results = new Array();
  32967. if (this.material) {
  32968. results.push(this.material);
  32969. }
  32970. if (this.skeleton) {
  32971. results.push(this.skeleton);
  32972. }
  32973. return results;
  32974. };
  32975. /**
  32976. * Modifies the mesh geometry according to the passed transformation matrix.
  32977. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32978. * The mesh normals are modified accordingly the same transformation.
  32979. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32980. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32981. * Returns the Mesh.
  32982. */
  32983. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32984. // Position
  32985. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32986. return this;
  32987. }
  32988. var submeshes = this.subMeshes.splice(0);
  32989. this._resetPointsArrayCache();
  32990. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32991. var temp = new Array();
  32992. var index;
  32993. for (index = 0; index < data.length; index += 3) {
  32994. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32995. }
  32996. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32997. // Normals
  32998. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32999. return this;
  33000. }
  33001. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33002. temp = [];
  33003. for (index = 0; index < data.length; index += 3) {
  33004. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33005. }
  33006. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33007. // flip faces?
  33008. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33009. this.flipFaces();
  33010. }
  33011. // Restore submeshes
  33012. this.releaseSubMeshes();
  33013. this.subMeshes = submeshes;
  33014. return this;
  33015. };
  33016. /**
  33017. * Modifies the mesh geometry according to its own current World Matrix.
  33018. * The mesh World Matrix is then reset.
  33019. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33020. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  33021. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33022. * Returns the Mesh.
  33023. */
  33024. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33025. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33026. this.scaling.copyFromFloats(1, 1, 1);
  33027. this.position.copyFromFloats(0, 0, 0);
  33028. this.rotation.copyFromFloats(0, 0, 0);
  33029. //only if quaternion is already set
  33030. if (this.rotationQuaternion) {
  33031. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33032. }
  33033. this._worldMatrix = BABYLON.Matrix.Identity();
  33034. return this;
  33035. };
  33036. Object.defineProperty(Mesh.prototype, "_positions", {
  33037. // Cache
  33038. get: function () {
  33039. if (this._geometry) {
  33040. return this._geometry._positions;
  33041. }
  33042. return null;
  33043. },
  33044. enumerable: true,
  33045. configurable: true
  33046. });
  33047. Mesh.prototype._resetPointsArrayCache = function () {
  33048. if (this._geometry) {
  33049. this._geometry._resetPointsArrayCache();
  33050. }
  33051. return this;
  33052. };
  33053. Mesh.prototype._generatePointsArray = function () {
  33054. if (this._geometry) {
  33055. return this._geometry._generatePointsArray();
  33056. }
  33057. return false;
  33058. };
  33059. /**
  33060. * Returns a new Mesh object generated from the current mesh properties.
  33061. * This method must not get confused with createInstance().
  33062. * The parameter `name` is a string, the name given to the new mesh.
  33063. * The optional parameter `newParent` can be any Node object (default `null`).
  33064. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  33065. * 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.
  33066. */
  33067. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33068. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33069. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33070. };
  33071. /**
  33072. * Releases resources associated with this mesh.
  33073. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33074. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33075. */
  33076. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33077. var _this = this;
  33078. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33079. this.morphTargetManager = null;
  33080. if (this._geometry) {
  33081. this._geometry.releaseForMesh(this, true);
  33082. }
  33083. // Sources
  33084. var meshes = this.getScene().meshes;
  33085. meshes.forEach(function (abstractMesh) {
  33086. var mesh = abstractMesh;
  33087. if (mesh._source && mesh._source === _this) {
  33088. mesh._source = null;
  33089. }
  33090. });
  33091. this._source = null;
  33092. // Instances
  33093. if (this._instancesBuffer) {
  33094. this._instancesBuffer.dispose();
  33095. this._instancesBuffer = null;
  33096. }
  33097. while (this.instances.length) {
  33098. this.instances[0].dispose();
  33099. }
  33100. // Effect layers.
  33101. var effectLayers = this.getScene().effectLayers;
  33102. for (var i = 0; i < effectLayers.length; i++) {
  33103. var effectLayer = effectLayers[i];
  33104. if (effectLayer) {
  33105. effectLayer._disposeMesh(this);
  33106. }
  33107. }
  33108. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33109. };
  33110. /**
  33111. * Modifies the mesh geometry according to a displacement map.
  33112. * 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.
  33113. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33114. * This method returns nothing.
  33115. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33116. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33117. * 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.
  33118. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33119. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33120. *
  33121. * Returns the Mesh.
  33122. */
  33123. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33124. var _this = this;
  33125. var scene = this.getScene();
  33126. var onload = function (img) {
  33127. // Getting height map data
  33128. var canvas = document.createElement("canvas");
  33129. var context = canvas.getContext("2d");
  33130. var heightMapWidth = img.width;
  33131. var heightMapHeight = img.height;
  33132. canvas.width = heightMapWidth;
  33133. canvas.height = heightMapHeight;
  33134. context.drawImage(img, 0, 0);
  33135. // Create VertexData from map data
  33136. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33137. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33138. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33139. //execute success callback, if set
  33140. if (onSuccess) {
  33141. onSuccess(_this);
  33142. }
  33143. };
  33144. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33145. return this;
  33146. };
  33147. /**
  33148. * Modifies the mesh geometry according to a displacementMap buffer.
  33149. * 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.
  33150. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33151. * This method returns nothing.
  33152. * 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.
  33153. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33154. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33155. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33156. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33157. *
  33158. * Returns the Mesh.
  33159. */
  33160. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33161. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33162. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33163. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33164. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33165. return this;
  33166. }
  33167. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33168. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33169. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33170. var position = BABYLON.Vector3.Zero();
  33171. var normal = BABYLON.Vector3.Zero();
  33172. var uv = BABYLON.Vector2.Zero();
  33173. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33174. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33175. for (var index = 0; index < positions.length; index += 3) {
  33176. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33177. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33178. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33179. // Compute height
  33180. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33181. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33182. var pos = (u + v * heightMapWidth) * 4;
  33183. var r = buffer[pos] / 255.0;
  33184. var g = buffer[pos + 1] / 255.0;
  33185. var b = buffer[pos + 2] / 255.0;
  33186. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33187. normal.normalize();
  33188. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33189. position = position.add(normal);
  33190. position.toArray(positions, index);
  33191. }
  33192. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33193. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33194. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33195. return this;
  33196. };
  33197. /**
  33198. * Modify the mesh to get a flat shading rendering.
  33199. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33200. * This method returns the Mesh.
  33201. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33202. */
  33203. Mesh.prototype.convertToFlatShadedMesh = function () {
  33204. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33205. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33206. var kinds = this.getVerticesDataKinds();
  33207. var vbs = {};
  33208. var data = {};
  33209. var newdata = {};
  33210. var updatableNormals = false;
  33211. var kindIndex;
  33212. var kind;
  33213. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33214. kind = kinds[kindIndex];
  33215. var vertexBuffer = this.getVertexBuffer(kind);
  33216. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33217. updatableNormals = vertexBuffer.isUpdatable();
  33218. kinds.splice(kindIndex, 1);
  33219. kindIndex--;
  33220. continue;
  33221. }
  33222. vbs[kind] = vertexBuffer;
  33223. data[kind] = vbs[kind].getData();
  33224. newdata[kind] = [];
  33225. }
  33226. // Save previous submeshes
  33227. var previousSubmeshes = this.subMeshes.slice(0);
  33228. var indices = this.getIndices();
  33229. var totalIndices = this.getTotalIndices();
  33230. // Generating unique vertices per face
  33231. var index;
  33232. for (index = 0; index < totalIndices; index++) {
  33233. var vertexIndex = indices[index];
  33234. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33235. kind = kinds[kindIndex];
  33236. var stride = vbs[kind].getStrideSize();
  33237. for (var offset = 0; offset < stride; offset++) {
  33238. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33239. }
  33240. }
  33241. }
  33242. // Updating faces & normal
  33243. var normals = [];
  33244. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33245. for (index = 0; index < totalIndices; index += 3) {
  33246. indices[index] = index;
  33247. indices[index + 1] = index + 1;
  33248. indices[index + 2] = index + 2;
  33249. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33250. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33251. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33252. var p1p2 = p1.subtract(p2);
  33253. var p3p2 = p3.subtract(p2);
  33254. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33255. // Store same normals for every vertex
  33256. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33257. normals.push(normal.x);
  33258. normals.push(normal.y);
  33259. normals.push(normal.z);
  33260. }
  33261. }
  33262. this.setIndices(indices);
  33263. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33264. // Updating vertex buffers
  33265. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33266. kind = kinds[kindIndex];
  33267. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33268. }
  33269. // Updating submeshes
  33270. this.releaseSubMeshes();
  33271. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33272. var previousOne = previousSubmeshes[submeshIndex];
  33273. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33274. }
  33275. this.synchronizeInstances();
  33276. return this;
  33277. };
  33278. /**
  33279. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33280. * In other words, more vertices, no more indices and a single bigger VBO.
  33281. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33282. * Returns the Mesh.
  33283. */
  33284. Mesh.prototype.convertToUnIndexedMesh = function () {
  33285. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33286. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33287. var kinds = this.getVerticesDataKinds();
  33288. var vbs = {};
  33289. var data = {};
  33290. var newdata = {};
  33291. var kindIndex;
  33292. var kind;
  33293. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33294. kind = kinds[kindIndex];
  33295. var vertexBuffer = this.getVertexBuffer(kind);
  33296. vbs[kind] = vertexBuffer;
  33297. data[kind] = vbs[kind].getData();
  33298. newdata[kind] = [];
  33299. }
  33300. // Save previous submeshes
  33301. var previousSubmeshes = this.subMeshes.slice(0);
  33302. var indices = this.getIndices();
  33303. var totalIndices = this.getTotalIndices();
  33304. // Generating unique vertices per face
  33305. var index;
  33306. for (index = 0; index < totalIndices; index++) {
  33307. var vertexIndex = indices[index];
  33308. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33309. kind = kinds[kindIndex];
  33310. var stride = vbs[kind].getStrideSize();
  33311. for (var offset = 0; offset < stride; offset++) {
  33312. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33313. }
  33314. }
  33315. }
  33316. // Updating indices
  33317. for (index = 0; index < totalIndices; index += 3) {
  33318. indices[index] = index;
  33319. indices[index + 1] = index + 1;
  33320. indices[index + 2] = index + 2;
  33321. }
  33322. this.setIndices(indices);
  33323. // Updating vertex buffers
  33324. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33325. kind = kinds[kindIndex];
  33326. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33327. }
  33328. // Updating submeshes
  33329. this.releaseSubMeshes();
  33330. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33331. var previousOne = previousSubmeshes[submeshIndex];
  33332. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33333. }
  33334. this._unIndexed = true;
  33335. this.synchronizeInstances();
  33336. return this;
  33337. };
  33338. /**
  33339. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33340. * This method returns the Mesh.
  33341. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33342. */
  33343. Mesh.prototype.flipFaces = function (flipNormals) {
  33344. if (flipNormals === void 0) { flipNormals = false; }
  33345. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33346. var i;
  33347. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33348. for (i = 0; i < vertex_data.normals.length; i++) {
  33349. vertex_data.normals[i] *= -1;
  33350. }
  33351. }
  33352. if (vertex_data.indices) {
  33353. var temp;
  33354. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33355. // reassign indices
  33356. temp = vertex_data.indices[i + 1];
  33357. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33358. vertex_data.indices[i + 2] = temp;
  33359. }
  33360. }
  33361. vertex_data.applyToMesh(this);
  33362. return this;
  33363. };
  33364. // Instances
  33365. /**
  33366. * Creates a new InstancedMesh object from the mesh model.
  33367. * An instance shares the same properties and the same material than its model.
  33368. * Only these properties of each instance can then be set individually :
  33369. * - position
  33370. * - rotation
  33371. * - rotationQuaternion
  33372. * - setPivotMatrix
  33373. * - scaling
  33374. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33375. * Warning : this method is not supported for Line mesh and LineSystem
  33376. */
  33377. Mesh.prototype.createInstance = function (name) {
  33378. return new BABYLON.InstancedMesh(name, this);
  33379. };
  33380. /**
  33381. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33382. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33383. * This method returns the Mesh.
  33384. */
  33385. Mesh.prototype.synchronizeInstances = function () {
  33386. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33387. var instance = this.instances[instanceIndex];
  33388. instance._syncSubMeshes();
  33389. }
  33390. return this;
  33391. };
  33392. /**
  33393. * Simplify the mesh according to the given array of settings.
  33394. * Function will return immediately and will simplify async. It returns the Mesh.
  33395. * @param settings a collection of simplification settings.
  33396. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33397. * @param type the type of simplification to run.
  33398. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33399. */
  33400. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33401. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33402. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33403. this.getScene().simplificationQueue.addTask({
  33404. settings: settings,
  33405. parallelProcessing: parallelProcessing,
  33406. mesh: this,
  33407. simplificationType: simplificationType,
  33408. successCallback: successCallback
  33409. });
  33410. return this;
  33411. };
  33412. /**
  33413. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33414. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33415. * This should be used together with the simplification to avoid disappearing triangles.
  33416. * Returns the Mesh.
  33417. * @param successCallback an optional success callback to be called after the optimization finished.
  33418. */
  33419. Mesh.prototype.optimizeIndices = function (successCallback) {
  33420. var _this = this;
  33421. var indices = this.getIndices();
  33422. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33423. if (!positions || !indices) {
  33424. return this;
  33425. }
  33426. var vectorPositions = new Array();
  33427. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33428. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33429. }
  33430. var dupes = new Array();
  33431. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33432. var realPos = vectorPositions.length - 1 - iteration;
  33433. var testedPosition = vectorPositions[realPos];
  33434. for (var j = 0; j < realPos; ++j) {
  33435. var againstPosition = vectorPositions[j];
  33436. if (testedPosition.equals(againstPosition)) {
  33437. dupes[realPos] = j;
  33438. break;
  33439. }
  33440. }
  33441. }, function () {
  33442. for (var i = 0; i < indices.length; ++i) {
  33443. indices[i] = dupes[indices[i]] || indices[i];
  33444. }
  33445. //indices are now reordered
  33446. var originalSubMeshes = _this.subMeshes.slice(0);
  33447. _this.setIndices(indices);
  33448. _this.subMeshes = originalSubMeshes;
  33449. if (successCallback) {
  33450. successCallback(_this);
  33451. }
  33452. });
  33453. return this;
  33454. };
  33455. Mesh.prototype.serialize = function (serializationObject) {
  33456. serializationObject.name = this.name;
  33457. serializationObject.id = this.id;
  33458. serializationObject.type = this.getClassName();
  33459. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33460. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33461. }
  33462. serializationObject.position = this.position.asArray();
  33463. if (this.rotationQuaternion) {
  33464. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33465. }
  33466. else if (this.rotation) {
  33467. serializationObject.rotation = this.rotation.asArray();
  33468. }
  33469. serializationObject.scaling = this.scaling.asArray();
  33470. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33471. serializationObject.isEnabled = this.isEnabled(false);
  33472. serializationObject.isVisible = this.isVisible;
  33473. serializationObject.infiniteDistance = this.infiniteDistance;
  33474. serializationObject.pickable = this.isPickable;
  33475. serializationObject.receiveShadows = this.receiveShadows;
  33476. serializationObject.billboardMode = this.billboardMode;
  33477. serializationObject.visibility = this.visibility;
  33478. serializationObject.checkCollisions = this.checkCollisions;
  33479. serializationObject.isBlocker = this.isBlocker;
  33480. // Parent
  33481. if (this.parent) {
  33482. serializationObject.parentId = this.parent.id;
  33483. }
  33484. // Geometry
  33485. serializationObject.isUnIndexed = this.isUnIndexed;
  33486. var geometry = this._geometry;
  33487. if (geometry) {
  33488. var geometryId = geometry.id;
  33489. serializationObject.geometryId = geometryId;
  33490. // SubMeshes
  33491. serializationObject.subMeshes = [];
  33492. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33493. var subMesh = this.subMeshes[subIndex];
  33494. serializationObject.subMeshes.push({
  33495. materialIndex: subMesh.materialIndex,
  33496. verticesStart: subMesh.verticesStart,
  33497. verticesCount: subMesh.verticesCount,
  33498. indexStart: subMesh.indexStart,
  33499. indexCount: subMesh.indexCount
  33500. });
  33501. }
  33502. }
  33503. // Material
  33504. if (this.material) {
  33505. serializationObject.materialId = this.material.id;
  33506. }
  33507. else {
  33508. this.material = null;
  33509. }
  33510. // Morph targets
  33511. if (this.morphTargetManager) {
  33512. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33513. }
  33514. // Skeleton
  33515. if (this.skeleton) {
  33516. serializationObject.skeletonId = this.skeleton.id;
  33517. }
  33518. // Physics
  33519. //TODO implement correct serialization for physics impostors.
  33520. var impostor = this.getPhysicsImpostor();
  33521. if (impostor) {
  33522. serializationObject.physicsMass = impostor.getParam("mass");
  33523. serializationObject.physicsFriction = impostor.getParam("friction");
  33524. serializationObject.physicsRestitution = impostor.getParam("mass");
  33525. serializationObject.physicsImpostor = impostor.type;
  33526. }
  33527. // Metadata
  33528. if (this.metadata) {
  33529. serializationObject.metadata = this.metadata;
  33530. }
  33531. // Instances
  33532. serializationObject.instances = [];
  33533. for (var index = 0; index < this.instances.length; index++) {
  33534. var instance = this.instances[index];
  33535. var serializationInstance = {
  33536. name: instance.name,
  33537. id: instance.id,
  33538. position: instance.position.asArray(),
  33539. scaling: instance.scaling.asArray()
  33540. };
  33541. if (instance.rotationQuaternion) {
  33542. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33543. }
  33544. else if (instance.rotation) {
  33545. serializationInstance.rotation = instance.rotation.asArray();
  33546. }
  33547. serializationObject.instances.push(serializationInstance);
  33548. // Animations
  33549. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33550. serializationInstance.ranges = instance.serializeAnimationRanges();
  33551. }
  33552. //
  33553. // Animations
  33554. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33555. serializationObject.ranges = this.serializeAnimationRanges();
  33556. // Layer mask
  33557. serializationObject.layerMask = this.layerMask;
  33558. // Alpha
  33559. serializationObject.alphaIndex = this.alphaIndex;
  33560. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33561. // Overlay
  33562. serializationObject.overlayAlpha = this.overlayAlpha;
  33563. serializationObject.overlayColor = this.overlayColor.asArray();
  33564. serializationObject.renderOverlay = this.renderOverlay;
  33565. // Fog
  33566. serializationObject.applyFog = this.applyFog;
  33567. // Action Manager
  33568. if (this.actionManager) {
  33569. serializationObject.actions = this.actionManager.serialize(this.name);
  33570. }
  33571. };
  33572. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33573. if (!this.geometry) {
  33574. return;
  33575. }
  33576. this._markSubMeshesAsAttributesDirty();
  33577. var morphTargetManager = this._morphTargetManager;
  33578. if (morphTargetManager && morphTargetManager.vertexCount) {
  33579. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33580. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33581. this.morphTargetManager = null;
  33582. return;
  33583. }
  33584. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33585. var morphTarget = morphTargetManager.getActiveTarget(index);
  33586. var positions = morphTarget.getPositions();
  33587. if (!positions) {
  33588. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33589. return;
  33590. }
  33591. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33592. var normals = morphTarget.getNormals();
  33593. if (normals) {
  33594. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33595. }
  33596. var tangents = morphTarget.getTangents();
  33597. if (tangents) {
  33598. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33599. }
  33600. }
  33601. }
  33602. else {
  33603. var index = 0;
  33604. // Positions
  33605. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33606. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33607. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33608. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33609. }
  33610. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33611. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33612. }
  33613. index++;
  33614. }
  33615. }
  33616. };
  33617. // Statics
  33618. /**
  33619. * Returns a new Mesh object parsed from the source provided.
  33620. * The parameter `parsedMesh` is the source.
  33621. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33622. */
  33623. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33624. var mesh;
  33625. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33626. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33627. }
  33628. else {
  33629. mesh = new Mesh(parsedMesh.name, scene);
  33630. }
  33631. mesh.id = parsedMesh.id;
  33632. if (BABYLON.Tags) {
  33633. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33634. }
  33635. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33636. if (parsedMesh.metadata !== undefined) {
  33637. mesh.metadata = parsedMesh.metadata;
  33638. }
  33639. if (parsedMesh.rotationQuaternion) {
  33640. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33641. }
  33642. else if (parsedMesh.rotation) {
  33643. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33644. }
  33645. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33646. if (parsedMesh.localMatrix) {
  33647. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33648. }
  33649. else if (parsedMesh.pivotMatrix) {
  33650. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33651. }
  33652. mesh.setEnabled(parsedMesh.isEnabled);
  33653. mesh.isVisible = parsedMesh.isVisible;
  33654. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33655. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33656. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33657. if (parsedMesh.applyFog !== undefined) {
  33658. mesh.applyFog = parsedMesh.applyFog;
  33659. }
  33660. if (parsedMesh.pickable !== undefined) {
  33661. mesh.isPickable = parsedMesh.pickable;
  33662. }
  33663. if (parsedMesh.alphaIndex !== undefined) {
  33664. mesh.alphaIndex = parsedMesh.alphaIndex;
  33665. }
  33666. mesh.receiveShadows = parsedMesh.receiveShadows;
  33667. mesh.billboardMode = parsedMesh.billboardMode;
  33668. if (parsedMesh.visibility !== undefined) {
  33669. mesh.visibility = parsedMesh.visibility;
  33670. }
  33671. mesh.checkCollisions = parsedMesh.checkCollisions;
  33672. if (parsedMesh.isBlocker !== undefined) {
  33673. mesh.isBlocker = parsedMesh.isBlocker;
  33674. }
  33675. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33676. // freezeWorldMatrix
  33677. if (parsedMesh.freezeWorldMatrix) {
  33678. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33679. }
  33680. // Parent
  33681. if (parsedMesh.parentId) {
  33682. mesh._waitingParentId = parsedMesh.parentId;
  33683. }
  33684. // Actions
  33685. if (parsedMesh.actions !== undefined) {
  33686. mesh._waitingActions = parsedMesh.actions;
  33687. }
  33688. // Overlay
  33689. if (parsedMesh.overlayAlpha !== undefined) {
  33690. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33691. }
  33692. if (parsedMesh.overlayColor !== undefined) {
  33693. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33694. }
  33695. if (parsedMesh.renderOverlay !== undefined) {
  33696. mesh.renderOverlay = parsedMesh.renderOverlay;
  33697. }
  33698. // Geometry
  33699. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33700. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33701. if (parsedMesh.delayLoadingFile) {
  33702. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33703. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33704. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33705. if (parsedMesh._binaryInfo) {
  33706. mesh._binaryInfo = parsedMesh._binaryInfo;
  33707. }
  33708. mesh._delayInfo = [];
  33709. if (parsedMesh.hasUVs) {
  33710. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33711. }
  33712. if (parsedMesh.hasUVs2) {
  33713. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33714. }
  33715. if (parsedMesh.hasUVs3) {
  33716. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33717. }
  33718. if (parsedMesh.hasUVs4) {
  33719. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33720. }
  33721. if (parsedMesh.hasUVs5) {
  33722. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33723. }
  33724. if (parsedMesh.hasUVs6) {
  33725. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33726. }
  33727. if (parsedMesh.hasColors) {
  33728. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33729. }
  33730. if (parsedMesh.hasMatricesIndices) {
  33731. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33732. }
  33733. if (parsedMesh.hasMatricesWeights) {
  33734. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33735. }
  33736. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33737. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33738. mesh._checkDelayState();
  33739. }
  33740. }
  33741. else {
  33742. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33743. }
  33744. // Material
  33745. if (parsedMesh.materialId) {
  33746. mesh.setMaterialByID(parsedMesh.materialId);
  33747. }
  33748. else {
  33749. mesh.material = null;
  33750. }
  33751. // Morph targets
  33752. if (parsedMesh.morphTargetManagerId > -1) {
  33753. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33754. }
  33755. // Skeleton
  33756. if (parsedMesh.skeletonId > -1) {
  33757. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33758. if (parsedMesh.numBoneInfluencers) {
  33759. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33760. }
  33761. }
  33762. // Animations
  33763. if (parsedMesh.animations) {
  33764. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33765. var parsedAnimation = parsedMesh.animations[animationIndex];
  33766. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33767. }
  33768. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33769. }
  33770. if (parsedMesh.autoAnimate) {
  33771. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33772. }
  33773. // Layer Mask
  33774. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33775. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33776. }
  33777. else {
  33778. mesh.layerMask = 0x0FFFFFFF;
  33779. }
  33780. // Physics
  33781. if (parsedMesh.physicsImpostor) {
  33782. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33783. mass: parsedMesh.physicsMass,
  33784. friction: parsedMesh.physicsFriction,
  33785. restitution: parsedMesh.physicsRestitution
  33786. }, scene);
  33787. }
  33788. // Instances
  33789. if (parsedMesh.instances) {
  33790. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33791. var parsedInstance = parsedMesh.instances[index];
  33792. var instance = mesh.createInstance(parsedInstance.name);
  33793. if (parsedInstance.id) {
  33794. instance.id = parsedInstance.id;
  33795. }
  33796. if (BABYLON.Tags) {
  33797. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33798. }
  33799. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33800. if (parsedInstance.parentId) {
  33801. instance._waitingParentId = parsedInstance.parentId;
  33802. }
  33803. if (parsedInstance.rotationQuaternion) {
  33804. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33805. }
  33806. else if (parsedInstance.rotation) {
  33807. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33808. }
  33809. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33810. instance.checkCollisions = mesh.checkCollisions;
  33811. if (parsedMesh.animations) {
  33812. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33813. parsedAnimation = parsedMesh.animations[animationIndex];
  33814. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33815. }
  33816. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33817. if (parsedMesh.autoAnimate) {
  33818. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33819. }
  33820. }
  33821. }
  33822. }
  33823. return mesh;
  33824. };
  33825. /**
  33826. * Creates a ribbon mesh.
  33827. * Please consider using the same method from the MeshBuilder class instead.
  33828. * 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.
  33829. *
  33830. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33831. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33832. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33833. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33834. * 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.
  33835. * 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.
  33836. * 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
  33837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33838. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33840. */
  33841. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33842. if (closeArray === void 0) { closeArray = false; }
  33843. if (updatable === void 0) { updatable = false; }
  33844. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33845. pathArray: pathArray,
  33846. closeArray: closeArray,
  33847. closePath: closePath,
  33848. offset: offset,
  33849. updatable: updatable,
  33850. sideOrientation: sideOrientation,
  33851. instance: instance
  33852. }, scene);
  33853. };
  33854. /**
  33855. * Creates a plane polygonal mesh. By default, this is a disc.
  33856. * Please consider using the same method from the MeshBuilder class instead.
  33857. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33858. * 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.
  33859. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33860. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33862. */
  33863. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33864. if (scene === void 0) { scene = null; }
  33865. var options = {
  33866. radius: radius,
  33867. tessellation: tessellation,
  33868. sideOrientation: sideOrientation,
  33869. updatable: updatable
  33870. };
  33871. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33872. };
  33873. /**
  33874. * Creates a box mesh.
  33875. * Please consider using the same method from the MeshBuilder class instead.
  33876. * The parameter `size` sets the size (float) of each box side (default 1).
  33877. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33878. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33879. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33880. */
  33881. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33882. if (scene === void 0) { scene = null; }
  33883. var options = {
  33884. size: size,
  33885. sideOrientation: sideOrientation,
  33886. updatable: updatable
  33887. };
  33888. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33889. };
  33890. /**
  33891. * Creates a sphere mesh.
  33892. * Please consider using the same method from the MeshBuilder class instead.
  33893. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33894. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33895. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33896. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33898. */
  33899. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33900. var options = {
  33901. segments: segments,
  33902. diameterX: diameter,
  33903. diameterY: diameter,
  33904. diameterZ: diameter,
  33905. sideOrientation: sideOrientation,
  33906. updatable: updatable
  33907. };
  33908. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33909. };
  33910. /**
  33911. * Creates a cylinder or a cone mesh.
  33912. * Please consider using the same method from the MeshBuilder class instead.
  33913. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33914. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33915. * 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.
  33916. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33917. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33918. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33919. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33921. */
  33922. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33923. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33924. if (scene !== undefined) {
  33925. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33926. updatable = scene;
  33927. }
  33928. scene = subdivisions;
  33929. subdivisions = 1;
  33930. }
  33931. var options = {
  33932. height: height,
  33933. diameterTop: diameterTop,
  33934. diameterBottom: diameterBottom,
  33935. tessellation: tessellation,
  33936. subdivisions: subdivisions,
  33937. sideOrientation: sideOrientation,
  33938. updatable: updatable
  33939. };
  33940. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33941. };
  33942. // Torus (Code from SharpDX.org)
  33943. /**
  33944. * Creates a torus mesh.
  33945. * Please consider using the same method from the MeshBuilder class instead.
  33946. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33947. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33948. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33950. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33952. */
  33953. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33954. var options = {
  33955. diameter: diameter,
  33956. thickness: thickness,
  33957. tessellation: tessellation,
  33958. sideOrientation: sideOrientation,
  33959. updatable: updatable
  33960. };
  33961. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33962. };
  33963. /**
  33964. * Creates a torus knot mesh.
  33965. * Please consider using the same method from the MeshBuilder class instead.
  33966. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33967. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33968. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33969. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33971. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33973. */
  33974. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33975. var options = {
  33976. radius: radius,
  33977. tube: tube,
  33978. radialSegments: radialSegments,
  33979. tubularSegments: tubularSegments,
  33980. p: p,
  33981. q: q,
  33982. sideOrientation: sideOrientation,
  33983. updatable: updatable
  33984. };
  33985. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33986. };
  33987. /**
  33988. * Creates a line mesh.
  33989. * Please consider using the same method from the MeshBuilder class instead.
  33990. * 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.
  33991. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33992. * The parameter `points` is an array successive Vector3.
  33993. * 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
  33994. * When updating an instance, remember that only point positions can change, not the number of points.
  33995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33996. */
  33997. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33998. if (scene === void 0) { scene = null; }
  33999. if (updatable === void 0) { updatable = false; }
  34000. if (instance === void 0) { instance = null; }
  34001. var options = {
  34002. points: points,
  34003. updatable: updatable,
  34004. instance: instance
  34005. };
  34006. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34007. };
  34008. /**
  34009. * Creates a dashed line mesh.
  34010. * Please consider using the same method from the MeshBuilder class instead.
  34011. * 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.
  34012. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  34013. * The parameter `points` is an array successive Vector3.
  34014. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  34015. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  34016. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  34017. * 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
  34018. * When updating an instance, remember that only point positions can change, not the number of points.
  34019. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34020. */
  34021. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34022. if (scene === void 0) { scene = null; }
  34023. var options = {
  34024. points: points,
  34025. dashSize: dashSize,
  34026. gapSize: gapSize,
  34027. dashNb: dashNb,
  34028. updatable: updatable,
  34029. instance: instance
  34030. };
  34031. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34032. };
  34033. /**
  34034. * Creates a polygon mesh.
  34035. * Please consider using the same method from the MeshBuilder class instead.
  34036. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34037. * 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.
  34038. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34040. * Remember you can only change the shape positions, not their number when updating a polygon.
  34041. */
  34042. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34043. var options = {
  34044. shape: shape,
  34045. holes: holes,
  34046. updatable: updatable,
  34047. sideOrientation: sideOrientation
  34048. };
  34049. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34050. };
  34051. /**
  34052. * Creates an extruded polygon mesh, with depth in the Y direction.
  34053. * Please consider using the same method from the MeshBuilder class instead.
  34054. */
  34055. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34056. var options = {
  34057. shape: shape,
  34058. holes: holes,
  34059. depth: depth,
  34060. updatable: updatable,
  34061. sideOrientation: sideOrientation
  34062. };
  34063. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34064. };
  34065. /**
  34066. * Creates an extruded shape mesh.
  34067. * 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.
  34068. * Please consider using the same method from the MeshBuilder class instead.
  34069. *
  34070. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34071. * 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
  34072. * extruded along the Z axis.
  34073. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34074. * 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.
  34075. * The parameter `scale` (float, default 1) is the value to scale the shape.
  34076. * 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
  34077. * 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
  34078. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34080. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34082. */
  34083. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34084. if (scene === void 0) { scene = null; }
  34085. var options = {
  34086. shape: shape,
  34087. path: path,
  34088. scale: scale,
  34089. rotation: rotation,
  34090. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34091. sideOrientation: sideOrientation,
  34092. instance: instance,
  34093. updatable: updatable
  34094. };
  34095. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34096. };
  34097. /**
  34098. * Creates an custom extruded shape mesh.
  34099. * 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.
  34100. * Please consider using the same method from the MeshBuilder class instead.
  34101. *
  34102. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34103. * 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
  34104. * extruded along the Z axis.
  34105. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34106. * 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
  34107. * and the distance of this point from the begining of the path :
  34108. * ```javascript
  34109. * var rotationFunction = function(i, distance) {
  34110. * // do things
  34111. * return rotationValue; }
  34112. * ```
  34113. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34114. * 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
  34115. * and the distance of this point from the begining of the path :
  34116. * ```javascript
  34117. * var scaleFunction = function(i, distance) {
  34118. * // do things
  34119. * return scaleValue;}
  34120. * ```
  34121. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34122. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34123. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34124. * 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
  34125. * 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
  34126. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34128. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34130. */
  34131. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34132. var options = {
  34133. shape: shape,
  34134. path: path,
  34135. scaleFunction: scaleFunction,
  34136. rotationFunction: rotationFunction,
  34137. ribbonCloseArray: ribbonCloseArray,
  34138. ribbonClosePath: ribbonClosePath,
  34139. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34140. sideOrientation: sideOrientation,
  34141. instance: instance,
  34142. updatable: updatable
  34143. };
  34144. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34145. };
  34146. /**
  34147. * Creates lathe mesh.
  34148. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34149. * Please consider using the same method from the MeshBuilder class instead.
  34150. * 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
  34151. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34152. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34153. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34154. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34155. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34157. */
  34158. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34159. var options = {
  34160. shape: shape,
  34161. radius: radius,
  34162. tessellation: tessellation,
  34163. sideOrientation: sideOrientation,
  34164. updatable: updatable
  34165. };
  34166. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34167. };
  34168. /**
  34169. * Creates a plane mesh.
  34170. * Please consider using the same method from the MeshBuilder class instead.
  34171. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34173. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34175. */
  34176. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34177. var options = {
  34178. size: size,
  34179. width: size,
  34180. height: size,
  34181. sideOrientation: sideOrientation,
  34182. updatable: updatable
  34183. };
  34184. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34185. };
  34186. /**
  34187. * Creates a ground mesh.
  34188. * Please consider using the same method from the MeshBuilder class instead.
  34189. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34190. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34192. */
  34193. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34194. var options = {
  34195. width: width,
  34196. height: height,
  34197. subdivisions: subdivisions,
  34198. updatable: updatable
  34199. };
  34200. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34201. };
  34202. /**
  34203. * Creates a tiled ground mesh.
  34204. * Please consider using the same method from the MeshBuilder class instead.
  34205. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34206. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34207. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34208. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34209. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34210. * numbers of subdivisions on the ground width and height of each tile.
  34211. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34212. */
  34213. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34214. var options = {
  34215. xmin: xmin,
  34216. zmin: zmin,
  34217. xmax: xmax,
  34218. zmax: zmax,
  34219. subdivisions: subdivisions,
  34220. precision: precision,
  34221. updatable: updatable
  34222. };
  34223. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34224. };
  34225. /**
  34226. * Creates a ground mesh from a height map.
  34227. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34228. * Please consider using the same method from the MeshBuilder class instead.
  34229. * The parameter `url` sets the URL of the height map image resource.
  34230. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34231. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34232. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34233. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34234. * 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).
  34235. * This function is passed the newly built mesh :
  34236. * ```javascript
  34237. * function(mesh) { // do things
  34238. * return; }
  34239. * ```
  34240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34241. */
  34242. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34243. var options = {
  34244. width: width,
  34245. height: height,
  34246. subdivisions: subdivisions,
  34247. minHeight: minHeight,
  34248. maxHeight: maxHeight,
  34249. updatable: updatable,
  34250. onReady: onReady
  34251. };
  34252. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34253. };
  34254. /**
  34255. * Creates a tube mesh.
  34256. * 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.
  34257. * Please consider using the same method from the MeshBuilder class instead.
  34258. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34259. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34260. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34261. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34262. * 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.
  34263. * It must return a radius value (positive float) :
  34264. * ```javascript
  34265. * var radiusFunction = function(i, distance) {
  34266. * // do things
  34267. * return radius; }
  34268. * ```
  34269. * 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
  34270. * 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
  34271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34272. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34274. */
  34275. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34276. var options = {
  34277. path: path,
  34278. radius: radius,
  34279. tessellation: tessellation,
  34280. radiusFunction: radiusFunction,
  34281. arc: 1,
  34282. cap: cap,
  34283. updatable: updatable,
  34284. sideOrientation: sideOrientation,
  34285. instance: instance
  34286. };
  34287. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34288. };
  34289. /**
  34290. * Creates a polyhedron mesh.
  34291. * Please consider using the same method from the MeshBuilder class instead.
  34292. * 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
  34293. * to choose the wanted type.
  34294. * The parameter `size` (positive float, default 1) sets the polygon size.
  34295. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34296. * 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`.
  34297. * 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
  34298. * 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)`).
  34299. * 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
  34300. * 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.
  34301. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34302. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34304. */
  34305. Mesh.CreatePolyhedron = function (name, options, scene) {
  34306. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34307. };
  34308. /**
  34309. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34310. * Please consider using the same method from the MeshBuilder class instead.
  34311. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34312. * 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`).
  34313. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34314. * 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.
  34315. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34316. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34318. */
  34319. Mesh.CreateIcoSphere = function (name, options, scene) {
  34320. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34321. };
  34322. /**
  34323. * Creates a decal mesh.
  34324. * Please consider using the same method from the MeshBuilder class instead.
  34325. * 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.
  34326. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34327. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34328. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34329. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34330. */
  34331. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34332. var options = {
  34333. position: position,
  34334. normal: normal,
  34335. size: size,
  34336. angle: angle
  34337. };
  34338. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34339. };
  34340. // Skeletons
  34341. /**
  34342. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34343. */
  34344. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34345. if (!this._sourcePositions) {
  34346. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34347. if (!source) {
  34348. return this._sourcePositions;
  34349. }
  34350. this._sourcePositions = new Float32Array(source);
  34351. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34352. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34353. }
  34354. }
  34355. return this._sourcePositions;
  34356. };
  34357. /**
  34358. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34359. */
  34360. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34361. if (!this._sourceNormals) {
  34362. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34363. if (!source) {
  34364. return this._sourceNormals;
  34365. }
  34366. this._sourceNormals = new Float32Array(source);
  34367. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34368. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34369. }
  34370. }
  34371. return this._sourceNormals;
  34372. };
  34373. /**
  34374. * Updates the vertex buffer by applying transformation from the bones.
  34375. * Returns the Mesh.
  34376. *
  34377. * @param {skeleton} skeleton to apply
  34378. */
  34379. Mesh.prototype.applySkeleton = function (skeleton) {
  34380. if (!this.geometry) {
  34381. return this;
  34382. }
  34383. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34384. return this;
  34385. }
  34386. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34387. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34388. return this;
  34389. }
  34390. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34391. return this;
  34392. }
  34393. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34394. return this;
  34395. }
  34396. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34397. return this;
  34398. }
  34399. if (!this._sourcePositions) {
  34400. var submeshes = this.subMeshes.slice();
  34401. this.setPositionsForCPUSkinning();
  34402. this.subMeshes = submeshes;
  34403. }
  34404. if (!this._sourceNormals) {
  34405. this.setNormalsForCPUSkinning();
  34406. }
  34407. // positionsData checks for not being Float32Array will only pass at most once
  34408. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34409. if (!positionsData) {
  34410. return this;
  34411. }
  34412. if (!(positionsData instanceof Float32Array)) {
  34413. positionsData = new Float32Array(positionsData);
  34414. }
  34415. // normalsData checks for not being Float32Array will only pass at most once
  34416. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34417. if (!normalsData) {
  34418. return this;
  34419. }
  34420. if (!(normalsData instanceof Float32Array)) {
  34421. normalsData = new Float32Array(normalsData);
  34422. }
  34423. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34424. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34425. if (!matricesWeightsData || !matricesIndicesData) {
  34426. return this;
  34427. }
  34428. var needExtras = this.numBoneInfluencers > 4;
  34429. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34430. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34431. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34432. var tempVector3 = BABYLON.Vector3.Zero();
  34433. var finalMatrix = new BABYLON.Matrix();
  34434. var tempMatrix = new BABYLON.Matrix();
  34435. var matWeightIdx = 0;
  34436. var inf;
  34437. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34438. var weight;
  34439. for (inf = 0; inf < 4; inf++) {
  34440. weight = matricesWeightsData[matWeightIdx + inf];
  34441. if (weight > 0) {
  34442. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34443. finalMatrix.addToSelf(tempMatrix);
  34444. }
  34445. else
  34446. break;
  34447. }
  34448. if (needExtras) {
  34449. for (inf = 0; inf < 4; inf++) {
  34450. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34451. if (weight > 0) {
  34452. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34453. finalMatrix.addToSelf(tempMatrix);
  34454. }
  34455. else
  34456. break;
  34457. }
  34458. }
  34459. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34460. tempVector3.toArray(positionsData, index);
  34461. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34462. tempVector3.toArray(normalsData, index);
  34463. finalMatrix.reset();
  34464. }
  34465. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34466. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34467. return this;
  34468. };
  34469. // Tools
  34470. /**
  34471. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34472. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34473. */
  34474. Mesh.MinMax = function (meshes) {
  34475. var minVector = null;
  34476. var maxVector = null;
  34477. meshes.forEach(function (mesh, index, array) {
  34478. var boundingInfo = mesh.getBoundingInfo();
  34479. var boundingBox = boundingInfo.boundingBox;
  34480. if (!minVector || !maxVector) {
  34481. minVector = boundingBox.minimumWorld;
  34482. maxVector = boundingBox.maximumWorld;
  34483. }
  34484. else {
  34485. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34486. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34487. }
  34488. });
  34489. if (!minVector || !maxVector) {
  34490. return {
  34491. min: BABYLON.Vector3.Zero(),
  34492. max: BABYLON.Vector3.Zero()
  34493. };
  34494. }
  34495. return {
  34496. min: minVector,
  34497. max: maxVector
  34498. };
  34499. };
  34500. /**
  34501. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34502. */
  34503. Mesh.Center = function (meshesOrMinMaxVector) {
  34504. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34505. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34506. };
  34507. /**
  34508. * Merge the array of meshes into a single mesh for performance reasons.
  34509. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34510. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34511. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34512. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34513. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34514. */
  34515. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34516. if (disposeSource === void 0) { disposeSource = true; }
  34517. var index;
  34518. if (!allow32BitsIndices) {
  34519. var totalVertices = 0;
  34520. // Counting vertices
  34521. for (index = 0; index < meshes.length; index++) {
  34522. if (meshes[index]) {
  34523. totalVertices += meshes[index].getTotalVertices();
  34524. if (totalVertices > 65536) {
  34525. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34526. return null;
  34527. }
  34528. }
  34529. }
  34530. }
  34531. // Merge
  34532. var vertexData = null;
  34533. var otherVertexData;
  34534. var indiceArray = new Array();
  34535. var source = null;
  34536. for (index = 0; index < meshes.length; index++) {
  34537. if (meshes[index]) {
  34538. meshes[index].computeWorldMatrix(true);
  34539. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34540. otherVertexData.transform(meshes[index].getWorldMatrix());
  34541. if (vertexData) {
  34542. vertexData.merge(otherVertexData);
  34543. }
  34544. else {
  34545. vertexData = otherVertexData;
  34546. source = meshes[index];
  34547. }
  34548. if (subdivideWithSubMeshes) {
  34549. indiceArray.push(meshes[index].getTotalIndices());
  34550. }
  34551. }
  34552. }
  34553. source = source;
  34554. if (!meshSubclass) {
  34555. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34556. }
  34557. vertexData.applyToMesh(meshSubclass);
  34558. // Setting properties
  34559. meshSubclass.material = source.material;
  34560. meshSubclass.checkCollisions = source.checkCollisions;
  34561. // Cleaning
  34562. if (disposeSource) {
  34563. for (index = 0; index < meshes.length; index++) {
  34564. if (meshes[index]) {
  34565. meshes[index].dispose();
  34566. }
  34567. }
  34568. }
  34569. // Subdivide
  34570. if (subdivideWithSubMeshes) {
  34571. //-- removal of global submesh
  34572. meshSubclass.releaseSubMeshes();
  34573. index = 0;
  34574. var offset = 0;
  34575. //-- apply subdivision according to index table
  34576. while (index < indiceArray.length) {
  34577. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34578. offset += indiceArray[index];
  34579. index++;
  34580. }
  34581. }
  34582. return meshSubclass;
  34583. };
  34584. // Consts
  34585. Mesh._FRONTSIDE = 0;
  34586. Mesh._BACKSIDE = 1;
  34587. Mesh._DOUBLESIDE = 2;
  34588. Mesh._DEFAULTSIDE = 0;
  34589. Mesh._NO_CAP = 0;
  34590. Mesh._CAP_START = 1;
  34591. Mesh._CAP_END = 2;
  34592. Mesh._CAP_ALL = 3;
  34593. return Mesh;
  34594. }(BABYLON.AbstractMesh));
  34595. BABYLON.Mesh = Mesh;
  34596. })(BABYLON || (BABYLON = {}));
  34597. //# sourceMappingURL=babylon.mesh.js.map
  34598. var BABYLON;
  34599. (function (BABYLON) {
  34600. var BaseSubMesh = /** @class */ (function () {
  34601. function BaseSubMesh() {
  34602. }
  34603. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34604. get: function () {
  34605. return this._materialEffect;
  34606. },
  34607. enumerable: true,
  34608. configurable: true
  34609. });
  34610. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34611. if (defines === void 0) { defines = null; }
  34612. if (this._materialEffect === effect) {
  34613. if (!effect) {
  34614. this._materialDefines = null;
  34615. }
  34616. return;
  34617. }
  34618. this._materialDefines = defines;
  34619. this._materialEffect = effect;
  34620. };
  34621. return BaseSubMesh;
  34622. }());
  34623. BABYLON.BaseSubMesh = BaseSubMesh;
  34624. var SubMesh = /** @class */ (function (_super) {
  34625. __extends(SubMesh, _super);
  34626. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34627. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34628. var _this = _super.call(this) || this;
  34629. _this.materialIndex = materialIndex;
  34630. _this.verticesStart = verticesStart;
  34631. _this.verticesCount = verticesCount;
  34632. _this.indexStart = indexStart;
  34633. _this.indexCount = indexCount;
  34634. _this._renderId = 0;
  34635. _this._mesh = mesh;
  34636. _this._renderingMesh = renderingMesh || mesh;
  34637. mesh.subMeshes.push(_this);
  34638. _this._trianglePlanes = [];
  34639. _this._id = mesh.subMeshes.length - 1;
  34640. if (createBoundingBox) {
  34641. _this.refreshBoundingInfo();
  34642. mesh.computeWorldMatrix(true);
  34643. }
  34644. return _this;
  34645. }
  34646. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34647. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34648. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34649. };
  34650. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34651. get: function () {
  34652. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34653. },
  34654. enumerable: true,
  34655. configurable: true
  34656. });
  34657. /**
  34658. * Returns the submesh BoudingInfo object.
  34659. */
  34660. SubMesh.prototype.getBoundingInfo = function () {
  34661. if (this.IsGlobal) {
  34662. return this._mesh.getBoundingInfo();
  34663. }
  34664. return this._boundingInfo;
  34665. };
  34666. /**
  34667. * Sets the submesh BoundingInfo.
  34668. * Return the SubMesh.
  34669. */
  34670. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34671. this._boundingInfo = boundingInfo;
  34672. return this;
  34673. };
  34674. /**
  34675. * Returns the mesh of the current submesh.
  34676. */
  34677. SubMesh.prototype.getMesh = function () {
  34678. return this._mesh;
  34679. };
  34680. /**
  34681. * Returns the rendering mesh of the submesh.
  34682. */
  34683. SubMesh.prototype.getRenderingMesh = function () {
  34684. return this._renderingMesh;
  34685. };
  34686. /**
  34687. * Returns the submesh material.
  34688. */
  34689. SubMesh.prototype.getMaterial = function () {
  34690. var rootMaterial = this._renderingMesh.material;
  34691. if (rootMaterial === null || rootMaterial === undefined) {
  34692. return this._mesh.getScene().defaultMaterial;
  34693. }
  34694. else if (rootMaterial.getSubMaterial) {
  34695. var multiMaterial = rootMaterial;
  34696. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34697. if (this._currentMaterial !== effectiveMaterial) {
  34698. this._currentMaterial = effectiveMaterial;
  34699. this._materialDefines = null;
  34700. }
  34701. return effectiveMaterial;
  34702. }
  34703. return rootMaterial;
  34704. };
  34705. // Methods
  34706. /**
  34707. * Sets a new updated BoundingInfo object to the submesh.
  34708. * Returns the SubMesh.
  34709. */
  34710. SubMesh.prototype.refreshBoundingInfo = function () {
  34711. this._lastColliderWorldVertices = null;
  34712. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34713. return this;
  34714. }
  34715. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34716. if (!data) {
  34717. this._boundingInfo = this._mesh.getBoundingInfo();
  34718. return this;
  34719. }
  34720. var indices = this._renderingMesh.getIndices();
  34721. var extend;
  34722. //is this the only submesh?
  34723. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34724. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34725. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34726. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34727. }
  34728. else {
  34729. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34730. }
  34731. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34732. return this;
  34733. };
  34734. SubMesh.prototype._checkCollision = function (collider) {
  34735. var boundingInfo = this.getBoundingInfo();
  34736. return boundingInfo._checkCollision(collider);
  34737. };
  34738. /**
  34739. * Updates the submesh BoundingInfo.
  34740. * Returns the Submesh.
  34741. */
  34742. SubMesh.prototype.updateBoundingInfo = function (world) {
  34743. var boundingInfo = this.getBoundingInfo();
  34744. if (!boundingInfo) {
  34745. this.refreshBoundingInfo();
  34746. boundingInfo = this.getBoundingInfo();
  34747. }
  34748. boundingInfo.update(world);
  34749. return this;
  34750. };
  34751. /**
  34752. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34753. * Boolean returned.
  34754. */
  34755. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34756. var boundingInfo = this.getBoundingInfo();
  34757. if (!boundingInfo) {
  34758. return false;
  34759. }
  34760. return boundingInfo.isInFrustum(frustumPlanes);
  34761. };
  34762. /**
  34763. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34764. * Boolean returned.
  34765. */
  34766. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34767. var boundingInfo = this.getBoundingInfo();
  34768. if (!boundingInfo) {
  34769. return false;
  34770. }
  34771. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34772. };
  34773. /**
  34774. * Renders the submesh.
  34775. * Returns it.
  34776. */
  34777. SubMesh.prototype.render = function (enableAlphaMode) {
  34778. this._renderingMesh.render(this, enableAlphaMode);
  34779. return this;
  34780. };
  34781. /**
  34782. * Returns a new Index Buffer.
  34783. * Type returned : WebGLBuffer.
  34784. */
  34785. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34786. if (!this._linesIndexBuffer) {
  34787. var linesIndices = [];
  34788. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34789. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34790. }
  34791. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34792. this.linesIndexCount = linesIndices.length;
  34793. }
  34794. return this._linesIndexBuffer;
  34795. };
  34796. /**
  34797. * True is the passed Ray intersects the submesh bounding box.
  34798. * Boolean returned.
  34799. */
  34800. SubMesh.prototype.canIntersects = function (ray) {
  34801. var boundingInfo = this.getBoundingInfo();
  34802. if (!boundingInfo) {
  34803. return false;
  34804. }
  34805. return ray.intersectsBox(boundingInfo.boundingBox);
  34806. };
  34807. /**
  34808. * Returns an object IntersectionInfo.
  34809. */
  34810. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34811. var intersectInfo = null;
  34812. var material = this.getMaterial();
  34813. if (!material) {
  34814. return null;
  34815. }
  34816. switch (material.fillMode) {
  34817. case BABYLON.Material.PointListDrawMode:
  34818. case BABYLON.Material.LineListDrawMode:
  34819. case BABYLON.Material.LineLoopDrawMode:
  34820. case BABYLON.Material.LineStripDrawMode:
  34821. case BABYLON.Material.TriangleFanDrawMode:
  34822. case BABYLON.Material.TriangleStripDrawMode:
  34823. return null;
  34824. }
  34825. // LineMesh first as it's also a Mesh...
  34826. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34827. var lineMesh = this._mesh;
  34828. // Line test
  34829. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34830. var p0 = positions[indices[index]];
  34831. var p1 = positions[indices[index + 1]];
  34832. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34833. if (length < 0) {
  34834. continue;
  34835. }
  34836. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34837. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34838. if (fastCheck) {
  34839. break;
  34840. }
  34841. }
  34842. }
  34843. }
  34844. else {
  34845. // Triangles test
  34846. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34847. var p0 = positions[indices[index]];
  34848. var p1 = positions[indices[index + 1]];
  34849. var p2 = positions[indices[index + 2]];
  34850. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34851. if (currentIntersectInfo) {
  34852. if (currentIntersectInfo.distance < 0) {
  34853. continue;
  34854. }
  34855. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34856. intersectInfo = currentIntersectInfo;
  34857. intersectInfo.faceId = index / 3;
  34858. if (fastCheck) {
  34859. break;
  34860. }
  34861. }
  34862. }
  34863. }
  34864. }
  34865. return intersectInfo;
  34866. };
  34867. SubMesh.prototype._rebuild = function () {
  34868. if (this._linesIndexBuffer) {
  34869. this._linesIndexBuffer = null;
  34870. }
  34871. };
  34872. // Clone
  34873. /**
  34874. * Creates a new Submesh from the passed Mesh.
  34875. */
  34876. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34877. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34878. if (!this.IsGlobal) {
  34879. var boundingInfo = this.getBoundingInfo();
  34880. if (!boundingInfo) {
  34881. return result;
  34882. }
  34883. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34884. }
  34885. return result;
  34886. };
  34887. // Dispose
  34888. /**
  34889. * Disposes the Submesh.
  34890. * Returns nothing.
  34891. */
  34892. SubMesh.prototype.dispose = function () {
  34893. if (this._linesIndexBuffer) {
  34894. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34895. this._linesIndexBuffer = null;
  34896. }
  34897. // Remove from mesh
  34898. var index = this._mesh.subMeshes.indexOf(this);
  34899. this._mesh.subMeshes.splice(index, 1);
  34900. };
  34901. // Statics
  34902. /**
  34903. * Creates a new Submesh from the passed parameters :
  34904. * - materialIndex (integer) : the index of the main mesh material.
  34905. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34906. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34907. * - mesh (Mesh) : the main mesh to create the submesh from.
  34908. * - renderingMesh (optional Mesh) : rendering mesh.
  34909. */
  34910. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34911. var minVertexIndex = Number.MAX_VALUE;
  34912. var maxVertexIndex = -Number.MAX_VALUE;
  34913. renderingMesh = (renderingMesh || mesh);
  34914. var indices = renderingMesh.getIndices();
  34915. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34916. var vertexIndex = indices[index];
  34917. if (vertexIndex < minVertexIndex)
  34918. minVertexIndex = vertexIndex;
  34919. if (vertexIndex > maxVertexIndex)
  34920. maxVertexIndex = vertexIndex;
  34921. }
  34922. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34923. };
  34924. return SubMesh;
  34925. }(BaseSubMesh));
  34926. BABYLON.SubMesh = SubMesh;
  34927. })(BABYLON || (BABYLON = {}));
  34928. //# sourceMappingURL=babylon.subMesh.js.map
  34929. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34930. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34931. s = arguments[i];
  34932. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34933. t[p] = s[p];
  34934. }
  34935. return t;
  34936. };
  34937. var BABYLON;
  34938. (function (BABYLON) {
  34939. /**
  34940. * Manages the defines for the Material
  34941. */
  34942. var MaterialDefines = /** @class */ (function () {
  34943. function MaterialDefines() {
  34944. this._isDirty = true;
  34945. /** @hidden */
  34946. this._areLightsDirty = true;
  34947. /** @hidden */
  34948. this._areAttributesDirty = true;
  34949. /** @hidden */
  34950. this._areTexturesDirty = true;
  34951. /** @hidden */
  34952. this._areFresnelDirty = true;
  34953. /** @hidden */
  34954. this._areMiscDirty = true;
  34955. /** @hidden */
  34956. this._areImageProcessingDirty = true;
  34957. /** @hidden */
  34958. this._normals = false;
  34959. /** @hidden */
  34960. this._uvs = false;
  34961. /** @hidden */
  34962. this._needNormals = false;
  34963. /** @hidden */
  34964. this._needUVs = false;
  34965. }
  34966. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34967. /**
  34968. * Specifies if the material needs to be re-calculated
  34969. */
  34970. get: function () {
  34971. return this._isDirty;
  34972. },
  34973. enumerable: true,
  34974. configurable: true
  34975. });
  34976. /**
  34977. * Marks the material to indicate that it has been re-calculated
  34978. */
  34979. MaterialDefines.prototype.markAsProcessed = function () {
  34980. this._isDirty = false;
  34981. this._areAttributesDirty = false;
  34982. this._areTexturesDirty = false;
  34983. this._areFresnelDirty = false;
  34984. this._areLightsDirty = false;
  34985. this._areMiscDirty = false;
  34986. this._areImageProcessingDirty = false;
  34987. };
  34988. /**
  34989. * Marks the material to indicate that it needs to be re-calculated
  34990. */
  34991. MaterialDefines.prototype.markAsUnprocessed = function () {
  34992. this._isDirty = true;
  34993. };
  34994. /**
  34995. * Marks the material to indicate all of its defines need to be re-calculated
  34996. */
  34997. MaterialDefines.prototype.markAllAsDirty = function () {
  34998. this._areTexturesDirty = true;
  34999. this._areAttributesDirty = true;
  35000. this._areLightsDirty = true;
  35001. this._areFresnelDirty = true;
  35002. this._areMiscDirty = true;
  35003. this._areImageProcessingDirty = true;
  35004. this._isDirty = true;
  35005. };
  35006. /**
  35007. * Marks the material to indicate that image processing needs to be re-calculated
  35008. */
  35009. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35010. this._areImageProcessingDirty = true;
  35011. this._isDirty = true;
  35012. };
  35013. /**
  35014. * Marks the material to indicate the lights need to be re-calculated
  35015. */
  35016. MaterialDefines.prototype.markAsLightDirty = function () {
  35017. this._areLightsDirty = true;
  35018. this._isDirty = true;
  35019. };
  35020. /**
  35021. * Marks the attribute state as changed
  35022. */
  35023. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35024. this._areAttributesDirty = true;
  35025. this._isDirty = true;
  35026. };
  35027. /**
  35028. * Marks the texture state as changed
  35029. */
  35030. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35031. this._areTexturesDirty = true;
  35032. this._isDirty = true;
  35033. };
  35034. /**
  35035. * Marks the fresnel state as changed
  35036. */
  35037. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35038. this._areFresnelDirty = true;
  35039. this._isDirty = true;
  35040. };
  35041. /**
  35042. * Marks the misc state as changed
  35043. */
  35044. MaterialDefines.prototype.markAsMiscDirty = function () {
  35045. this._areMiscDirty = true;
  35046. this._isDirty = true;
  35047. };
  35048. /**
  35049. * Rebuilds the material defines
  35050. */
  35051. MaterialDefines.prototype.rebuild = function () {
  35052. if (this._keys) {
  35053. delete this._keys;
  35054. }
  35055. this._keys = [];
  35056. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35057. var key = _a[_i];
  35058. if (key[0] === "_") {
  35059. continue;
  35060. }
  35061. this._keys.push(key);
  35062. }
  35063. };
  35064. /**
  35065. * Specifies if two material defines are equal
  35066. * @param other - A material define instance to compare to
  35067. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35068. */
  35069. MaterialDefines.prototype.isEqual = function (other) {
  35070. if (this._keys.length !== other._keys.length) {
  35071. return false;
  35072. }
  35073. for (var index = 0; index < this._keys.length; index++) {
  35074. var prop = this._keys[index];
  35075. if (this[prop] !== other[prop]) {
  35076. return false;
  35077. }
  35078. }
  35079. return true;
  35080. };
  35081. /**
  35082. * Clones this instance's defines to another instance
  35083. * @param other - material defines to clone values to
  35084. */
  35085. MaterialDefines.prototype.cloneTo = function (other) {
  35086. if (this._keys.length !== other._keys.length) {
  35087. other._keys = this._keys.slice(0);
  35088. }
  35089. for (var index = 0; index < this._keys.length; index++) {
  35090. var prop = this._keys[index];
  35091. other[prop] = this[prop];
  35092. }
  35093. };
  35094. /**
  35095. * Resets the material define values
  35096. */
  35097. MaterialDefines.prototype.reset = function () {
  35098. for (var index = 0; index < this._keys.length; index++) {
  35099. var prop = this._keys[index];
  35100. var type = typeof this[prop];
  35101. switch (type) {
  35102. case "number":
  35103. this[prop] = 0;
  35104. break;
  35105. case "string":
  35106. this[prop] = "";
  35107. break;
  35108. default:
  35109. this[prop] = false;
  35110. break;
  35111. }
  35112. }
  35113. };
  35114. /**
  35115. * Converts the material define values to a string
  35116. * @returns - String of material define information
  35117. */
  35118. MaterialDefines.prototype.toString = function () {
  35119. var result = "";
  35120. for (var index = 0; index < this._keys.length; index++) {
  35121. var prop = this._keys[index];
  35122. var value = this[prop];
  35123. var type = typeof value;
  35124. switch (type) {
  35125. case "number":
  35126. case "string":
  35127. result += "#define " + prop + " " + value + "\n";
  35128. break;
  35129. default:
  35130. if (value) {
  35131. result += "#define " + prop + "\n";
  35132. }
  35133. break;
  35134. }
  35135. }
  35136. return result;
  35137. };
  35138. return MaterialDefines;
  35139. }());
  35140. BABYLON.MaterialDefines = MaterialDefines;
  35141. /**
  35142. * Base class for the main features of a material in Babylon.js
  35143. */
  35144. var Material = /** @class */ (function () {
  35145. /**
  35146. * Creates a material instance
  35147. * @param name defines the name of the material
  35148. * @param scene defines the scene to reference
  35149. * @param doNotAdd specifies if the material should be added to the scene
  35150. */
  35151. function Material(name, scene, doNotAdd) {
  35152. /**
  35153. * Specifies if the ready state should be checked on each call
  35154. */
  35155. this.checkReadyOnEveryCall = false;
  35156. /**
  35157. * Specifies if the ready state should be checked once
  35158. */
  35159. this.checkReadyOnlyOnce = false;
  35160. /**
  35161. * The state of the material
  35162. */
  35163. this.state = "";
  35164. /**
  35165. * The alpha value of the material
  35166. */
  35167. this._alpha = 1.0;
  35168. /**
  35169. * Specifies if back face culling is enabled
  35170. */
  35171. this._backFaceCulling = true;
  35172. /**
  35173. * Specifies if the material should be serialized
  35174. */
  35175. this.doNotSerialize = false;
  35176. /**
  35177. * Specifies if the effect should be stored on sub meshes
  35178. */
  35179. this.storeEffectOnSubMeshes = false;
  35180. /**
  35181. * An event triggered when the material is disposed
  35182. */
  35183. this.onDisposeObservable = new BABYLON.Observable();
  35184. /**
  35185. * An event triggered when the material is bound
  35186. */
  35187. this.onBindObservable = new BABYLON.Observable();
  35188. /**
  35189. * An event triggered when the material is unbound
  35190. */
  35191. this.onUnBindObservable = new BABYLON.Observable();
  35192. /**
  35193. * Stores the value of the alpha mode
  35194. */
  35195. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35196. /**
  35197. * Stores the state of the need depth pre-pass value
  35198. */
  35199. this._needDepthPrePass = false;
  35200. /**
  35201. * Specifies if depth writing should be disabled
  35202. */
  35203. this.disableDepthWrite = false;
  35204. /**
  35205. * Specifies if depth writing should be forced
  35206. */
  35207. this.forceDepthWrite = false;
  35208. /**
  35209. * Specifies if there should be a separate pass for culling
  35210. */
  35211. this.separateCullingPass = false;
  35212. /**
  35213. * Stores the state specifing if fog should be enabled
  35214. */
  35215. this._fogEnabled = true;
  35216. /**
  35217. * Stores the size of points
  35218. */
  35219. this.pointSize = 1.0;
  35220. /**
  35221. * Stores the z offset value
  35222. */
  35223. this.zOffset = 0;
  35224. /**
  35225. * Specifies if the material was previously ready
  35226. */
  35227. this._wasPreviouslyReady = false;
  35228. /**
  35229. * Stores the fill mode state
  35230. */
  35231. this._fillMode = Material.TriangleFillMode;
  35232. this.name = name;
  35233. this.id = name || BABYLON.Tools.RandomId();
  35234. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35235. this.uniqueId = this._scene.getUniqueId();
  35236. if (this._scene.useRightHandedSystem) {
  35237. this.sideOrientation = Material.ClockWiseSideOrientation;
  35238. }
  35239. else {
  35240. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35241. }
  35242. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35243. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35244. if (!doNotAdd) {
  35245. this._scene.materials.push(this);
  35246. }
  35247. }
  35248. Object.defineProperty(Material, "TriangleFillMode", {
  35249. /**
  35250. * Returns the triangle fill mode
  35251. */
  35252. get: function () {
  35253. return Material._TriangleFillMode;
  35254. },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. Object.defineProperty(Material, "WireFrameFillMode", {
  35259. /**
  35260. * Returns the wireframe mode
  35261. */
  35262. get: function () {
  35263. return Material._WireFrameFillMode;
  35264. },
  35265. enumerable: true,
  35266. configurable: true
  35267. });
  35268. Object.defineProperty(Material, "PointFillMode", {
  35269. /**
  35270. * Returns the point fill mode
  35271. */
  35272. get: function () {
  35273. return Material._PointFillMode;
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. Object.defineProperty(Material, "PointListDrawMode", {
  35279. /**
  35280. * Returns the point list draw mode
  35281. */
  35282. get: function () {
  35283. return Material._PointListDrawMode;
  35284. },
  35285. enumerable: true,
  35286. configurable: true
  35287. });
  35288. Object.defineProperty(Material, "LineListDrawMode", {
  35289. /**
  35290. * Returns the line list draw mode
  35291. */
  35292. get: function () {
  35293. return Material._LineListDrawMode;
  35294. },
  35295. enumerable: true,
  35296. configurable: true
  35297. });
  35298. Object.defineProperty(Material, "LineLoopDrawMode", {
  35299. /**
  35300. * Returns the line loop draw mode
  35301. */
  35302. get: function () {
  35303. return Material._LineLoopDrawMode;
  35304. },
  35305. enumerable: true,
  35306. configurable: true
  35307. });
  35308. Object.defineProperty(Material, "LineStripDrawMode", {
  35309. /**
  35310. * Returns the line strip draw mode
  35311. */
  35312. get: function () {
  35313. return Material._LineStripDrawMode;
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35319. /**
  35320. * Returns the triangle strip draw mode
  35321. */
  35322. get: function () {
  35323. return Material._TriangleStripDrawMode;
  35324. },
  35325. enumerable: true,
  35326. configurable: true
  35327. });
  35328. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35329. /**
  35330. * Returns the triangle fan draw mode
  35331. */
  35332. get: function () {
  35333. return Material._TriangleFanDrawMode;
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35339. /**
  35340. * Returns the clock-wise side orientation
  35341. */
  35342. get: function () {
  35343. return Material._ClockWiseSideOrientation;
  35344. },
  35345. enumerable: true,
  35346. configurable: true
  35347. });
  35348. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35349. /**
  35350. * Returns the counter clock-wise side orientation
  35351. */
  35352. get: function () {
  35353. return Material._CounterClockWiseSideOrientation;
  35354. },
  35355. enumerable: true,
  35356. configurable: true
  35357. });
  35358. Object.defineProperty(Material, "TextureDirtyFlag", {
  35359. /**
  35360. * Returns the dirty texture flag value
  35361. */
  35362. get: function () {
  35363. return Material._TextureDirtyFlag;
  35364. },
  35365. enumerable: true,
  35366. configurable: true
  35367. });
  35368. Object.defineProperty(Material, "LightDirtyFlag", {
  35369. /**
  35370. * Returns the dirty light flag value
  35371. */
  35372. get: function () {
  35373. return Material._LightDirtyFlag;
  35374. },
  35375. enumerable: true,
  35376. configurable: true
  35377. });
  35378. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35379. /**
  35380. * Returns the dirty fresnel flag value
  35381. */
  35382. get: function () {
  35383. return Material._FresnelDirtyFlag;
  35384. },
  35385. enumerable: true,
  35386. configurable: true
  35387. });
  35388. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35389. /**
  35390. * Returns the dirty attributes flag value
  35391. */
  35392. get: function () {
  35393. return Material._AttributesDirtyFlag;
  35394. },
  35395. enumerable: true,
  35396. configurable: true
  35397. });
  35398. Object.defineProperty(Material, "MiscDirtyFlag", {
  35399. /**
  35400. * Returns the dirty misc flag value
  35401. */
  35402. get: function () {
  35403. return Material._MiscDirtyFlag;
  35404. },
  35405. enumerable: true,
  35406. configurable: true
  35407. });
  35408. Object.defineProperty(Material.prototype, "alpha", {
  35409. /**
  35410. * Gets the alpha value of the material
  35411. */
  35412. get: function () {
  35413. return this._alpha;
  35414. },
  35415. /**
  35416. * Sets the alpha value of the material
  35417. */
  35418. set: function (value) {
  35419. if (this._alpha === value) {
  35420. return;
  35421. }
  35422. this._alpha = value;
  35423. this.markAsDirty(Material.MiscDirtyFlag);
  35424. },
  35425. enumerable: true,
  35426. configurable: true
  35427. });
  35428. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35429. /**
  35430. * Gets the back-face culling state
  35431. */
  35432. get: function () {
  35433. return this._backFaceCulling;
  35434. },
  35435. /**
  35436. * Sets the back-face culling state
  35437. */
  35438. set: function (value) {
  35439. if (this._backFaceCulling === value) {
  35440. return;
  35441. }
  35442. this._backFaceCulling = value;
  35443. this.markAsDirty(Material.TextureDirtyFlag);
  35444. },
  35445. enumerable: true,
  35446. configurable: true
  35447. });
  35448. Object.defineProperty(Material.prototype, "onDispose", {
  35449. /**
  35450. * Called during a dispose event
  35451. */
  35452. set: function (callback) {
  35453. if (this._onDisposeObserver) {
  35454. this.onDisposeObservable.remove(this._onDisposeObserver);
  35455. }
  35456. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35457. },
  35458. enumerable: true,
  35459. configurable: true
  35460. });
  35461. Object.defineProperty(Material.prototype, "onBind", {
  35462. /**
  35463. * Called during a bind event
  35464. */
  35465. set: function (callback) {
  35466. if (this._onBindObserver) {
  35467. this.onBindObservable.remove(this._onBindObserver);
  35468. }
  35469. this._onBindObserver = this.onBindObservable.add(callback);
  35470. },
  35471. enumerable: true,
  35472. configurable: true
  35473. });
  35474. Object.defineProperty(Material.prototype, "alphaMode", {
  35475. /**
  35476. * Gets the value of the alpha mode
  35477. */
  35478. get: function () {
  35479. return this._alphaMode;
  35480. },
  35481. /**
  35482. * Sets the value of the alpha mode.
  35483. *
  35484. * | Value | Type | Description |
  35485. * | --- | --- | --- |
  35486. * | 0 | ALPHA_DISABLE | |
  35487. * | 1 | ALPHA_ADD | |
  35488. * | 2 | ALPHA_COMBINE | |
  35489. * | 3 | ALPHA_SUBTRACT | |
  35490. * | 4 | ALPHA_MULTIPLY | |
  35491. * | 5 | ALPHA_MAXIMIZED | |
  35492. * | 6 | ALPHA_ONEONE | |
  35493. * | 7 | ALPHA_PREMULTIPLIED | |
  35494. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35495. * | 9 | ALPHA_INTERPOLATE | |
  35496. * | 10 | ALPHA_SCREENMODE | |
  35497. *
  35498. */
  35499. set: function (value) {
  35500. if (this._alphaMode === value) {
  35501. return;
  35502. }
  35503. this._alphaMode = value;
  35504. this.markAsDirty(Material.TextureDirtyFlag);
  35505. },
  35506. enumerable: true,
  35507. configurable: true
  35508. });
  35509. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35510. /**
  35511. * Gets the depth pre-pass value
  35512. */
  35513. get: function () {
  35514. return this._needDepthPrePass;
  35515. },
  35516. /**
  35517. * Sets the need depth pre-pass value
  35518. */
  35519. set: function (value) {
  35520. if (this._needDepthPrePass === value) {
  35521. return;
  35522. }
  35523. this._needDepthPrePass = value;
  35524. if (this._needDepthPrePass) {
  35525. this.checkReadyOnEveryCall = true;
  35526. }
  35527. },
  35528. enumerable: true,
  35529. configurable: true
  35530. });
  35531. Object.defineProperty(Material.prototype, "fogEnabled", {
  35532. /**
  35533. * Gets the value of the fog enabled state
  35534. */
  35535. get: function () {
  35536. return this._fogEnabled;
  35537. },
  35538. /**
  35539. * Sets the state for enabling fog
  35540. */
  35541. set: function (value) {
  35542. if (this._fogEnabled === value) {
  35543. return;
  35544. }
  35545. this._fogEnabled = value;
  35546. this.markAsDirty(Material.MiscDirtyFlag);
  35547. },
  35548. enumerable: true,
  35549. configurable: true
  35550. });
  35551. Object.defineProperty(Material.prototype, "wireframe", {
  35552. /**
  35553. * Gets a value specifying if wireframe mode is enabled
  35554. */
  35555. get: function () {
  35556. switch (this._fillMode) {
  35557. case Material.WireFrameFillMode:
  35558. case Material.LineListDrawMode:
  35559. case Material.LineLoopDrawMode:
  35560. case Material.LineStripDrawMode:
  35561. return true;
  35562. }
  35563. return this._scene.forceWireframe;
  35564. },
  35565. /**
  35566. * Sets the state of wireframe mode
  35567. */
  35568. set: function (value) {
  35569. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35570. },
  35571. enumerable: true,
  35572. configurable: true
  35573. });
  35574. Object.defineProperty(Material.prototype, "pointsCloud", {
  35575. /**
  35576. * Gets the value specifying if point clouds are enabled
  35577. */
  35578. get: function () {
  35579. switch (this._fillMode) {
  35580. case Material.PointFillMode:
  35581. case Material.PointListDrawMode:
  35582. return true;
  35583. }
  35584. return this._scene.forcePointsCloud;
  35585. },
  35586. /**
  35587. * Sets the state of point cloud mode
  35588. */
  35589. set: function (value) {
  35590. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35591. },
  35592. enumerable: true,
  35593. configurable: true
  35594. });
  35595. Object.defineProperty(Material.prototype, "fillMode", {
  35596. /**
  35597. * Gets the material fill mode
  35598. */
  35599. get: function () {
  35600. return this._fillMode;
  35601. },
  35602. /**
  35603. * Sets the material fill mode
  35604. */
  35605. set: function (value) {
  35606. if (this._fillMode === value) {
  35607. return;
  35608. }
  35609. this._fillMode = value;
  35610. this.markAsDirty(Material.MiscDirtyFlag);
  35611. },
  35612. enumerable: true,
  35613. configurable: true
  35614. });
  35615. /**
  35616. * Returns a string representation of the current material
  35617. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35618. * @returns a string with material information
  35619. */
  35620. Material.prototype.toString = function (fullDetails) {
  35621. var ret = "Name: " + this.name;
  35622. if (fullDetails) {
  35623. }
  35624. return ret;
  35625. };
  35626. /**
  35627. * Gets the class name of the material
  35628. * @returns a string with the class name of the material
  35629. */
  35630. Material.prototype.getClassName = function () {
  35631. return "Material";
  35632. };
  35633. Object.defineProperty(Material.prototype, "isFrozen", {
  35634. /**
  35635. * Specifies if updates for the material been locked
  35636. */
  35637. get: function () {
  35638. return this.checkReadyOnlyOnce;
  35639. },
  35640. enumerable: true,
  35641. configurable: true
  35642. });
  35643. /**
  35644. * Locks updates for the material
  35645. */
  35646. Material.prototype.freeze = function () {
  35647. this.checkReadyOnlyOnce = true;
  35648. };
  35649. /**
  35650. * Unlocks updates for the material
  35651. */
  35652. Material.prototype.unfreeze = function () {
  35653. this.checkReadyOnlyOnce = false;
  35654. };
  35655. /**
  35656. * Specifies if the material is ready to be used
  35657. * @param mesh defines the mesh to check
  35658. * @param useInstances specifies if instances should be used
  35659. * @returns a boolean indicating if the material is ready to be used
  35660. */
  35661. Material.prototype.isReady = function (mesh, useInstances) {
  35662. return true;
  35663. };
  35664. /**
  35665. * Specifies that the submesh is ready to be used
  35666. * @param mesh defines the mesh to check
  35667. * @param subMesh defines which submesh to check
  35668. * @param useInstances specifies that instances should be used
  35669. * @returns a boolean indicating that the submesh is ready or not
  35670. */
  35671. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35672. return false;
  35673. };
  35674. /**
  35675. * Returns the material effect
  35676. * @returns the effect associated with the material
  35677. */
  35678. Material.prototype.getEffect = function () {
  35679. return this._effect;
  35680. };
  35681. /**
  35682. * Returns the current scene
  35683. * @returns a Scene
  35684. */
  35685. Material.prototype.getScene = function () {
  35686. return this._scene;
  35687. };
  35688. /**
  35689. * Specifies if the material will require alpha blending
  35690. * @returns a boolean specifying if alpha blending is needed
  35691. */
  35692. Material.prototype.needAlphaBlending = function () {
  35693. return (this.alpha < 1.0);
  35694. };
  35695. /**
  35696. * Specifies if the mesh will require alpha blending
  35697. * @param mesh defines the mesh to check
  35698. * @returns a boolean specifying if alpha blending is needed for the mesh
  35699. */
  35700. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35701. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35702. };
  35703. /**
  35704. * Specifies if this material should be rendered in alpha test mode
  35705. * @returns a boolean specifying if an alpha test is needed.
  35706. */
  35707. Material.prototype.needAlphaTesting = function () {
  35708. return false;
  35709. };
  35710. /**
  35711. * Gets the texture used for the alpha test
  35712. * @returns the texture to use for alpha testing
  35713. */
  35714. Material.prototype.getAlphaTestTexture = function () {
  35715. return null;
  35716. };
  35717. /**
  35718. * Marks the material to indicate that it needs to be re-calculated
  35719. */
  35720. Material.prototype.markDirty = function () {
  35721. this._wasPreviouslyReady = false;
  35722. };
  35723. /** @hidden */
  35724. Material.prototype._preBind = function (effect, overrideOrientation) {
  35725. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35726. var engine = this._scene.getEngine();
  35727. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35728. var reverse = orientation === Material.ClockWiseSideOrientation;
  35729. engine.enableEffect(effect ? effect : this._effect);
  35730. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35731. return reverse;
  35732. };
  35733. /**
  35734. * Binds the material to the mesh
  35735. * @param world defines the world transformation matrix
  35736. * @param mesh defines the mesh to bind the material to
  35737. */
  35738. Material.prototype.bind = function (world, mesh) {
  35739. };
  35740. /**
  35741. * Binds the submesh to the material
  35742. * @param world defines the world transformation matrix
  35743. * @param mesh defines the mesh containing the submesh
  35744. * @param subMesh defines the submesh to bind the material to
  35745. */
  35746. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35747. };
  35748. /**
  35749. * Binds the world matrix to the material
  35750. * @param world defines the world transformation matrix
  35751. */
  35752. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35753. };
  35754. /**
  35755. * Binds the scene's uniform buffer to the effect.
  35756. * @param effect defines the effect to bind to the scene uniform buffer
  35757. * @param sceneUbo defines the uniform buffer storing scene data
  35758. */
  35759. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35760. sceneUbo.bindToEffect(effect, "Scene");
  35761. };
  35762. /**
  35763. * Binds the view matrix to the effect
  35764. * @param effect defines the effect to bind the view matrix to
  35765. */
  35766. Material.prototype.bindView = function (effect) {
  35767. if (!this._useUBO) {
  35768. effect.setMatrix("view", this.getScene().getViewMatrix());
  35769. }
  35770. else {
  35771. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35772. }
  35773. };
  35774. /**
  35775. * Binds the view projection matrix to the effect
  35776. * @param effect defines the effect to bind the view projection matrix to
  35777. */
  35778. Material.prototype.bindViewProjection = function (effect) {
  35779. if (!this._useUBO) {
  35780. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35781. }
  35782. else {
  35783. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35784. }
  35785. };
  35786. /**
  35787. * Specifies if material alpha testing should be turned on for the mesh
  35788. * @param mesh defines the mesh to check
  35789. */
  35790. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35791. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35792. };
  35793. /**
  35794. * Processes to execute after binding the material to a mesh
  35795. * @param mesh defines the rendered mesh
  35796. */
  35797. Material.prototype._afterBind = function (mesh) {
  35798. this._scene._cachedMaterial = this;
  35799. if (mesh) {
  35800. this._scene._cachedVisibility = mesh.visibility;
  35801. }
  35802. else {
  35803. this._scene._cachedVisibility = 1;
  35804. }
  35805. if (mesh) {
  35806. this.onBindObservable.notifyObservers(mesh);
  35807. }
  35808. if (this.disableDepthWrite) {
  35809. var engine = this._scene.getEngine();
  35810. this._cachedDepthWriteState = engine.getDepthWrite();
  35811. engine.setDepthWrite(false);
  35812. }
  35813. };
  35814. /**
  35815. * Unbinds the material from the mesh
  35816. */
  35817. Material.prototype.unbind = function () {
  35818. this.onUnBindObservable.notifyObservers(this);
  35819. if (this.disableDepthWrite) {
  35820. var engine = this._scene.getEngine();
  35821. engine.setDepthWrite(this._cachedDepthWriteState);
  35822. }
  35823. };
  35824. /**
  35825. * Gets the active textures from the material
  35826. * @returns an array of textures
  35827. */
  35828. Material.prototype.getActiveTextures = function () {
  35829. return [];
  35830. };
  35831. /**
  35832. * Specifies if the material uses a texture
  35833. * @param texture defines the texture to check against the material
  35834. * @returns a boolean specifying if the material uses the texture
  35835. */
  35836. Material.prototype.hasTexture = function (texture) {
  35837. return false;
  35838. };
  35839. /**
  35840. * Makes a duplicate of the material, and gives it a new name
  35841. * @param name defines the new name for the duplicated material
  35842. * @returns the cloned material
  35843. */
  35844. Material.prototype.clone = function (name) {
  35845. return null;
  35846. };
  35847. /**
  35848. * Gets the meshes bound to the material
  35849. * @returns an array of meshes bound to the material
  35850. */
  35851. Material.prototype.getBindedMeshes = function () {
  35852. var result = new Array();
  35853. for (var index = 0; index < this._scene.meshes.length; index++) {
  35854. var mesh = this._scene.meshes[index];
  35855. if (mesh.material === this) {
  35856. result.push(mesh);
  35857. }
  35858. }
  35859. return result;
  35860. };
  35861. /**
  35862. * Force shader compilation
  35863. * @param mesh defines the mesh associated with this material
  35864. * @param onCompiled defines a function to execute once the material is compiled
  35865. * @param options defines the options to configure the compilation
  35866. */
  35867. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35868. var _this = this;
  35869. var localOptions = __assign({ clipPlane: false }, options);
  35870. var subMesh = new BABYLON.BaseSubMesh();
  35871. var scene = this.getScene();
  35872. var checkReady = function () {
  35873. if (!_this._scene || !_this._scene.getEngine()) {
  35874. return;
  35875. }
  35876. if (subMesh._materialDefines) {
  35877. subMesh._materialDefines._renderId = -1;
  35878. }
  35879. var clipPlaneState = scene.clipPlane;
  35880. if (localOptions.clipPlane) {
  35881. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35882. }
  35883. if (_this.storeEffectOnSubMeshes) {
  35884. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35885. if (onCompiled) {
  35886. onCompiled(_this);
  35887. }
  35888. }
  35889. else {
  35890. setTimeout(checkReady, 16);
  35891. }
  35892. }
  35893. else {
  35894. if (_this.isReady(mesh)) {
  35895. if (onCompiled) {
  35896. onCompiled(_this);
  35897. }
  35898. }
  35899. else {
  35900. setTimeout(checkReady, 16);
  35901. }
  35902. }
  35903. if (localOptions.clipPlane) {
  35904. scene.clipPlane = clipPlaneState;
  35905. }
  35906. };
  35907. checkReady();
  35908. };
  35909. /**
  35910. * Force shader compilation
  35911. * @param mesh defines the mesh that will use this material
  35912. * @param options defines additional options for compiling the shaders
  35913. * @returns a promise that resolves when the compilation completes
  35914. */
  35915. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35916. var _this = this;
  35917. return new Promise(function (resolve) {
  35918. _this.forceCompilation(mesh, function () {
  35919. resolve();
  35920. }, options);
  35921. });
  35922. };
  35923. /**
  35924. * Marks a define in the material to indicate that it needs to be re-computed
  35925. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35926. */
  35927. Material.prototype.markAsDirty = function (flag) {
  35928. if (flag & Material.TextureDirtyFlag) {
  35929. this._markAllSubMeshesAsTexturesDirty();
  35930. }
  35931. if (flag & Material.LightDirtyFlag) {
  35932. this._markAllSubMeshesAsLightsDirty();
  35933. }
  35934. if (flag & Material.FresnelDirtyFlag) {
  35935. this._markAllSubMeshesAsFresnelDirty();
  35936. }
  35937. if (flag & Material.AttributesDirtyFlag) {
  35938. this._markAllSubMeshesAsAttributesDirty();
  35939. }
  35940. if (flag & Material.MiscDirtyFlag) {
  35941. this._markAllSubMeshesAsMiscDirty();
  35942. }
  35943. this.getScene().resetCachedMaterial();
  35944. };
  35945. /**
  35946. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35947. * @param func defines a function which checks material defines against the submeshes
  35948. */
  35949. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35950. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35951. var mesh = _a[_i];
  35952. if (!mesh.subMeshes) {
  35953. continue;
  35954. }
  35955. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35956. var subMesh = _c[_b];
  35957. if (subMesh.getMaterial() !== this) {
  35958. continue;
  35959. }
  35960. if (!subMesh._materialDefines) {
  35961. continue;
  35962. }
  35963. func(subMesh._materialDefines);
  35964. }
  35965. }
  35966. };
  35967. /**
  35968. * Indicates that image processing needs to be re-calculated for all submeshes
  35969. */
  35970. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35971. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35972. };
  35973. /**
  35974. * Indicates that textures need to be re-calculated for all submeshes
  35975. */
  35976. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35977. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35978. };
  35979. /**
  35980. * Indicates that fresnel needs to be re-calculated for all submeshes
  35981. */
  35982. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35983. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35984. };
  35985. /**
  35986. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35987. */
  35988. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35989. this._markAllSubMeshesAsDirty(function (defines) {
  35990. defines.markAsFresnelDirty();
  35991. defines.markAsMiscDirty();
  35992. });
  35993. };
  35994. /**
  35995. * Indicates that lights need to be re-calculated for all submeshes
  35996. */
  35997. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35998. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35999. };
  36000. /**
  36001. * Indicates that attributes need to be re-calculated for all submeshes
  36002. */
  36003. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36004. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36005. };
  36006. /**
  36007. * Indicates that misc needs to be re-calculated for all submeshes
  36008. */
  36009. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36010. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36011. };
  36012. /**
  36013. * Indicates that textures and misc need to be re-calculated for all submeshes
  36014. */
  36015. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36016. this._markAllSubMeshesAsDirty(function (defines) {
  36017. defines.markAsTexturesDirty();
  36018. defines.markAsMiscDirty();
  36019. });
  36020. };
  36021. /**
  36022. * Disposes the material
  36023. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36024. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36025. */
  36026. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36027. // Animations
  36028. this.getScene().stopAnimation(this);
  36029. this.getScene().freeProcessedMaterials();
  36030. // Remove from scene
  36031. var index = this._scene.materials.indexOf(this);
  36032. if (index >= 0) {
  36033. this._scene.materials.splice(index, 1);
  36034. }
  36035. // Remove from meshes
  36036. for (index = 0; index < this._scene.meshes.length; index++) {
  36037. var mesh = this._scene.meshes[index];
  36038. if (mesh.material === this) {
  36039. mesh.material = null;
  36040. if (mesh.geometry) {
  36041. var geometry = (mesh.geometry);
  36042. if (this.storeEffectOnSubMeshes) {
  36043. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36044. var subMesh = _a[_i];
  36045. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36046. if (forceDisposeEffect && subMesh._materialEffect) {
  36047. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36048. }
  36049. }
  36050. }
  36051. else {
  36052. geometry._releaseVertexArrayObject(this._effect);
  36053. }
  36054. }
  36055. }
  36056. }
  36057. this._uniformBuffer.dispose();
  36058. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36059. if (forceDisposeEffect && this._effect) {
  36060. if (!this.storeEffectOnSubMeshes) {
  36061. this._scene.getEngine()._releaseEffect(this._effect);
  36062. }
  36063. this._effect = null;
  36064. }
  36065. // Callback
  36066. this.onDisposeObservable.notifyObservers(this);
  36067. this.onDisposeObservable.clear();
  36068. this.onBindObservable.clear();
  36069. this.onUnBindObservable.clear();
  36070. };
  36071. /**
  36072. * Serializes this material
  36073. * @returns the serialized material object
  36074. */
  36075. Material.prototype.serialize = function () {
  36076. return BABYLON.SerializationHelper.Serialize(this);
  36077. };
  36078. /**
  36079. * Creates a MultiMaterial from parsed MultiMaterial data.
  36080. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36081. * @param scene defines the hosting scene
  36082. * @returns a new MultiMaterial
  36083. */
  36084. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36085. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36086. multiMaterial.id = parsedMultiMaterial.id;
  36087. if (BABYLON.Tags) {
  36088. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36089. }
  36090. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36091. var subMatId = parsedMultiMaterial.materials[matIndex];
  36092. if (subMatId) {
  36093. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36094. }
  36095. else {
  36096. multiMaterial.subMaterials.push(null);
  36097. }
  36098. }
  36099. return multiMaterial;
  36100. };
  36101. /**
  36102. * Creates a material from parsed material data
  36103. * @param parsedMaterial defines parsed material data
  36104. * @param scene defines the hosting scene
  36105. * @param rootUrl defines the root URL to use to load textures
  36106. * @returns a new material
  36107. */
  36108. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36109. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36110. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36111. }
  36112. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36113. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36114. if (!BABYLON.LegacyPBRMaterial) {
  36115. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36116. return;
  36117. }
  36118. }
  36119. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36120. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36121. };
  36122. // Triangle views
  36123. Material._TriangleFillMode = 0;
  36124. Material._WireFrameFillMode = 1;
  36125. Material._PointFillMode = 2;
  36126. // Draw modes
  36127. Material._PointListDrawMode = 3;
  36128. Material._LineListDrawMode = 4;
  36129. Material._LineLoopDrawMode = 5;
  36130. Material._LineStripDrawMode = 6;
  36131. Material._TriangleStripDrawMode = 7;
  36132. Material._TriangleFanDrawMode = 8;
  36133. /**
  36134. * Stores the clock-wise side orientation
  36135. */
  36136. Material._ClockWiseSideOrientation = 0;
  36137. /**
  36138. * Stores the counter clock-wise side orientation
  36139. */
  36140. Material._CounterClockWiseSideOrientation = 1;
  36141. /**
  36142. * The dirty texture flag value
  36143. */
  36144. Material._TextureDirtyFlag = 1;
  36145. /**
  36146. * The dirty light flag value
  36147. */
  36148. Material._LightDirtyFlag = 2;
  36149. /**
  36150. * The dirty fresnel flag value
  36151. */
  36152. Material._FresnelDirtyFlag = 4;
  36153. /**
  36154. * The dirty attribute flag value
  36155. */
  36156. Material._AttributesDirtyFlag = 8;
  36157. /**
  36158. * The dirty misc flag value
  36159. */
  36160. Material._MiscDirtyFlag = 16;
  36161. __decorate([
  36162. BABYLON.serialize()
  36163. ], Material.prototype, "id", void 0);
  36164. __decorate([
  36165. BABYLON.serialize()
  36166. ], Material.prototype, "uniqueId", void 0);
  36167. __decorate([
  36168. BABYLON.serialize()
  36169. ], Material.prototype, "name", void 0);
  36170. __decorate([
  36171. BABYLON.serialize()
  36172. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36173. __decorate([
  36174. BABYLON.serialize()
  36175. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36176. __decorate([
  36177. BABYLON.serialize()
  36178. ], Material.prototype, "state", void 0);
  36179. __decorate([
  36180. BABYLON.serialize("alpha")
  36181. ], Material.prototype, "_alpha", void 0);
  36182. __decorate([
  36183. BABYLON.serialize("backFaceCulling")
  36184. ], Material.prototype, "_backFaceCulling", void 0);
  36185. __decorate([
  36186. BABYLON.serialize()
  36187. ], Material.prototype, "sideOrientation", void 0);
  36188. __decorate([
  36189. BABYLON.serialize("alphaMode")
  36190. ], Material.prototype, "_alphaMode", void 0);
  36191. __decorate([
  36192. BABYLON.serialize()
  36193. ], Material.prototype, "_needDepthPrePass", void 0);
  36194. __decorate([
  36195. BABYLON.serialize()
  36196. ], Material.prototype, "disableDepthWrite", void 0);
  36197. __decorate([
  36198. BABYLON.serialize()
  36199. ], Material.prototype, "forceDepthWrite", void 0);
  36200. __decorate([
  36201. BABYLON.serialize()
  36202. ], Material.prototype, "separateCullingPass", void 0);
  36203. __decorate([
  36204. BABYLON.serialize("fogEnabled")
  36205. ], Material.prototype, "_fogEnabled", void 0);
  36206. __decorate([
  36207. BABYLON.serialize()
  36208. ], Material.prototype, "pointSize", void 0);
  36209. __decorate([
  36210. BABYLON.serialize()
  36211. ], Material.prototype, "zOffset", void 0);
  36212. __decorate([
  36213. BABYLON.serialize()
  36214. ], Material.prototype, "wireframe", null);
  36215. __decorate([
  36216. BABYLON.serialize()
  36217. ], Material.prototype, "pointsCloud", null);
  36218. __decorate([
  36219. BABYLON.serialize()
  36220. ], Material.prototype, "fillMode", null);
  36221. return Material;
  36222. }());
  36223. BABYLON.Material = Material;
  36224. })(BABYLON || (BABYLON = {}));
  36225. //# sourceMappingURL=babylon.material.js.map
  36226. var BABYLON;
  36227. (function (BABYLON) {
  36228. var UniformBuffer = /** @class */ (function () {
  36229. /**
  36230. * Uniform buffer objects.
  36231. *
  36232. * Handles blocks of uniform on the GPU.
  36233. *
  36234. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36235. *
  36236. * For more information, please refer to :
  36237. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36238. */
  36239. function UniformBuffer(engine, data, dynamic) {
  36240. this._engine = engine;
  36241. this._noUBO = !engine.supportsUniformBuffers;
  36242. this._dynamic = dynamic;
  36243. this._data = data || [];
  36244. this._uniformLocations = {};
  36245. this._uniformSizes = {};
  36246. this._uniformLocationPointer = 0;
  36247. this._needSync = false;
  36248. if (this._noUBO) {
  36249. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36250. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36251. this.updateFloat = this._updateFloatForEffect;
  36252. this.updateFloat2 = this._updateFloat2ForEffect;
  36253. this.updateFloat3 = this._updateFloat3ForEffect;
  36254. this.updateFloat4 = this._updateFloat4ForEffect;
  36255. this.updateMatrix = this._updateMatrixForEffect;
  36256. this.updateVector3 = this._updateVector3ForEffect;
  36257. this.updateVector4 = this._updateVector4ForEffect;
  36258. this.updateColor3 = this._updateColor3ForEffect;
  36259. this.updateColor4 = this._updateColor4ForEffect;
  36260. }
  36261. else {
  36262. this._engine._uniformBuffers.push(this);
  36263. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36264. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36265. this.updateFloat = this._updateFloatForUniform;
  36266. this.updateFloat2 = this._updateFloat2ForUniform;
  36267. this.updateFloat3 = this._updateFloat3ForUniform;
  36268. this.updateFloat4 = this._updateFloat4ForUniform;
  36269. this.updateMatrix = this._updateMatrixForUniform;
  36270. this.updateVector3 = this._updateVector3ForUniform;
  36271. this.updateVector4 = this._updateVector4ForUniform;
  36272. this.updateColor3 = this._updateColor3ForUniform;
  36273. this.updateColor4 = this._updateColor4ForUniform;
  36274. }
  36275. }
  36276. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36277. // Properties
  36278. /**
  36279. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36280. * or just falling back on setUniformXXX calls.
  36281. */
  36282. get: function () {
  36283. return !this._noUBO;
  36284. },
  36285. enumerable: true,
  36286. configurable: true
  36287. });
  36288. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36289. /**
  36290. * Indicates if the WebGL underlying uniform buffer is in sync
  36291. * with the javascript cache data.
  36292. */
  36293. get: function () {
  36294. return !this._needSync;
  36295. },
  36296. enumerable: true,
  36297. configurable: true
  36298. });
  36299. /**
  36300. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36301. * Also, a dynamic UniformBuffer will disable cache verification and always
  36302. * update the underlying WebGL uniform buffer to the GPU.
  36303. */
  36304. UniformBuffer.prototype.isDynamic = function () {
  36305. return this._dynamic !== undefined;
  36306. };
  36307. /**
  36308. * The data cache on JS side.
  36309. */
  36310. UniformBuffer.prototype.getData = function () {
  36311. return this._bufferData;
  36312. };
  36313. /**
  36314. * The underlying WebGL Uniform buffer.
  36315. */
  36316. UniformBuffer.prototype.getBuffer = function () {
  36317. return this._buffer;
  36318. };
  36319. /**
  36320. * std140 layout specifies how to align data within an UBO structure.
  36321. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36322. * for specs.
  36323. */
  36324. UniformBuffer.prototype._fillAlignment = function (size) {
  36325. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36326. // and 4x4 matrices
  36327. // TODO : change if other types are used
  36328. var alignment;
  36329. if (size <= 2) {
  36330. alignment = size;
  36331. }
  36332. else {
  36333. alignment = 4;
  36334. }
  36335. if ((this._uniformLocationPointer % alignment) !== 0) {
  36336. var oldPointer = this._uniformLocationPointer;
  36337. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36338. var diff = this._uniformLocationPointer - oldPointer;
  36339. for (var i = 0; i < diff; i++) {
  36340. this._data.push(0);
  36341. }
  36342. }
  36343. };
  36344. /**
  36345. * Adds an uniform in the buffer.
  36346. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36347. * for the layout to be correct !
  36348. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36349. * @param {number|number[]} size Data size, or data directly.
  36350. */
  36351. UniformBuffer.prototype.addUniform = function (name, size) {
  36352. if (this._noUBO) {
  36353. return;
  36354. }
  36355. if (this._uniformLocations[name] !== undefined) {
  36356. // Already existing uniform
  36357. return;
  36358. }
  36359. // This function must be called in the order of the shader layout !
  36360. // size can be the size of the uniform, or data directly
  36361. var data;
  36362. if (size instanceof Array) {
  36363. data = size;
  36364. size = data.length;
  36365. }
  36366. else {
  36367. size = size;
  36368. data = [];
  36369. // Fill with zeros
  36370. for (var i = 0; i < size; i++) {
  36371. data.push(0);
  36372. }
  36373. }
  36374. this._fillAlignment(size);
  36375. this._uniformSizes[name] = size;
  36376. this._uniformLocations[name] = this._uniformLocationPointer;
  36377. this._uniformLocationPointer += size;
  36378. for (var i = 0; i < size; i++) {
  36379. this._data.push(data[i]);
  36380. }
  36381. this._needSync = true;
  36382. };
  36383. /**
  36384. * Wrapper for addUniform.
  36385. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36386. * @param {Matrix} mat A 4x4 matrix.
  36387. */
  36388. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36389. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36390. };
  36391. /**
  36392. * Wrapper for addUniform.
  36393. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36394. * @param {number} x
  36395. * @param {number} y
  36396. */
  36397. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36398. var temp = [x, y];
  36399. this.addUniform(name, temp);
  36400. };
  36401. /**
  36402. * Wrapper for addUniform.
  36403. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36404. * @param {number} x
  36405. * @param {number} y
  36406. * @param {number} z
  36407. */
  36408. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36409. var temp = [x, y, z];
  36410. this.addUniform(name, temp);
  36411. };
  36412. /**
  36413. * Wrapper for addUniform.
  36414. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36415. * @param {Color3} color
  36416. */
  36417. UniformBuffer.prototype.addColor3 = function (name, color) {
  36418. var temp = new Array();
  36419. color.toArray(temp);
  36420. this.addUniform(name, temp);
  36421. };
  36422. /**
  36423. * Wrapper for addUniform.
  36424. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36425. * @param {Color3} color
  36426. * @param {number} alpha
  36427. */
  36428. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36429. var temp = new Array();
  36430. color.toArray(temp);
  36431. temp.push(alpha);
  36432. this.addUniform(name, temp);
  36433. };
  36434. /**
  36435. * Wrapper for addUniform.
  36436. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36437. * @param {Vector3} vector
  36438. */
  36439. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36440. var temp = new Array();
  36441. vector.toArray(temp);
  36442. this.addUniform(name, temp);
  36443. };
  36444. /**
  36445. * Wrapper for addUniform.
  36446. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36447. */
  36448. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36449. this.addUniform(name, 12);
  36450. };
  36451. /**
  36452. * Wrapper for addUniform.
  36453. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36454. */
  36455. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36456. this.addUniform(name, 8);
  36457. };
  36458. /**
  36459. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36460. */
  36461. UniformBuffer.prototype.create = function () {
  36462. if (this._noUBO) {
  36463. return;
  36464. }
  36465. if (this._buffer) {
  36466. return; // nothing to do
  36467. }
  36468. // See spec, alignment must be filled as a vec4
  36469. this._fillAlignment(4);
  36470. this._bufferData = new Float32Array(this._data);
  36471. this._rebuild();
  36472. this._needSync = true;
  36473. };
  36474. UniformBuffer.prototype._rebuild = function () {
  36475. if (this._noUBO) {
  36476. return;
  36477. }
  36478. if (this._dynamic) {
  36479. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36480. }
  36481. else {
  36482. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36483. }
  36484. };
  36485. /**
  36486. * Updates the WebGL Uniform Buffer on the GPU.
  36487. * If the `dynamic` flag is set to true, no cache comparison is done.
  36488. * Otherwise, the buffer will be updated only if the cache differs.
  36489. */
  36490. UniformBuffer.prototype.update = function () {
  36491. if (!this._buffer) {
  36492. this.create();
  36493. return;
  36494. }
  36495. if (!this._dynamic && !this._needSync) {
  36496. return;
  36497. }
  36498. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36499. this._needSync = false;
  36500. };
  36501. /**
  36502. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36503. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36504. * @param {number[]|Float32Array} data Flattened data
  36505. * @param {number} size Size of the data.
  36506. */
  36507. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36508. var location = this._uniformLocations[uniformName];
  36509. if (location === undefined) {
  36510. if (this._buffer) {
  36511. // Cannot add an uniform if the buffer is already created
  36512. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36513. return;
  36514. }
  36515. this.addUniform(uniformName, size);
  36516. location = this._uniformLocations[uniformName];
  36517. }
  36518. if (!this._buffer) {
  36519. this.create();
  36520. }
  36521. if (!this._dynamic) {
  36522. // Cache for static uniform buffers
  36523. var changed = false;
  36524. for (var i = 0; i < size; i++) {
  36525. if (this._bufferData[location + i] !== data[i]) {
  36526. changed = true;
  36527. this._bufferData[location + i] = data[i];
  36528. }
  36529. }
  36530. this._needSync = this._needSync || changed;
  36531. }
  36532. else {
  36533. // No cache for dynamic
  36534. for (var i = 0; i < size; i++) {
  36535. this._bufferData[location + i] = data[i];
  36536. }
  36537. }
  36538. };
  36539. // Update methods
  36540. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36541. // To match std140, matrix must be realigned
  36542. for (var i = 0; i < 3; i++) {
  36543. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36544. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36545. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36546. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36547. }
  36548. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36549. };
  36550. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36551. this._currentEffect.setMatrix3x3(name, matrix);
  36552. };
  36553. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36554. this._currentEffect.setMatrix2x2(name, matrix);
  36555. };
  36556. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36557. // To match std140, matrix must be realigned
  36558. for (var i = 0; i < 2; i++) {
  36559. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36560. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36561. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36562. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36563. }
  36564. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36565. };
  36566. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36567. this._currentEffect.setFloat(name, x);
  36568. };
  36569. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36570. UniformBuffer._tempBuffer[0] = x;
  36571. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36572. };
  36573. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36574. if (suffix === void 0) { suffix = ""; }
  36575. this._currentEffect.setFloat2(name + suffix, x, y);
  36576. };
  36577. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36578. if (suffix === void 0) { suffix = ""; }
  36579. UniformBuffer._tempBuffer[0] = x;
  36580. UniformBuffer._tempBuffer[1] = y;
  36581. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36582. };
  36583. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36584. if (suffix === void 0) { suffix = ""; }
  36585. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36586. };
  36587. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36588. if (suffix === void 0) { suffix = ""; }
  36589. UniformBuffer._tempBuffer[0] = x;
  36590. UniformBuffer._tempBuffer[1] = y;
  36591. UniformBuffer._tempBuffer[2] = z;
  36592. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36593. };
  36594. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36595. if (suffix === void 0) { suffix = ""; }
  36596. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36597. };
  36598. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36599. if (suffix === void 0) { suffix = ""; }
  36600. UniformBuffer._tempBuffer[0] = x;
  36601. UniformBuffer._tempBuffer[1] = y;
  36602. UniformBuffer._tempBuffer[2] = z;
  36603. UniformBuffer._tempBuffer[3] = w;
  36604. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36605. };
  36606. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36607. this._currentEffect.setMatrix(name, mat);
  36608. };
  36609. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36610. this.updateUniform(name, mat.toArray(), 16);
  36611. };
  36612. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36613. this._currentEffect.setVector3(name, vector);
  36614. };
  36615. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36616. vector.toArray(UniformBuffer._tempBuffer);
  36617. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36618. };
  36619. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36620. this._currentEffect.setVector4(name, vector);
  36621. };
  36622. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36623. vector.toArray(UniformBuffer._tempBuffer);
  36624. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36625. };
  36626. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36627. if (suffix === void 0) { suffix = ""; }
  36628. this._currentEffect.setColor3(name + suffix, color);
  36629. };
  36630. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36631. if (suffix === void 0) { suffix = ""; }
  36632. color.toArray(UniformBuffer._tempBuffer);
  36633. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36634. };
  36635. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36636. if (suffix === void 0) { suffix = ""; }
  36637. this._currentEffect.setColor4(name + suffix, color, alpha);
  36638. };
  36639. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36640. if (suffix === void 0) { suffix = ""; }
  36641. color.toArray(UniformBuffer._tempBuffer);
  36642. UniformBuffer._tempBuffer[3] = alpha;
  36643. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36644. };
  36645. /**
  36646. * Sets a sampler uniform on the effect.
  36647. * @param {string} name Name of the sampler.
  36648. * @param {Texture} texture
  36649. */
  36650. UniformBuffer.prototype.setTexture = function (name, texture) {
  36651. this._currentEffect.setTexture(name, texture);
  36652. };
  36653. /**
  36654. * Directly updates the value of the uniform in the cache AND on the GPU.
  36655. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36656. * @param {number[]|Float32Array} data Flattened data
  36657. */
  36658. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36659. this.updateUniform(uniformName, data, data.length);
  36660. this.update();
  36661. };
  36662. /**
  36663. * Binds this uniform buffer to an effect.
  36664. * @param {Effect} effect
  36665. * @param {string} name Name of the uniform block in the shader.
  36666. */
  36667. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36668. this._currentEffect = effect;
  36669. if (this._noUBO || !this._buffer) {
  36670. return;
  36671. }
  36672. effect.bindUniformBuffer(this._buffer, name);
  36673. };
  36674. /**
  36675. * Disposes the uniform buffer.
  36676. */
  36677. UniformBuffer.prototype.dispose = function () {
  36678. if (this._noUBO) {
  36679. return;
  36680. }
  36681. var index = this._engine._uniformBuffers.indexOf(this);
  36682. if (index !== -1) {
  36683. this._engine._uniformBuffers.splice(index, 1);
  36684. }
  36685. if (!this._buffer) {
  36686. return;
  36687. }
  36688. if (this._engine._releaseBuffer(this._buffer)) {
  36689. this._buffer = null;
  36690. }
  36691. };
  36692. // Pool for avoiding memory leaks
  36693. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36694. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36695. return UniformBuffer;
  36696. }());
  36697. BABYLON.UniformBuffer = UniformBuffer;
  36698. })(BABYLON || (BABYLON = {}));
  36699. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36700. var BABYLON;
  36701. (function (BABYLON) {
  36702. /**
  36703. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36704. */
  36705. var VertexData = /** @class */ (function () {
  36706. function VertexData() {
  36707. }
  36708. /**
  36709. * Uses the passed data array to set the set the values for the specified kind of data
  36710. * @param data a linear array of floating numbers
  36711. * @param kind the type of data that is being set, eg positions, colors etc
  36712. */
  36713. VertexData.prototype.set = function (data, kind) {
  36714. switch (kind) {
  36715. case BABYLON.VertexBuffer.PositionKind:
  36716. this.positions = data;
  36717. break;
  36718. case BABYLON.VertexBuffer.NormalKind:
  36719. this.normals = data;
  36720. break;
  36721. case BABYLON.VertexBuffer.TangentKind:
  36722. this.tangents = data;
  36723. break;
  36724. case BABYLON.VertexBuffer.UVKind:
  36725. this.uvs = data;
  36726. break;
  36727. case BABYLON.VertexBuffer.UV2Kind:
  36728. this.uvs2 = data;
  36729. break;
  36730. case BABYLON.VertexBuffer.UV3Kind:
  36731. this.uvs3 = data;
  36732. break;
  36733. case BABYLON.VertexBuffer.UV4Kind:
  36734. this.uvs4 = data;
  36735. break;
  36736. case BABYLON.VertexBuffer.UV5Kind:
  36737. this.uvs5 = data;
  36738. break;
  36739. case BABYLON.VertexBuffer.UV6Kind:
  36740. this.uvs6 = data;
  36741. break;
  36742. case BABYLON.VertexBuffer.ColorKind:
  36743. this.colors = data;
  36744. break;
  36745. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36746. this.matricesIndices = data;
  36747. break;
  36748. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36749. this.matricesWeights = data;
  36750. break;
  36751. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36752. this.matricesIndicesExtra = data;
  36753. break;
  36754. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36755. this.matricesWeightsExtra = data;
  36756. break;
  36757. }
  36758. };
  36759. /**
  36760. * Associates the vertexData to the passed Mesh.
  36761. * Sets it as updatable or not (default `false`)
  36762. * @param mesh the mesh the vertexData is applied to
  36763. * @param updatable when used and having the value true allows new data to update the vertexData
  36764. * @returns the VertexData
  36765. */
  36766. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36767. this._applyTo(mesh, updatable);
  36768. return this;
  36769. };
  36770. /**
  36771. * Associates the vertexData to the passed Geometry.
  36772. * Sets it as updatable or not (default `false`)
  36773. * @param geometry the geometry the vertexData is applied to
  36774. * @param updatable when used and having the value true allows new data to update the vertexData
  36775. * @returns VertexData
  36776. */
  36777. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36778. this._applyTo(geometry, updatable);
  36779. return this;
  36780. };
  36781. /**
  36782. * Updates the associated mesh
  36783. * @param mesh the mesh to be updated
  36784. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36785. * @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
  36786. * @returns VertexData
  36787. */
  36788. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36789. this._update(mesh);
  36790. return this;
  36791. };
  36792. /**
  36793. * Updates the associated geometry
  36794. * @param geometry the geometry to be updated
  36795. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36796. * @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
  36797. * @returns VertexData.
  36798. */
  36799. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36800. this._update(geometry);
  36801. return this;
  36802. };
  36803. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36804. if (updatable === void 0) { updatable = false; }
  36805. if (this.positions) {
  36806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36807. }
  36808. if (this.normals) {
  36809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36810. }
  36811. if (this.tangents) {
  36812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36813. }
  36814. if (this.uvs) {
  36815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36816. }
  36817. if (this.uvs2) {
  36818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36819. }
  36820. if (this.uvs3) {
  36821. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36822. }
  36823. if (this.uvs4) {
  36824. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36825. }
  36826. if (this.uvs5) {
  36827. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36828. }
  36829. if (this.uvs6) {
  36830. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36831. }
  36832. if (this.colors) {
  36833. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36834. }
  36835. if (this.matricesIndices) {
  36836. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36837. }
  36838. if (this.matricesWeights) {
  36839. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36840. }
  36841. if (this.matricesIndicesExtra) {
  36842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36843. }
  36844. if (this.matricesWeightsExtra) {
  36845. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36846. }
  36847. if (this.indices) {
  36848. meshOrGeometry.setIndices(this.indices, null, updatable);
  36849. }
  36850. else {
  36851. meshOrGeometry.setIndices([], null);
  36852. }
  36853. return this;
  36854. };
  36855. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36856. if (this.positions) {
  36857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36858. }
  36859. if (this.normals) {
  36860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36861. }
  36862. if (this.tangents) {
  36863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36864. }
  36865. if (this.uvs) {
  36866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36867. }
  36868. if (this.uvs2) {
  36869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36870. }
  36871. if (this.uvs3) {
  36872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36873. }
  36874. if (this.uvs4) {
  36875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36876. }
  36877. if (this.uvs5) {
  36878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36879. }
  36880. if (this.uvs6) {
  36881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36882. }
  36883. if (this.colors) {
  36884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36885. }
  36886. if (this.matricesIndices) {
  36887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36888. }
  36889. if (this.matricesWeights) {
  36890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36891. }
  36892. if (this.matricesIndicesExtra) {
  36893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36894. }
  36895. if (this.matricesWeightsExtra) {
  36896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36897. }
  36898. if (this.indices) {
  36899. meshOrGeometry.setIndices(this.indices, null);
  36900. }
  36901. return this;
  36902. };
  36903. /**
  36904. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36905. * @param matrix the transforming matrix
  36906. * @returns the VertexData
  36907. */
  36908. VertexData.prototype.transform = function (matrix) {
  36909. var transformed = BABYLON.Vector3.Zero();
  36910. var index;
  36911. if (this.positions) {
  36912. var position = BABYLON.Vector3.Zero();
  36913. for (index = 0; index < this.positions.length; index += 3) {
  36914. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36915. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36916. this.positions[index] = transformed.x;
  36917. this.positions[index + 1] = transformed.y;
  36918. this.positions[index + 2] = transformed.z;
  36919. }
  36920. }
  36921. if (this.normals) {
  36922. var normal = BABYLON.Vector3.Zero();
  36923. for (index = 0; index < this.normals.length; index += 3) {
  36924. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36925. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36926. this.normals[index] = transformed.x;
  36927. this.normals[index + 1] = transformed.y;
  36928. this.normals[index + 2] = transformed.z;
  36929. }
  36930. }
  36931. if (this.tangents) {
  36932. var tangent = BABYLON.Vector4.Zero();
  36933. var tangentTransformed = BABYLON.Vector4.Zero();
  36934. for (index = 0; index < this.tangents.length; index += 4) {
  36935. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36936. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36937. this.tangents[index] = tangentTransformed.x;
  36938. this.tangents[index + 1] = tangentTransformed.y;
  36939. this.tangents[index + 2] = tangentTransformed.z;
  36940. this.tangents[index + 3] = tangentTransformed.w;
  36941. }
  36942. }
  36943. return this;
  36944. };
  36945. /**
  36946. * Merges the passed VertexData into the current one
  36947. * @param other the VertexData to be merged into the current one
  36948. * @returns the modified VertexData
  36949. */
  36950. VertexData.prototype.merge = function (other) {
  36951. this._validate();
  36952. other._validate();
  36953. if (!this.normals !== !other.normals ||
  36954. !this.tangents !== !other.tangents ||
  36955. !this.uvs !== !other.uvs ||
  36956. !this.uvs2 !== !other.uvs2 ||
  36957. !this.uvs3 !== !other.uvs3 ||
  36958. !this.uvs4 !== !other.uvs4 ||
  36959. !this.uvs5 !== !other.uvs5 ||
  36960. !this.uvs6 !== !other.uvs6 ||
  36961. !this.colors !== !other.colors ||
  36962. !this.matricesIndices !== !other.matricesIndices ||
  36963. !this.matricesWeights !== !other.matricesWeights ||
  36964. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36965. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36966. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36967. }
  36968. if (other.indices) {
  36969. if (!this.indices) {
  36970. this.indices = [];
  36971. }
  36972. var offset = this.positions ? this.positions.length / 3 : 0;
  36973. for (var index = 0; index < other.indices.length; index++) {
  36974. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36975. this.indices.push(other.indices[index] + offset);
  36976. }
  36977. }
  36978. this.positions = this._mergeElement(this.positions, other.positions);
  36979. this.normals = this._mergeElement(this.normals, other.normals);
  36980. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36981. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36982. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36983. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36984. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36985. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36986. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36987. this.colors = this._mergeElement(this.colors, other.colors);
  36988. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36989. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36990. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36991. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36992. return this;
  36993. };
  36994. VertexData.prototype._mergeElement = function (source, other) {
  36995. if (!source) {
  36996. return other;
  36997. }
  36998. if (!other) {
  36999. return source;
  37000. }
  37001. var len = other.length + source.length;
  37002. var isSrcTypedArray = source instanceof Float32Array;
  37003. var isOthTypedArray = other instanceof Float32Array;
  37004. // use non-loop method when the source is Float32Array
  37005. if (isSrcTypedArray) {
  37006. var ret32 = new Float32Array(len);
  37007. ret32.set(source);
  37008. ret32.set(other, source.length);
  37009. return ret32;
  37010. // source is number[], when other is also use concat
  37011. }
  37012. else if (!isOthTypedArray) {
  37013. return source.concat(other);
  37014. // source is a number[], but other is a Float32Array, loop required
  37015. }
  37016. else {
  37017. var ret = source.slice(0); // copy source to a separate array
  37018. for (var i = 0, len = other.length; i < len; i++) {
  37019. ret.push(other[i]);
  37020. }
  37021. return ret;
  37022. }
  37023. };
  37024. VertexData.prototype._validate = function () {
  37025. if (!this.positions) {
  37026. throw new Error("Positions are required");
  37027. }
  37028. var getElementCount = function (kind, values) {
  37029. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37030. if ((values.length % stride) !== 0) {
  37031. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37032. }
  37033. return values.length / stride;
  37034. };
  37035. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37036. var validateElementCount = function (kind, values) {
  37037. var elementCount = getElementCount(kind, values);
  37038. if (elementCount !== positionsElementCount) {
  37039. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37040. }
  37041. };
  37042. if (this.normals)
  37043. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37044. if (this.tangents)
  37045. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37046. if (this.uvs)
  37047. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37048. if (this.uvs2)
  37049. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37050. if (this.uvs3)
  37051. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37052. if (this.uvs4)
  37053. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37054. if (this.uvs5)
  37055. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37056. if (this.uvs6)
  37057. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37058. if (this.colors)
  37059. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37060. if (this.matricesIndices)
  37061. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37062. if (this.matricesWeights)
  37063. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37064. if (this.matricesIndicesExtra)
  37065. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37066. if (this.matricesWeightsExtra)
  37067. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37068. };
  37069. /**
  37070. * Serializes the VertexData
  37071. * @returns a serialized object
  37072. */
  37073. VertexData.prototype.serialize = function () {
  37074. var serializationObject = this.serialize();
  37075. if (this.positions) {
  37076. serializationObject.positions = this.positions;
  37077. }
  37078. if (this.normals) {
  37079. serializationObject.normals = this.normals;
  37080. }
  37081. if (this.tangents) {
  37082. serializationObject.tangents = this.tangents;
  37083. }
  37084. if (this.uvs) {
  37085. serializationObject.uvs = this.uvs;
  37086. }
  37087. if (this.uvs2) {
  37088. serializationObject.uvs2 = this.uvs2;
  37089. }
  37090. if (this.uvs3) {
  37091. serializationObject.uvs3 = this.uvs3;
  37092. }
  37093. if (this.uvs4) {
  37094. serializationObject.uvs4 = this.uvs4;
  37095. }
  37096. if (this.uvs5) {
  37097. serializationObject.uvs5 = this.uvs5;
  37098. }
  37099. if (this.uvs6) {
  37100. serializationObject.uvs6 = this.uvs6;
  37101. }
  37102. if (this.colors) {
  37103. serializationObject.colors = this.colors;
  37104. }
  37105. if (this.matricesIndices) {
  37106. serializationObject.matricesIndices = this.matricesIndices;
  37107. serializationObject.matricesIndices._isExpanded = true;
  37108. }
  37109. if (this.matricesWeights) {
  37110. serializationObject.matricesWeights = this.matricesWeights;
  37111. }
  37112. if (this.matricesIndicesExtra) {
  37113. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37114. serializationObject.matricesIndicesExtra._isExpanded = true;
  37115. }
  37116. if (this.matricesWeightsExtra) {
  37117. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37118. }
  37119. serializationObject.indices = this.indices;
  37120. return serializationObject;
  37121. };
  37122. // Statics
  37123. /**
  37124. * Extracts the vertexData from a mesh
  37125. * @param mesh the mesh from which to extract the VertexData
  37126. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37127. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37128. * @returns the object VertexData associated to the passed mesh
  37129. */
  37130. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37131. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37132. };
  37133. /**
  37134. * Extracts the vertexData from the geometry
  37135. * @param geometry the geometry from which to extract the VertexData
  37136. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37137. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37138. * @returns the object VertexData associated to the passed mesh
  37139. */
  37140. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37141. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37142. };
  37143. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37144. var result = new VertexData();
  37145. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37146. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37147. }
  37148. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37149. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37150. }
  37151. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37152. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37153. }
  37154. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37155. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37156. }
  37157. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37158. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37159. }
  37160. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37161. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37162. }
  37163. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37164. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37165. }
  37166. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37167. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37168. }
  37169. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37170. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37171. }
  37172. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37173. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37174. }
  37175. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37176. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37177. }
  37178. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37179. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37180. }
  37181. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37182. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37183. }
  37184. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37185. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37186. }
  37187. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37188. return result;
  37189. };
  37190. /**
  37191. * Creates the VertexData for a Ribbon
  37192. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37193. * * pathArray array of paths, each of which an array of successive Vector3
  37194. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37195. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37196. * * 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
  37197. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37198. * * 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)
  37199. * * 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)
  37200. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37201. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37202. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37203. * @returns the VertexData of the ribbon
  37204. */
  37205. VertexData.CreateRibbon = function (options) {
  37206. var pathArray = options.pathArray;
  37207. var closeArray = options.closeArray || false;
  37208. var closePath = options.closePath || false;
  37209. var invertUV = options.invertUV || false;
  37210. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37211. var offset = options.offset || defaultOffset;
  37212. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37213. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37214. var customUV = options.uvs;
  37215. var customColors = options.colors;
  37216. var positions = [];
  37217. var indices = [];
  37218. var normals = [];
  37219. var uvs = [];
  37220. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37221. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37222. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37223. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37224. var minlg; // minimal length among all paths from pathArray
  37225. var lg = []; // array of path lengths : nb of vertex per path
  37226. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37227. var p; // path iterator
  37228. var i; // point iterator
  37229. var j; // point iterator
  37230. // if single path in pathArray
  37231. if (pathArray.length < 2) {
  37232. var ar1 = [];
  37233. var ar2 = [];
  37234. for (i = 0; i < pathArray[0].length - offset; i++) {
  37235. ar1.push(pathArray[0][i]);
  37236. ar2.push(pathArray[0][i + offset]);
  37237. }
  37238. pathArray = [ar1, ar2];
  37239. }
  37240. // positions and horizontal distances (u)
  37241. var idc = 0;
  37242. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37243. var path;
  37244. var l;
  37245. minlg = pathArray[0].length;
  37246. var vectlg;
  37247. var dist;
  37248. for (p = 0; p < pathArray.length; p++) {
  37249. uTotalDistance[p] = 0;
  37250. us[p] = [0];
  37251. path = pathArray[p];
  37252. l = path.length;
  37253. minlg = (minlg < l) ? minlg : l;
  37254. j = 0;
  37255. while (j < l) {
  37256. positions.push(path[j].x, path[j].y, path[j].z);
  37257. if (j > 0) {
  37258. vectlg = path[j].subtract(path[j - 1]).length();
  37259. dist = vectlg + uTotalDistance[p];
  37260. us[p].push(dist);
  37261. uTotalDistance[p] = dist;
  37262. }
  37263. j++;
  37264. }
  37265. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37266. j--;
  37267. positions.push(path[0].x, path[0].y, path[0].z);
  37268. vectlg = path[j].subtract(path[0]).length();
  37269. dist = vectlg + uTotalDistance[p];
  37270. us[p].push(dist);
  37271. uTotalDistance[p] = dist;
  37272. }
  37273. lg[p] = l + closePathCorr;
  37274. idx[p] = idc;
  37275. idc += (l + closePathCorr);
  37276. }
  37277. // vertical distances (v)
  37278. var path1;
  37279. var path2;
  37280. var vertex1 = null;
  37281. var vertex2 = null;
  37282. for (i = 0; i < minlg + closePathCorr; i++) {
  37283. vTotalDistance[i] = 0;
  37284. vs[i] = [0];
  37285. for (p = 0; p < pathArray.length - 1; p++) {
  37286. path1 = pathArray[p];
  37287. path2 = pathArray[p + 1];
  37288. if (i === minlg) { // closePath
  37289. vertex1 = path1[0];
  37290. vertex2 = path2[0];
  37291. }
  37292. else {
  37293. vertex1 = path1[i];
  37294. vertex2 = path2[i];
  37295. }
  37296. vectlg = vertex2.subtract(vertex1).length();
  37297. dist = vectlg + vTotalDistance[i];
  37298. vs[i].push(dist);
  37299. vTotalDistance[i] = dist;
  37300. }
  37301. if (closeArray && vertex2 && vertex1) {
  37302. path1 = pathArray[p];
  37303. path2 = pathArray[0];
  37304. if (i === minlg) { // closePath
  37305. vertex2 = path2[0];
  37306. }
  37307. vectlg = vertex2.subtract(vertex1).length();
  37308. dist = vectlg + vTotalDistance[i];
  37309. vTotalDistance[i] = dist;
  37310. }
  37311. }
  37312. // uvs
  37313. var u;
  37314. var v;
  37315. if (customUV) {
  37316. for (p = 0; p < customUV.length; p++) {
  37317. uvs.push(customUV[p].x, customUV[p].y);
  37318. }
  37319. }
  37320. else {
  37321. for (p = 0; p < pathArray.length; p++) {
  37322. for (i = 0; i < minlg + closePathCorr; i++) {
  37323. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37324. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37325. if (invertUV) {
  37326. uvs.push(v, u);
  37327. }
  37328. else {
  37329. uvs.push(u, v);
  37330. }
  37331. }
  37332. }
  37333. }
  37334. // indices
  37335. p = 0; // path index
  37336. var pi = 0; // positions array index
  37337. var l1 = lg[p] - 1; // path1 length
  37338. var l2 = lg[p + 1] - 1; // path2 length
  37339. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37340. var shft = idx[1] - idx[0]; // shift
  37341. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37342. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37343. // 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
  37344. indices.push(pi, pi + shft, pi + 1);
  37345. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37346. pi += 1;
  37347. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37348. p++;
  37349. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37350. shft = idx[0] - idx[p];
  37351. l1 = lg[p] - 1;
  37352. l2 = lg[0] - 1;
  37353. }
  37354. else {
  37355. shft = idx[p + 1] - idx[p];
  37356. l1 = lg[p] - 1;
  37357. l2 = lg[p + 1] - 1;
  37358. }
  37359. pi = idx[p];
  37360. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37361. }
  37362. }
  37363. // normals
  37364. VertexData.ComputeNormals(positions, indices, normals);
  37365. if (closePath) { // update both the first and last vertex normals to their average value
  37366. var indexFirst = 0;
  37367. var indexLast = 0;
  37368. for (p = 0; p < pathArray.length; p++) {
  37369. indexFirst = idx[p] * 3;
  37370. if (p + 1 < pathArray.length) {
  37371. indexLast = (idx[p + 1] - 1) * 3;
  37372. }
  37373. else {
  37374. indexLast = normals.length - 3;
  37375. }
  37376. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37377. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37378. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37379. normals[indexLast] = normals[indexFirst];
  37380. normals[indexLast + 1] = normals[indexFirst + 1];
  37381. normals[indexLast + 2] = normals[indexFirst + 2];
  37382. }
  37383. }
  37384. // sides
  37385. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37386. // Colors
  37387. var colors = null;
  37388. if (customColors) {
  37389. colors = new Float32Array(customColors.length * 4);
  37390. for (var c = 0; c < customColors.length; c++) {
  37391. colors[c * 4] = customColors[c].r;
  37392. colors[c * 4 + 1] = customColors[c].g;
  37393. colors[c * 4 + 2] = customColors[c].b;
  37394. colors[c * 4 + 3] = customColors[c].a;
  37395. }
  37396. }
  37397. // Result
  37398. var vertexData = new VertexData();
  37399. var positions32 = new Float32Array(positions);
  37400. var normals32 = new Float32Array(normals);
  37401. var uvs32 = new Float32Array(uvs);
  37402. vertexData.indices = indices;
  37403. vertexData.positions = positions32;
  37404. vertexData.normals = normals32;
  37405. vertexData.uvs = uvs32;
  37406. if (colors) {
  37407. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37408. }
  37409. if (closePath) {
  37410. vertexData._idx = idx;
  37411. }
  37412. return vertexData;
  37413. };
  37414. /**
  37415. * Creates the VertexData for a box
  37416. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37417. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37418. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37419. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37420. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37421. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37422. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37423. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37424. * * 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)
  37425. * * 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)
  37426. * @returns the VertexData of the box
  37427. */
  37428. VertexData.CreateBox = function (options) {
  37429. var normalsSource = [
  37430. new BABYLON.Vector3(0, 0, 1),
  37431. new BABYLON.Vector3(0, 0, -1),
  37432. new BABYLON.Vector3(1, 0, 0),
  37433. new BABYLON.Vector3(-1, 0, 0),
  37434. new BABYLON.Vector3(0, 1, 0),
  37435. new BABYLON.Vector3(0, -1, 0)
  37436. ];
  37437. var indices = [];
  37438. var positions = [];
  37439. var normals = [];
  37440. var uvs = [];
  37441. var width = options.width || options.size || 1;
  37442. var height = options.height || options.size || 1;
  37443. var depth = options.depth || options.size || 1;
  37444. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37445. var faceUV = options.faceUV || new Array(6);
  37446. var faceColors = options.faceColors;
  37447. var colors = [];
  37448. // default face colors and UV if undefined
  37449. for (var f = 0; f < 6; f++) {
  37450. if (faceUV[f] === undefined) {
  37451. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37452. }
  37453. if (faceColors && faceColors[f] === undefined) {
  37454. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37455. }
  37456. }
  37457. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37458. // Create each face in turn.
  37459. for (var index = 0; index < normalsSource.length; index++) {
  37460. var normal = normalsSource[index];
  37461. // Get two vectors perpendicular to the face normal and to each other.
  37462. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37463. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37464. // Six indices (two triangles) per face.
  37465. var verticesLength = positions.length / 3;
  37466. indices.push(verticesLength);
  37467. indices.push(verticesLength + 1);
  37468. indices.push(verticesLength + 2);
  37469. indices.push(verticesLength);
  37470. indices.push(verticesLength + 2);
  37471. indices.push(verticesLength + 3);
  37472. // Four vertices per face.
  37473. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37474. positions.push(vertex.x, vertex.y, vertex.z);
  37475. normals.push(normal.x, normal.y, normal.z);
  37476. uvs.push(faceUV[index].z, faceUV[index].w);
  37477. if (faceColors) {
  37478. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37479. }
  37480. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37481. positions.push(vertex.x, vertex.y, vertex.z);
  37482. normals.push(normal.x, normal.y, normal.z);
  37483. uvs.push(faceUV[index].x, faceUV[index].w);
  37484. if (faceColors) {
  37485. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37486. }
  37487. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37488. positions.push(vertex.x, vertex.y, vertex.z);
  37489. normals.push(normal.x, normal.y, normal.z);
  37490. uvs.push(faceUV[index].x, faceUV[index].y);
  37491. if (faceColors) {
  37492. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37493. }
  37494. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37495. positions.push(vertex.x, vertex.y, vertex.z);
  37496. normals.push(normal.x, normal.y, normal.z);
  37497. uvs.push(faceUV[index].z, faceUV[index].y);
  37498. if (faceColors) {
  37499. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37500. }
  37501. }
  37502. // sides
  37503. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37504. // Result
  37505. var vertexData = new VertexData();
  37506. vertexData.indices = indices;
  37507. vertexData.positions = positions;
  37508. vertexData.normals = normals;
  37509. vertexData.uvs = uvs;
  37510. if (faceColors) {
  37511. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37512. vertexData.colors = totalColors;
  37513. }
  37514. return vertexData;
  37515. };
  37516. /**
  37517. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37518. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37519. * * segments sets the number of horizontal strips optional, default 32
  37520. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37521. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37522. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37523. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37524. * * 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
  37525. * * 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
  37526. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37527. * * 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)
  37528. * * 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)
  37529. * @returns the VertexData of the ellipsoid
  37530. */
  37531. VertexData.CreateSphere = function (options) {
  37532. var segments = options.segments || 32;
  37533. var diameterX = options.diameterX || options.diameter || 1;
  37534. var diameterY = options.diameterY || options.diameter || 1;
  37535. var diameterZ = options.diameterZ || options.diameter || 1;
  37536. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37537. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37538. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37539. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37540. var totalZRotationSteps = 2 + segments;
  37541. var totalYRotationSteps = 2 * totalZRotationSteps;
  37542. var indices = [];
  37543. var positions = [];
  37544. var normals = [];
  37545. var uvs = [];
  37546. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37547. var normalizedZ = zRotationStep / totalZRotationSteps;
  37548. var angleZ = normalizedZ * Math.PI * slice;
  37549. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37550. var normalizedY = yRotationStep / totalYRotationSteps;
  37551. var angleY = normalizedY * Math.PI * 2 * arc;
  37552. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37553. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37554. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37555. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37556. var vertex = complete.multiply(radius);
  37557. var normal = complete.divide(radius).normalize();
  37558. positions.push(vertex.x, vertex.y, vertex.z);
  37559. normals.push(normal.x, normal.y, normal.z);
  37560. uvs.push(normalizedY, normalizedZ);
  37561. }
  37562. if (zRotationStep > 0) {
  37563. var verticesCount = positions.length / 3;
  37564. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37565. indices.push((firstIndex));
  37566. indices.push((firstIndex + 1));
  37567. indices.push(firstIndex + totalYRotationSteps + 1);
  37568. indices.push((firstIndex + totalYRotationSteps + 1));
  37569. indices.push((firstIndex + 1));
  37570. indices.push((firstIndex + totalYRotationSteps + 2));
  37571. }
  37572. }
  37573. }
  37574. // Sides
  37575. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37576. // Result
  37577. var vertexData = new VertexData();
  37578. vertexData.indices = indices;
  37579. vertexData.positions = positions;
  37580. vertexData.normals = normals;
  37581. vertexData.uvs = uvs;
  37582. return vertexData;
  37583. };
  37584. /**
  37585. * Creates the VertexData for a cylinder, cone or prism
  37586. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37587. * * height sets the height (y direction) of the cylinder, optional, default 2
  37588. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37589. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37590. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37591. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37592. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37593. * * 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
  37594. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37595. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37596. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37597. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37598. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37599. * * 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)
  37600. * * 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)
  37601. * @returns the VertexData of the cylinder, cone or prism
  37602. */
  37603. VertexData.CreateCylinder = function (options) {
  37604. var height = options.height || 2;
  37605. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37606. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37607. var tessellation = options.tessellation || 24;
  37608. var subdivisions = options.subdivisions || 1;
  37609. var hasRings = options.hasRings ? true : false;
  37610. var enclose = options.enclose ? true : false;
  37611. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37612. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37613. var faceUV = options.faceUV || new Array(3);
  37614. var faceColors = options.faceColors;
  37615. // default face colors and UV if undefined
  37616. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37617. var ringNb = (hasRings) ? subdivisions : 1;
  37618. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37619. var f;
  37620. for (f = 0; f < surfaceNb; f++) {
  37621. if (faceColors && faceColors[f] === undefined) {
  37622. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37623. }
  37624. }
  37625. for (f = 0; f < surfaceNb; f++) {
  37626. if (faceUV && faceUV[f] === undefined) {
  37627. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37628. }
  37629. }
  37630. var indices = new Array();
  37631. var positions = new Array();
  37632. var normals = new Array();
  37633. var uvs = new Array();
  37634. var colors = new Array();
  37635. var angle_step = Math.PI * 2 * arc / tessellation;
  37636. var angle;
  37637. var h;
  37638. var radius;
  37639. var tan = (diameterBottom - diameterTop) / 2 / height;
  37640. var ringVertex = BABYLON.Vector3.Zero();
  37641. var ringNormal = BABYLON.Vector3.Zero();
  37642. var ringFirstVertex = BABYLON.Vector3.Zero();
  37643. var ringFirstNormal = BABYLON.Vector3.Zero();
  37644. var quadNormal = BABYLON.Vector3.Zero();
  37645. var Y = BABYLON.Axis.Y;
  37646. // positions, normals, uvs
  37647. var i;
  37648. var j;
  37649. var r;
  37650. var ringIdx = 1;
  37651. var s = 1; // surface index
  37652. var cs = 0;
  37653. var v = 0;
  37654. for (i = 0; i <= subdivisions; i++) {
  37655. h = i / subdivisions;
  37656. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37657. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37658. for (r = 0; r < ringIdx; r++) {
  37659. if (hasRings) {
  37660. s += r;
  37661. }
  37662. if (enclose) {
  37663. s += 2 * r;
  37664. }
  37665. for (j = 0; j <= tessellation; j++) {
  37666. angle = j * angle_step;
  37667. // position
  37668. ringVertex.x = Math.cos(-angle) * radius;
  37669. ringVertex.y = -height / 2 + h * height;
  37670. ringVertex.z = Math.sin(-angle) * radius;
  37671. // normal
  37672. if (diameterTop === 0 && i === subdivisions) {
  37673. // if no top cap, reuse former normals
  37674. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37675. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37676. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37677. }
  37678. else {
  37679. ringNormal.x = ringVertex.x;
  37680. ringNormal.z = ringVertex.z;
  37681. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37682. ringNormal.normalize();
  37683. }
  37684. // keep first ring vertex values for enclose
  37685. if (j === 0) {
  37686. ringFirstVertex.copyFrom(ringVertex);
  37687. ringFirstNormal.copyFrom(ringNormal);
  37688. }
  37689. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37690. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37691. if (hasRings) {
  37692. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37693. }
  37694. else {
  37695. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37696. }
  37697. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37698. if (faceColors) {
  37699. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37700. }
  37701. }
  37702. // if enclose, add four vertices and their dedicated normals
  37703. if (arc !== 1 && enclose) {
  37704. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37705. positions.push(0, ringVertex.y, 0);
  37706. positions.push(0, ringVertex.y, 0);
  37707. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37708. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37709. quadNormal.normalize();
  37710. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37711. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37712. quadNormal.normalize();
  37713. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37714. if (hasRings) {
  37715. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37716. }
  37717. else {
  37718. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37719. }
  37720. uvs.push(faceUV[s + 1].x, v);
  37721. uvs.push(faceUV[s + 1].z, v);
  37722. if (hasRings) {
  37723. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37724. }
  37725. else {
  37726. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37727. }
  37728. uvs.push(faceUV[s + 2].x, v);
  37729. uvs.push(faceUV[s + 2].z, v);
  37730. if (faceColors) {
  37731. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37732. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37733. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37734. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37735. }
  37736. }
  37737. if (cs !== s) {
  37738. cs = s;
  37739. }
  37740. }
  37741. }
  37742. // indices
  37743. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37744. var s;
  37745. i = 0;
  37746. for (s = 0; s < subdivisions; s++) {
  37747. var i0 = 0;
  37748. var i1 = 0;
  37749. var i2 = 0;
  37750. var i3 = 0;
  37751. for (j = 0; j < tessellation; j++) {
  37752. i0 = i * (e + 1) + j;
  37753. i1 = (i + 1) * (e + 1) + j;
  37754. i2 = i * (e + 1) + (j + 1);
  37755. i3 = (i + 1) * (e + 1) + (j + 1);
  37756. indices.push(i0, i1, i2);
  37757. indices.push(i3, i2, i1);
  37758. }
  37759. if (arc !== 1 && enclose) { // if enclose, add two quads
  37760. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37761. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37762. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37763. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37764. }
  37765. i = (hasRings) ? (i + 2) : (i + 1);
  37766. }
  37767. // Caps
  37768. var createCylinderCap = function (isTop) {
  37769. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37770. if (radius === 0) {
  37771. return;
  37772. }
  37773. // Cap positions, normals & uvs
  37774. var angle;
  37775. var circleVector;
  37776. var i;
  37777. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37778. var c = null;
  37779. if (faceColors) {
  37780. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37781. }
  37782. // cap center
  37783. var vbase = positions.length / 3;
  37784. var offset = isTop ? height / 2 : -height / 2;
  37785. var center = new BABYLON.Vector3(0, offset, 0);
  37786. positions.push(center.x, center.y, center.z);
  37787. normals.push(0, isTop ? 1 : -1, 0);
  37788. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37789. if (c) {
  37790. colors.push(c.r, c.g, c.b, c.a);
  37791. }
  37792. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37793. for (i = 0; i <= tessellation; i++) {
  37794. angle = Math.PI * 2 * i * arc / tessellation;
  37795. var cos = Math.cos(-angle);
  37796. var sin = Math.sin(-angle);
  37797. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37798. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37799. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37800. normals.push(0, isTop ? 1 : -1, 0);
  37801. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37802. if (c) {
  37803. colors.push(c.r, c.g, c.b, c.a);
  37804. }
  37805. }
  37806. // Cap indices
  37807. for (i = 0; i < tessellation; i++) {
  37808. if (!isTop) {
  37809. indices.push(vbase);
  37810. indices.push(vbase + (i + 1));
  37811. indices.push(vbase + (i + 2));
  37812. }
  37813. else {
  37814. indices.push(vbase);
  37815. indices.push(vbase + (i + 2));
  37816. indices.push(vbase + (i + 1));
  37817. }
  37818. }
  37819. };
  37820. // add caps to geometry
  37821. createCylinderCap(false);
  37822. createCylinderCap(true);
  37823. // Sides
  37824. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37825. var vertexData = new VertexData();
  37826. vertexData.indices = indices;
  37827. vertexData.positions = positions;
  37828. vertexData.normals = normals;
  37829. vertexData.uvs = uvs;
  37830. if (faceColors) {
  37831. vertexData.colors = colors;
  37832. }
  37833. return vertexData;
  37834. };
  37835. /**
  37836. * Creates the VertexData for a torus
  37837. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37838. * * diameter the diameter of the torus, optional default 1
  37839. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37840. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37841. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37842. * * 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)
  37843. * * 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)
  37844. * @returns the VertexData of the torus
  37845. */
  37846. VertexData.CreateTorus = function (options) {
  37847. var indices = [];
  37848. var positions = [];
  37849. var normals = [];
  37850. var uvs = [];
  37851. var diameter = options.diameter || 1;
  37852. var thickness = options.thickness || 0.5;
  37853. var tessellation = options.tessellation || 16;
  37854. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37855. var stride = tessellation + 1;
  37856. for (var i = 0; i <= tessellation; i++) {
  37857. var u = i / tessellation;
  37858. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37859. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37860. for (var j = 0; j <= tessellation; j++) {
  37861. var v = 1 - j / tessellation;
  37862. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37863. var dx = Math.cos(innerAngle);
  37864. var dy = Math.sin(innerAngle);
  37865. // Create a vertex.
  37866. var normal = new BABYLON.Vector3(dx, dy, 0);
  37867. var position = normal.scale(thickness / 2);
  37868. var textureCoordinate = new BABYLON.Vector2(u, v);
  37869. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37870. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37871. positions.push(position.x, position.y, position.z);
  37872. normals.push(normal.x, normal.y, normal.z);
  37873. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37874. // And create indices for two triangles.
  37875. var nextI = (i + 1) % stride;
  37876. var nextJ = (j + 1) % stride;
  37877. indices.push(i * stride + j);
  37878. indices.push(i * stride + nextJ);
  37879. indices.push(nextI * stride + j);
  37880. indices.push(i * stride + nextJ);
  37881. indices.push(nextI * stride + nextJ);
  37882. indices.push(nextI * stride + j);
  37883. }
  37884. }
  37885. // Sides
  37886. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37887. // Result
  37888. var vertexData = new VertexData();
  37889. vertexData.indices = indices;
  37890. vertexData.positions = positions;
  37891. vertexData.normals = normals;
  37892. vertexData.uvs = uvs;
  37893. return vertexData;
  37894. };
  37895. /**
  37896. * Creates the VertexData of the LineSystem
  37897. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37898. * - lines an array of lines, each line being an array of successive Vector3
  37899. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37900. * @returns the VertexData of the LineSystem
  37901. */
  37902. VertexData.CreateLineSystem = function (options) {
  37903. var indices = [];
  37904. var positions = [];
  37905. var lines = options.lines;
  37906. var colors = options.colors;
  37907. var vertexColors = [];
  37908. var idx = 0;
  37909. for (var l = 0; l < lines.length; l++) {
  37910. var points = lines[l];
  37911. for (var index = 0; index < points.length; index++) {
  37912. positions.push(points[index].x, points[index].y, points[index].z);
  37913. if (colors) {
  37914. var color = colors[l];
  37915. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37916. }
  37917. if (index > 0) {
  37918. indices.push(idx - 1);
  37919. indices.push(idx);
  37920. }
  37921. idx++;
  37922. }
  37923. }
  37924. var vertexData = new VertexData();
  37925. vertexData.indices = indices;
  37926. vertexData.positions = positions;
  37927. if (colors) {
  37928. vertexData.colors = vertexColors;
  37929. }
  37930. return vertexData;
  37931. };
  37932. /**
  37933. * Create the VertexData for a DashedLines
  37934. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37935. * - points an array successive Vector3
  37936. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37937. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37938. * - dashNb the intended total number of dashes, optional, default 200
  37939. * @returns the VertexData for the DashedLines
  37940. */
  37941. VertexData.CreateDashedLines = function (options) {
  37942. var dashSize = options.dashSize || 3;
  37943. var gapSize = options.gapSize || 1;
  37944. var dashNb = options.dashNb || 200;
  37945. var points = options.points;
  37946. var positions = new Array();
  37947. var indices = new Array();
  37948. var curvect = BABYLON.Vector3.Zero();
  37949. var lg = 0;
  37950. var nb = 0;
  37951. var shft = 0;
  37952. var dashshft = 0;
  37953. var curshft = 0;
  37954. var idx = 0;
  37955. var i = 0;
  37956. for (i = 0; i < points.length - 1; i++) {
  37957. points[i + 1].subtractToRef(points[i], curvect);
  37958. lg += curvect.length();
  37959. }
  37960. shft = lg / dashNb;
  37961. dashshft = dashSize * shft / (dashSize + gapSize);
  37962. for (i = 0; i < points.length - 1; i++) {
  37963. points[i + 1].subtractToRef(points[i], curvect);
  37964. nb = Math.floor(curvect.length() / shft);
  37965. curvect.normalize();
  37966. for (var j = 0; j < nb; j++) {
  37967. curshft = shft * j;
  37968. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37969. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37970. indices.push(idx, idx + 1);
  37971. idx += 2;
  37972. }
  37973. }
  37974. // Result
  37975. var vertexData = new VertexData();
  37976. vertexData.positions = positions;
  37977. vertexData.indices = indices;
  37978. return vertexData;
  37979. };
  37980. /**
  37981. * Creates the VertexData for a Ground
  37982. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37983. * - width the width (x direction) of the ground, optional, default 1
  37984. * - height the height (z direction) of the ground, optional, default 1
  37985. * - subdivisions the number of subdivisions per side, optional, default 1
  37986. * @returns the VertexData of the Ground
  37987. */
  37988. VertexData.CreateGround = function (options) {
  37989. var indices = [];
  37990. var positions = [];
  37991. var normals = [];
  37992. var uvs = [];
  37993. var row, col;
  37994. var width = options.width || 1;
  37995. var height = options.height || 1;
  37996. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37997. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37998. for (row = 0; row <= subdivisionsY; row++) {
  37999. for (col = 0; col <= subdivisionsX; col++) {
  38000. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38001. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38002. positions.push(position.x, position.y, position.z);
  38003. normals.push(normal.x, normal.y, normal.z);
  38004. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38005. }
  38006. }
  38007. for (row = 0; row < subdivisionsY; row++) {
  38008. for (col = 0; col < subdivisionsX; col++) {
  38009. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38010. indices.push(col + 1 + row * (subdivisionsX + 1));
  38011. indices.push(col + row * (subdivisionsX + 1));
  38012. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38013. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38014. indices.push(col + row * (subdivisionsX + 1));
  38015. }
  38016. }
  38017. // Result
  38018. var vertexData = new VertexData();
  38019. vertexData.indices = indices;
  38020. vertexData.positions = positions;
  38021. vertexData.normals = normals;
  38022. vertexData.uvs = uvs;
  38023. return vertexData;
  38024. };
  38025. /**
  38026. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38027. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38028. * * xmin the ground minimum X coordinate, optional, default -1
  38029. * * zmin the ground minimum Z coordinate, optional, default -1
  38030. * * xmax the ground maximum X coordinate, optional, default 1
  38031. * * zmax the ground maximum Z coordinate, optional, default 1
  38032. * * 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}
  38033. * * 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}
  38034. * @returns the VertexData of the TiledGround
  38035. */
  38036. VertexData.CreateTiledGround = function (options) {
  38037. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38038. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38039. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38040. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38041. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38042. var precision = options.precision || { w: 1, h: 1 };
  38043. var indices = new Array();
  38044. var positions = new Array();
  38045. var normals = new Array();
  38046. var uvs = new Array();
  38047. var row, col, tileRow, tileCol;
  38048. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38049. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38050. precision.w = (precision.w < 1) ? 1 : precision.w;
  38051. precision.h = (precision.h < 1) ? 1 : precision.h;
  38052. var tileSize = {
  38053. 'w': (xmax - xmin) / subdivisions.w,
  38054. 'h': (zmax - zmin) / subdivisions.h
  38055. };
  38056. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38057. // Indices
  38058. var base = positions.length / 3;
  38059. var rowLength = precision.w + 1;
  38060. for (row = 0; row < precision.h; row++) {
  38061. for (col = 0; col < precision.w; col++) {
  38062. var square = [
  38063. base + col + row * rowLength,
  38064. base + (col + 1) + row * rowLength,
  38065. base + (col + 1) + (row + 1) * rowLength,
  38066. base + col + (row + 1) * rowLength
  38067. ];
  38068. indices.push(square[1]);
  38069. indices.push(square[2]);
  38070. indices.push(square[3]);
  38071. indices.push(square[0]);
  38072. indices.push(square[1]);
  38073. indices.push(square[3]);
  38074. }
  38075. }
  38076. // Position, normals and uvs
  38077. var position = BABYLON.Vector3.Zero();
  38078. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38079. for (row = 0; row <= precision.h; row++) {
  38080. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38081. for (col = 0; col <= precision.w; col++) {
  38082. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38083. position.y = 0;
  38084. positions.push(position.x, position.y, position.z);
  38085. normals.push(normal.x, normal.y, normal.z);
  38086. uvs.push(col / precision.w, row / precision.h);
  38087. }
  38088. }
  38089. }
  38090. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38091. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38092. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38093. }
  38094. }
  38095. // Result
  38096. var vertexData = new VertexData();
  38097. vertexData.indices = indices;
  38098. vertexData.positions = positions;
  38099. vertexData.normals = normals;
  38100. vertexData.uvs = uvs;
  38101. return vertexData;
  38102. };
  38103. /**
  38104. * Creates the VertexData of the Ground designed from a heightmap
  38105. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38106. * * width the width (x direction) of the ground
  38107. * * height the height (z direction) of the ground
  38108. * * subdivisions the number of subdivisions per side
  38109. * * minHeight the minimum altitude on the ground, optional, default 0
  38110. * * maxHeight the maximum altitude on the ground, optional default 1
  38111. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38112. * * buffer the array holding the image color data
  38113. * * bufferWidth the width of image
  38114. * * bufferHeight the height of image
  38115. * @returns the VertexData of the Ground designed from a heightmap
  38116. */
  38117. VertexData.CreateGroundFromHeightMap = function (options) {
  38118. var indices = [];
  38119. var positions = [];
  38120. var normals = [];
  38121. var uvs = [];
  38122. var row, col;
  38123. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38124. // Vertices
  38125. for (row = 0; row <= options.subdivisions; row++) {
  38126. for (col = 0; col <= options.subdivisions; col++) {
  38127. 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));
  38128. // Compute height
  38129. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38130. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38131. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38132. var r = options.buffer[pos] / 255.0;
  38133. var g = options.buffer[pos + 1] / 255.0;
  38134. var b = options.buffer[pos + 2] / 255.0;
  38135. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38136. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38137. // Add vertex
  38138. positions.push(position.x, position.y, position.z);
  38139. normals.push(0, 0, 0);
  38140. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38141. }
  38142. }
  38143. // Indices
  38144. for (row = 0; row < options.subdivisions; row++) {
  38145. for (col = 0; col < options.subdivisions; col++) {
  38146. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38147. indices.push(col + 1 + row * (options.subdivisions + 1));
  38148. indices.push(col + row * (options.subdivisions + 1));
  38149. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38150. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38151. indices.push(col + row * (options.subdivisions + 1));
  38152. }
  38153. }
  38154. // Normals
  38155. VertexData.ComputeNormals(positions, indices, normals);
  38156. // Result
  38157. var vertexData = new VertexData();
  38158. vertexData.indices = indices;
  38159. vertexData.positions = positions;
  38160. vertexData.normals = normals;
  38161. vertexData.uvs = uvs;
  38162. return vertexData;
  38163. };
  38164. /**
  38165. * Creates the VertexData for a Plane
  38166. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38167. * * size sets the width and height of the plane to the value of size, optional default 1
  38168. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38169. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38170. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38171. * * 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)
  38172. * * 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)
  38173. * @returns the VertexData of the box
  38174. */
  38175. VertexData.CreatePlane = function (options) {
  38176. var indices = [];
  38177. var positions = [];
  38178. var normals = [];
  38179. var uvs = [];
  38180. var width = options.width || options.size || 1;
  38181. var height = options.height || options.size || 1;
  38182. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38183. // Vertices
  38184. var halfWidth = width / 2.0;
  38185. var halfHeight = height / 2.0;
  38186. positions.push(-halfWidth, -halfHeight, 0);
  38187. normals.push(0, 0, -1.0);
  38188. uvs.push(0.0, 0.0);
  38189. positions.push(halfWidth, -halfHeight, 0);
  38190. normals.push(0, 0, -1.0);
  38191. uvs.push(1.0, 0.0);
  38192. positions.push(halfWidth, halfHeight, 0);
  38193. normals.push(0, 0, -1.0);
  38194. uvs.push(1.0, 1.0);
  38195. positions.push(-halfWidth, halfHeight, 0);
  38196. normals.push(0, 0, -1.0);
  38197. uvs.push(0.0, 1.0);
  38198. // Indices
  38199. indices.push(0);
  38200. indices.push(1);
  38201. indices.push(2);
  38202. indices.push(0);
  38203. indices.push(2);
  38204. indices.push(3);
  38205. // Sides
  38206. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38207. // Result
  38208. var vertexData = new VertexData();
  38209. vertexData.indices = indices;
  38210. vertexData.positions = positions;
  38211. vertexData.normals = normals;
  38212. vertexData.uvs = uvs;
  38213. return vertexData;
  38214. };
  38215. /**
  38216. * Creates the VertexData of the Disc or regular Polygon
  38217. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38218. * * radius the radius of the disc, optional default 0.5
  38219. * * tessellation the number of polygon sides, optional, default 64
  38220. * * 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
  38221. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38222. * * 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)
  38223. * * 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)
  38224. * @returns the VertexData of the box
  38225. */
  38226. VertexData.CreateDisc = function (options) {
  38227. var positions = new Array();
  38228. var indices = new Array();
  38229. var normals = new Array();
  38230. var uvs = new Array();
  38231. var radius = options.radius || 0.5;
  38232. var tessellation = options.tessellation || 64;
  38233. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38234. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38235. // positions and uvs
  38236. positions.push(0, 0, 0); // disc center first
  38237. uvs.push(0.5, 0.5);
  38238. var theta = Math.PI * 2 * arc;
  38239. var step = theta / tessellation;
  38240. for (var a = 0; a < theta; a += step) {
  38241. var x = Math.cos(a);
  38242. var y = Math.sin(a);
  38243. var u = (x + 1) / 2;
  38244. var v = (1 - y) / 2;
  38245. positions.push(radius * x, radius * y, 0);
  38246. uvs.push(u, v);
  38247. }
  38248. if (arc === 1) {
  38249. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38250. uvs.push(uvs[2], uvs[3]);
  38251. }
  38252. //indices
  38253. var vertexNb = positions.length / 3;
  38254. for (var i = 1; i < vertexNb - 1; i++) {
  38255. indices.push(i + 1, 0, i);
  38256. }
  38257. // result
  38258. VertexData.ComputeNormals(positions, indices, normals);
  38259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38260. var vertexData = new VertexData();
  38261. vertexData.indices = indices;
  38262. vertexData.positions = positions;
  38263. vertexData.normals = normals;
  38264. vertexData.uvs = uvs;
  38265. return vertexData;
  38266. };
  38267. /**
  38268. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38269. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38270. * @param polygon a mesh built from polygonTriangulation.build()
  38271. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38272. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38273. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38274. * @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)
  38275. * @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)
  38276. * @returns the VertexData of the Polygon
  38277. */
  38278. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38279. var faceUV = fUV || new Array(3);
  38280. var faceColors = fColors;
  38281. var colors = [];
  38282. // default face colors and UV if undefined
  38283. for (var f = 0; f < 3; f++) {
  38284. if (faceUV[f] === undefined) {
  38285. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38286. }
  38287. if (faceColors && faceColors[f] === undefined) {
  38288. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38289. }
  38290. }
  38291. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38292. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38293. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38294. var indices = polygon.getIndices();
  38295. // set face colours and textures
  38296. var idx = 0;
  38297. var face = 0;
  38298. for (var index = 0; index < normals.length; index += 3) {
  38299. //Edge Face no. 1
  38300. if (Math.abs(normals[index + 1]) < 0.001) {
  38301. face = 1;
  38302. }
  38303. //Top Face no. 0
  38304. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38305. face = 0;
  38306. }
  38307. //Bottom Face no. 2
  38308. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38309. face = 2;
  38310. }
  38311. idx = index / 3;
  38312. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38313. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38314. if (faceColors) {
  38315. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38316. }
  38317. }
  38318. // sides
  38319. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38320. // Result
  38321. var vertexData = new VertexData();
  38322. vertexData.indices = indices;
  38323. vertexData.positions = positions;
  38324. vertexData.normals = normals;
  38325. vertexData.uvs = uvs;
  38326. if (faceColors) {
  38327. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38328. vertexData.colors = totalColors;
  38329. }
  38330. return vertexData;
  38331. };
  38332. /**
  38333. * Creates the VertexData of the IcoSphere
  38334. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38335. * * radius the radius of the IcoSphere, optional default 1
  38336. * * radiusX allows stretching in the x direction, optional, default radius
  38337. * * radiusY allows stretching in the y direction, optional, default radius
  38338. * * radiusZ allows stretching in the z direction, optional, default radius
  38339. * * flat when true creates a flat shaded mesh, optional, default true
  38340. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38341. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38342. * * 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)
  38343. * * 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)
  38344. * @returns the VertexData of the IcoSphere
  38345. */
  38346. VertexData.CreateIcoSphere = function (options) {
  38347. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38348. var radius = options.radius || 1;
  38349. var flat = (options.flat === undefined) ? true : options.flat;
  38350. var subdivisions = options.subdivisions || 4;
  38351. var radiusX = options.radiusX || radius;
  38352. var radiusY = options.radiusY || radius;
  38353. var radiusZ = options.radiusZ || radius;
  38354. var t = (1 + Math.sqrt(5)) / 2;
  38355. // 12 vertex x,y,z
  38356. var ico_vertices = [
  38357. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38358. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38359. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38360. ];
  38361. // index of 3 vertex makes a face of icopshere
  38362. var ico_indices = [
  38363. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38364. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38365. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38366. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38367. ];
  38368. // vertex for uv have aliased position, not for UV
  38369. var vertices_unalias_id = [
  38370. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38371. // vertex alias
  38372. 0,
  38373. 2,
  38374. 3,
  38375. 3,
  38376. 3,
  38377. 4,
  38378. 7,
  38379. 8,
  38380. 9,
  38381. 9,
  38382. 10,
  38383. 11 // 23: B + 12
  38384. ];
  38385. // uv as integer step (not pixels !)
  38386. var ico_vertexuv = [
  38387. 5, 1, 3, 1, 6, 4, 0, 0,
  38388. 5, 3, 4, 2, 2, 2, 4, 0,
  38389. 2, 0, 1, 1, 6, 0, 6, 2,
  38390. // vertex alias (for same vertex on different faces)
  38391. 0, 4,
  38392. 3, 3,
  38393. 4, 4,
  38394. 3, 1,
  38395. 4, 2,
  38396. 4, 4,
  38397. 0, 2,
  38398. 1, 1,
  38399. 2, 2,
  38400. 3, 3,
  38401. 1, 3,
  38402. 2, 4 // 23: B + 12
  38403. ];
  38404. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38405. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38406. // First island of uv mapping
  38407. // v = 4h 3+ 2
  38408. // v = 3h 9+ 4
  38409. // v = 2h 9+ 5 B
  38410. // v = 1h 9 1 0
  38411. // v = 0h 3 8 7 A
  38412. // u = 0 1 2 3 4 5 6 *a
  38413. // Second island of uv mapping
  38414. // v = 4h 0+ B+ 4+
  38415. // v = 3h A+ 2+
  38416. // v = 2h 7+ 6 3+
  38417. // v = 1h 8+ 3+
  38418. // v = 0h
  38419. // u = 0 1 2 3 4 5 6 *a
  38420. // Face layout on texture UV mapping
  38421. // ============
  38422. // \ 4 /\ 16 / ======
  38423. // \ / \ / /\ 11 /
  38424. // \/ 7 \/ / \ /
  38425. // ======= / 10 \/
  38426. // /\ 17 /\ =======
  38427. // / \ / \ \ 15 /\
  38428. // / 8 \/ 12 \ \ / \
  38429. // ============ \/ 6 \
  38430. // \ 18 /\ ============
  38431. // \ / \ \ 5 /\ 0 /
  38432. // \/ 13 \ \ / \ /
  38433. // ======= \/ 1 \/
  38434. // =============
  38435. // /\ 19 /\ 2 /\
  38436. // / \ / \ / \
  38437. // / 14 \/ 9 \/ 3 \
  38438. // ===================
  38439. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38440. var ustep = 138 / 1024;
  38441. var vstep = 239 / 1024;
  38442. var uoffset = 60 / 1024;
  38443. var voffset = 26 / 1024;
  38444. // Second island should have margin, not to touch the first island
  38445. // avoid any borderline artefact in pixel rounding
  38446. var island_u_offset = -40 / 1024;
  38447. var island_v_offset = +20 / 1024;
  38448. // face is either island 0 or 1 :
  38449. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38450. var island = [
  38451. 0, 0, 0, 0, 1,
  38452. 0, 0, 1, 1, 0,
  38453. 0, 0, 1, 1, 0,
  38454. 0, 1, 1, 1, 0 // 15 - 19
  38455. ];
  38456. var indices = new Array();
  38457. var positions = new Array();
  38458. var normals = new Array();
  38459. var uvs = new Array();
  38460. var current_indice = 0;
  38461. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38462. var face_vertex_pos = new Array(3);
  38463. var face_vertex_uv = new Array(3);
  38464. var v012;
  38465. for (v012 = 0; v012 < 3; v012++) {
  38466. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38467. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38468. }
  38469. // create all with normals
  38470. for (var face = 0; face < 20; face++) {
  38471. // 3 vertex per face
  38472. for (v012 = 0; v012 < 3; v012++) {
  38473. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38474. var v_id = ico_indices[3 * face + v012];
  38475. // vertex have 3D position (x,y,z)
  38476. 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]);
  38477. // Normalize to get normal, then scale to radius
  38478. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38479. // uv Coordinates from vertex ID
  38480. 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);
  38481. }
  38482. // Subdivide the face (interpolate pos, norm, uv)
  38483. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38484. // - norm is linear interpolation of vertex corner normal
  38485. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38486. // - uv is linear interpolation
  38487. //
  38488. // Topology is as below for sub-divide by 2
  38489. // vertex shown as v0,v1,v2
  38490. // interp index is i1 to progress in range [v0,v1[
  38491. // interp index is i2 to progress in range [v0,v2[
  38492. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38493. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38494. //
  38495. //
  38496. // i2 v2
  38497. // ^ ^
  38498. // / / \
  38499. // / / \
  38500. // / / \
  38501. // / / (0,1) \
  38502. // / #---------\
  38503. // / / \ (0,0)'/ \
  38504. // / / \ / \
  38505. // / / \ / \
  38506. // / / (0,0) \ / (1,0) \
  38507. // / #---------#---------\
  38508. // v0 v1
  38509. //
  38510. // --------------------> i1
  38511. //
  38512. // interp of (i1,i2):
  38513. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38514. // along i1 : lerp(x0,x1, i1/(S-i2))
  38515. //
  38516. // centroid of triangle is needed to get help normal computation
  38517. // (c1,c2) are used for centroid location
  38518. var interp_vertex = function (i1, i2, c1, c2) {
  38519. // vertex is interpolated from
  38520. // - face_vertex_pos[0..2]
  38521. // - face_vertex_uv[0..2]
  38522. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38523. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38524. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38525. pos_interp.normalize();
  38526. var vertex_normal;
  38527. if (flat) {
  38528. // in flat mode, recalculate normal as face centroid normal
  38529. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38530. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38531. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38532. }
  38533. else {
  38534. // in smooth mode, recalculate normal from each single vertex position
  38535. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38536. }
  38537. // Vertex normal need correction due to X,Y,Z radius scaling
  38538. vertex_normal.x /= radiusX;
  38539. vertex_normal.y /= radiusY;
  38540. vertex_normal.z /= radiusZ;
  38541. vertex_normal.normalize();
  38542. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38543. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38544. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38545. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38546. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38547. uvs.push(uv_interp.x, uv_interp.y);
  38548. // push each vertex has member of a face
  38549. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38550. indices.push(current_indice);
  38551. current_indice++;
  38552. };
  38553. for (var i2 = 0; i2 < subdivisions; i2++) {
  38554. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38555. // face : (i1,i2) for /\ :
  38556. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38557. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38558. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38559. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38560. if (i1 + i2 + 1 < subdivisions) {
  38561. // face : (i1,i2)' for \/ :
  38562. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38563. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38564. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38565. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38566. }
  38567. }
  38568. }
  38569. }
  38570. // Sides
  38571. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38572. // Result
  38573. var vertexData = new VertexData();
  38574. vertexData.indices = indices;
  38575. vertexData.positions = positions;
  38576. vertexData.normals = normals;
  38577. vertexData.uvs = uvs;
  38578. return vertexData;
  38579. };
  38580. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38581. /**
  38582. * Creates the VertexData for a Polyhedron
  38583. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38584. * * type provided types are:
  38585. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38586. * * 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)
  38587. * * size the size of the IcoSphere, optional default 1
  38588. * * sizeX allows stretching in the x direction, optional, default size
  38589. * * sizeY allows stretching in the y direction, optional, default size
  38590. * * sizeZ allows stretching in the z direction, optional, default size
  38591. * * 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
  38592. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38593. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38594. * * flat when true creates a flat shaded mesh, optional, default true
  38595. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38596. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38597. * * 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)
  38598. * * 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)
  38599. * @returns the VertexData of the Polyhedron
  38600. */
  38601. VertexData.CreatePolyhedron = function (options) {
  38602. // provided polyhedron types :
  38603. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38604. // 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)
  38605. var polyhedra = [];
  38606. 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]] };
  38607. 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]] };
  38608. polyhedra[2] = {
  38609. 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]],
  38610. 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]]
  38611. };
  38612. polyhedra[3] = {
  38613. 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]],
  38614. 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]]
  38615. };
  38616. polyhedra[4] = {
  38617. 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]],
  38618. 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]]
  38619. };
  38620. 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]] };
  38621. 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]] };
  38622. 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]] };
  38623. 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]] };
  38624. 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]] };
  38625. 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]] };
  38626. 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]] };
  38627. 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]] };
  38628. 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]] };
  38629. polyhedra[14] = {
  38630. 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]],
  38631. 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]]
  38632. };
  38633. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38634. var size = options.size;
  38635. var sizeX = options.sizeX || size || 1;
  38636. var sizeY = options.sizeY || size || 1;
  38637. var sizeZ = options.sizeZ || size || 1;
  38638. var data = options.custom || polyhedra[type];
  38639. var nbfaces = data.face.length;
  38640. var faceUV = options.faceUV || new Array(nbfaces);
  38641. var faceColors = options.faceColors;
  38642. var flat = (options.flat === undefined) ? true : options.flat;
  38643. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38644. var positions = new Array();
  38645. var indices = new Array();
  38646. var normals = new Array();
  38647. var uvs = new Array();
  38648. var colors = new Array();
  38649. var index = 0;
  38650. var faceIdx = 0; // face cursor in the array "indexes"
  38651. var indexes = new Array();
  38652. var i = 0;
  38653. var f = 0;
  38654. var u, v, ang, x, y, tmp;
  38655. // default face colors and UV if undefined
  38656. if (flat) {
  38657. for (f = 0; f < nbfaces; f++) {
  38658. if (faceColors && faceColors[f] === undefined) {
  38659. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38660. }
  38661. if (faceUV && faceUV[f] === undefined) {
  38662. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38663. }
  38664. }
  38665. }
  38666. if (!flat) {
  38667. for (i = 0; i < data.vertex.length; i++) {
  38668. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38669. uvs.push(0, 0);
  38670. }
  38671. for (f = 0; f < nbfaces; f++) {
  38672. for (i = 0; i < data.face[f].length - 2; i++) {
  38673. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38674. }
  38675. }
  38676. }
  38677. else {
  38678. for (f = 0; f < nbfaces; f++) {
  38679. var fl = data.face[f].length; // number of vertices of the current face
  38680. ang = 2 * Math.PI / fl;
  38681. x = 0.5 * Math.tan(ang / 2);
  38682. y = 0.5;
  38683. // positions, uvs, colors
  38684. for (i = 0; i < fl; i++) {
  38685. // positions
  38686. 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);
  38687. indexes.push(index);
  38688. index++;
  38689. // uvs
  38690. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38691. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38692. uvs.push(u, v);
  38693. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38694. y = x * Math.sin(ang) + y * Math.cos(ang);
  38695. x = tmp;
  38696. // colors
  38697. if (faceColors) {
  38698. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38699. }
  38700. }
  38701. // indices from indexes
  38702. for (i = 0; i < fl - 2; i++) {
  38703. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38704. }
  38705. faceIdx += fl;
  38706. }
  38707. }
  38708. VertexData.ComputeNormals(positions, indices, normals);
  38709. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38710. var vertexData = new VertexData();
  38711. vertexData.positions = positions;
  38712. vertexData.indices = indices;
  38713. vertexData.normals = normals;
  38714. vertexData.uvs = uvs;
  38715. if (faceColors && flat) {
  38716. vertexData.colors = colors;
  38717. }
  38718. return vertexData;
  38719. };
  38720. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38721. /**
  38722. * Creates the VertexData for a TorusKnot
  38723. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38724. * * radius the radius of the torus knot, optional, default 2
  38725. * * tube the thickness of the tube, optional, default 0.5
  38726. * * radialSegments the number of sides on each tube segments, optional, default 32
  38727. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38728. * * p the number of windings around the z axis, optional, default 2
  38729. * * q the number of windings around the x axis, optional, default 3
  38730. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38731. * * 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)
  38732. * * 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)
  38733. * @returns the VertexData of the Torus Knot
  38734. */
  38735. VertexData.CreateTorusKnot = function (options) {
  38736. var indices = new Array();
  38737. var positions = new Array();
  38738. var normals = new Array();
  38739. var uvs = new Array();
  38740. var radius = options.radius || 2;
  38741. var tube = options.tube || 0.5;
  38742. var radialSegments = options.radialSegments || 32;
  38743. var tubularSegments = options.tubularSegments || 32;
  38744. var p = options.p || 2;
  38745. var q = options.q || 3;
  38746. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38747. // Helper
  38748. var getPos = function (angle) {
  38749. var cu = Math.cos(angle);
  38750. var su = Math.sin(angle);
  38751. var quOverP = q / p * angle;
  38752. var cs = Math.cos(quOverP);
  38753. var tx = radius * (2 + cs) * 0.5 * cu;
  38754. var ty = radius * (2 + cs) * su * 0.5;
  38755. var tz = radius * Math.sin(quOverP) * 0.5;
  38756. return new BABYLON.Vector3(tx, ty, tz);
  38757. };
  38758. // Vertices
  38759. var i;
  38760. var j;
  38761. for (i = 0; i <= radialSegments; i++) {
  38762. var modI = i % radialSegments;
  38763. var u = modI / radialSegments * 2 * p * Math.PI;
  38764. var p1 = getPos(u);
  38765. var p2 = getPos(u + 0.01);
  38766. var tang = p2.subtract(p1);
  38767. var n = p2.add(p1);
  38768. var bitan = BABYLON.Vector3.Cross(tang, n);
  38769. n = BABYLON.Vector3.Cross(bitan, tang);
  38770. bitan.normalize();
  38771. n.normalize();
  38772. for (j = 0; j < tubularSegments; j++) {
  38773. var modJ = j % tubularSegments;
  38774. var v = modJ / tubularSegments * 2 * Math.PI;
  38775. var cx = -tube * Math.cos(v);
  38776. var cy = tube * Math.sin(v);
  38777. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38778. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38779. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38780. uvs.push(i / radialSegments);
  38781. uvs.push(j / tubularSegments);
  38782. }
  38783. }
  38784. for (i = 0; i < radialSegments; i++) {
  38785. for (j = 0; j < tubularSegments; j++) {
  38786. var jNext = (j + 1) % tubularSegments;
  38787. var a = i * tubularSegments + j;
  38788. var b = (i + 1) * tubularSegments + j;
  38789. var c = (i + 1) * tubularSegments + jNext;
  38790. var d = i * tubularSegments + jNext;
  38791. indices.push(d);
  38792. indices.push(b);
  38793. indices.push(a);
  38794. indices.push(d);
  38795. indices.push(c);
  38796. indices.push(b);
  38797. }
  38798. }
  38799. // Normals
  38800. VertexData.ComputeNormals(positions, indices, normals);
  38801. // Sides
  38802. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38803. // Result
  38804. var vertexData = new VertexData();
  38805. vertexData.indices = indices;
  38806. vertexData.positions = positions;
  38807. vertexData.normals = normals;
  38808. vertexData.uvs = uvs;
  38809. return vertexData;
  38810. };
  38811. // Tools
  38812. /**
  38813. * Compute normals for given positions and indices
  38814. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38815. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38816. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38817. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38818. * * facetNormals : optional array of facet normals (vector3)
  38819. * * facetPositions : optional array of facet positions (vector3)
  38820. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38821. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38822. * * bInfo : optional bounding info, required for facetPartitioning computation
  38823. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38824. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38825. * * useRightHandedSystem: optional boolean to for right handed system computation
  38826. * * depthSort : optional boolean to enable the facet depth sort computation
  38827. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38828. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38829. */
  38830. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38831. // temporary scalar variables
  38832. var index = 0; // facet index
  38833. var p1p2x = 0.0; // p1p2 vector x coordinate
  38834. var p1p2y = 0.0; // p1p2 vector y coordinate
  38835. var p1p2z = 0.0; // p1p2 vector z coordinate
  38836. var p3p2x = 0.0; // p3p2 vector x coordinate
  38837. var p3p2y = 0.0; // p3p2 vector y coordinate
  38838. var p3p2z = 0.0; // p3p2 vector z coordinate
  38839. var faceNormalx = 0.0; // facet normal x coordinate
  38840. var faceNormaly = 0.0; // facet normal y coordinate
  38841. var faceNormalz = 0.0; // facet normal z coordinate
  38842. var length = 0.0; // facet normal length before normalization
  38843. var v1x = 0; // vector1 x index in the positions array
  38844. var v1y = 0; // vector1 y index in the positions array
  38845. var v1z = 0; // vector1 z index in the positions array
  38846. var v2x = 0; // vector2 x index in the positions array
  38847. var v2y = 0; // vector2 y index in the positions array
  38848. var v2z = 0; // vector2 z index in the positions array
  38849. var v3x = 0; // vector3 x index in the positions array
  38850. var v3y = 0; // vector3 y index in the positions array
  38851. var v3z = 0; // vector3 z index in the positions array
  38852. var computeFacetNormals = false;
  38853. var computeFacetPositions = false;
  38854. var computeFacetPartitioning = false;
  38855. var computeDepthSort = false;
  38856. var faceNormalSign = 1;
  38857. var ratio = 0;
  38858. var distanceTo = null;
  38859. if (options) {
  38860. computeFacetNormals = (options.facetNormals) ? true : false;
  38861. computeFacetPositions = (options.facetPositions) ? true : false;
  38862. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38863. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38864. ratio = options.ratio || 0;
  38865. computeDepthSort = (options.depthSort) ? true : false;
  38866. distanceTo = (options.distanceTo);
  38867. if (computeDepthSort) {
  38868. if (distanceTo === undefined) {
  38869. distanceTo = BABYLON.Vector3.Zero();
  38870. }
  38871. var depthSortedFacets = options.depthSortedFacets;
  38872. }
  38873. }
  38874. // facetPartitioning reinit if needed
  38875. var xSubRatio = 0;
  38876. var ySubRatio = 0;
  38877. var zSubRatio = 0;
  38878. var subSq = 0;
  38879. if (computeFacetPartitioning && options && options.bbSize) {
  38880. var ox = 0; // X partitioning index for facet position
  38881. var oy = 0; // Y partinioning index for facet position
  38882. var oz = 0; // Z partinioning index for facet position
  38883. var b1x = 0; // X partitioning index for facet v1 vertex
  38884. var b1y = 0; // Y partitioning index for facet v1 vertex
  38885. var b1z = 0; // z partitioning index for facet v1 vertex
  38886. var b2x = 0; // X partitioning index for facet v2 vertex
  38887. var b2y = 0; // Y partitioning index for facet v2 vertex
  38888. var b2z = 0; // Z partitioning index for facet v2 vertex
  38889. var b3x = 0; // X partitioning index for facet v3 vertex
  38890. var b3y = 0; // Y partitioning index for facet v3 vertex
  38891. var b3z = 0; // Z partitioning index for facet v3 vertex
  38892. var block_idx_o = 0; // facet barycenter block index
  38893. var block_idx_v1 = 0; // v1 vertex block index
  38894. var block_idx_v2 = 0; // v2 vertex block index
  38895. var block_idx_v3 = 0; // v3 vertex block index
  38896. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38897. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38898. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38899. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38900. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38901. subSq = options.subDiv.max * options.subDiv.max;
  38902. options.facetPartitioning.length = 0;
  38903. }
  38904. // reset the normals
  38905. for (index = 0; index < positions.length; index++) {
  38906. normals[index] = 0.0;
  38907. }
  38908. // Loop : 1 indice triplet = 1 facet
  38909. var nbFaces = (indices.length / 3) | 0;
  38910. for (index = 0; index < nbFaces; index++) {
  38911. // get the indexes of the coordinates of each vertex of the facet
  38912. v1x = indices[index * 3] * 3;
  38913. v1y = v1x + 1;
  38914. v1z = v1x + 2;
  38915. v2x = indices[index * 3 + 1] * 3;
  38916. v2y = v2x + 1;
  38917. v2z = v2x + 2;
  38918. v3x = indices[index * 3 + 2] * 3;
  38919. v3y = v3x + 1;
  38920. v3z = v3x + 2;
  38921. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38922. p1p2y = positions[v1y] - positions[v2y];
  38923. p1p2z = positions[v1z] - positions[v2z];
  38924. p3p2x = positions[v3x] - positions[v2x];
  38925. p3p2y = positions[v3y] - positions[v2y];
  38926. p3p2z = positions[v3z] - positions[v2z];
  38927. // compute the face normal with the cross product
  38928. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38929. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38930. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38931. // normalize this normal and store it in the array facetData
  38932. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38933. length = (length === 0) ? 1.0 : length;
  38934. faceNormalx /= length;
  38935. faceNormaly /= length;
  38936. faceNormalz /= length;
  38937. if (computeFacetNormals && options) {
  38938. options.facetNormals[index].x = faceNormalx;
  38939. options.facetNormals[index].y = faceNormaly;
  38940. options.facetNormals[index].z = faceNormalz;
  38941. }
  38942. if (computeFacetPositions && options) {
  38943. // compute and the facet barycenter coordinates in the array facetPositions
  38944. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38945. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38946. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38947. }
  38948. if (computeFacetPartitioning && options) {
  38949. // store the facet indexes in arrays in the main facetPartitioning array :
  38950. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38951. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38952. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38953. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38954. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38955. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38956. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38957. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38958. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38959. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38960. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38961. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38962. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38963. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38964. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38965. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38966. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38967. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38968. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38969. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38970. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38971. // push each facet index in each block containing the vertex
  38972. options.facetPartitioning[block_idx_v1].push(index);
  38973. if (block_idx_v2 != block_idx_v1) {
  38974. options.facetPartitioning[block_idx_v2].push(index);
  38975. }
  38976. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38977. options.facetPartitioning[block_idx_v3].push(index);
  38978. }
  38979. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38980. options.facetPartitioning[block_idx_o].push(index);
  38981. }
  38982. }
  38983. if (computeDepthSort && options && options.facetPositions) {
  38984. var dsf = depthSortedFacets[index];
  38985. dsf.ind = index * 3;
  38986. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38987. }
  38988. // compute the normals anyway
  38989. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38990. normals[v1y] += faceNormaly;
  38991. normals[v1z] += faceNormalz;
  38992. normals[v2x] += faceNormalx;
  38993. normals[v2y] += faceNormaly;
  38994. normals[v2z] += faceNormalz;
  38995. normals[v3x] += faceNormalx;
  38996. normals[v3y] += faceNormaly;
  38997. normals[v3z] += faceNormalz;
  38998. }
  38999. // last normalization of each normal
  39000. for (index = 0; index < normals.length / 3; index++) {
  39001. faceNormalx = normals[index * 3];
  39002. faceNormaly = normals[index * 3 + 1];
  39003. faceNormalz = normals[index * 3 + 2];
  39004. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39005. length = (length === 0) ? 1.0 : length;
  39006. faceNormalx /= length;
  39007. faceNormaly /= length;
  39008. faceNormalz /= length;
  39009. normals[index * 3] = faceNormalx;
  39010. normals[index * 3 + 1] = faceNormaly;
  39011. normals[index * 3 + 2] = faceNormalz;
  39012. }
  39013. };
  39014. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39015. var li = indices.length;
  39016. var ln = normals.length;
  39017. var i;
  39018. var n;
  39019. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39020. switch (sideOrientation) {
  39021. case BABYLON.Mesh.FRONTSIDE:
  39022. // nothing changed
  39023. break;
  39024. case BABYLON.Mesh.BACKSIDE:
  39025. var tmp;
  39026. // indices
  39027. for (i = 0; i < li; i += 3) {
  39028. tmp = indices[i];
  39029. indices[i] = indices[i + 2];
  39030. indices[i + 2] = tmp;
  39031. }
  39032. // normals
  39033. for (n = 0; n < ln; n++) {
  39034. normals[n] = -normals[n];
  39035. }
  39036. break;
  39037. case BABYLON.Mesh.DOUBLESIDE:
  39038. // positions
  39039. var lp = positions.length;
  39040. var l = lp / 3;
  39041. for (var p = 0; p < lp; p++) {
  39042. positions[lp + p] = positions[p];
  39043. }
  39044. // indices
  39045. for (i = 0; i < li; i += 3) {
  39046. indices[i + li] = indices[i + 2] + l;
  39047. indices[i + 1 + li] = indices[i + 1] + l;
  39048. indices[i + 2 + li] = indices[i] + l;
  39049. }
  39050. // normals
  39051. for (n = 0; n < ln; n++) {
  39052. normals[ln + n] = -normals[n];
  39053. }
  39054. // uvs
  39055. var lu = uvs.length;
  39056. var u = 0;
  39057. for (u = 0; u < lu; u++) {
  39058. uvs[u + lu] = uvs[u];
  39059. }
  39060. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39061. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39062. u = 0;
  39063. for (i = 0; i < lu / 2; i++) {
  39064. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39065. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39066. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39067. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39068. u += 2;
  39069. }
  39070. break;
  39071. }
  39072. };
  39073. /**
  39074. * Applies VertexData created from the imported parameters to the geometry
  39075. * @param parsedVertexData the parsed data from an imported file
  39076. * @param geometry the geometry to apply the VertexData to
  39077. */
  39078. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39079. var vertexData = new VertexData();
  39080. // positions
  39081. var positions = parsedVertexData.positions;
  39082. if (positions) {
  39083. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39084. }
  39085. // normals
  39086. var normals = parsedVertexData.normals;
  39087. if (normals) {
  39088. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39089. }
  39090. // tangents
  39091. var tangents = parsedVertexData.tangents;
  39092. if (tangents) {
  39093. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39094. }
  39095. // uvs
  39096. var uvs = parsedVertexData.uvs;
  39097. if (uvs) {
  39098. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39099. }
  39100. // uv2s
  39101. var uv2s = parsedVertexData.uv2s;
  39102. if (uv2s) {
  39103. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39104. }
  39105. // uv3s
  39106. var uv3s = parsedVertexData.uv3s;
  39107. if (uv3s) {
  39108. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39109. }
  39110. // uv4s
  39111. var uv4s = parsedVertexData.uv4s;
  39112. if (uv4s) {
  39113. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39114. }
  39115. // uv5s
  39116. var uv5s = parsedVertexData.uv5s;
  39117. if (uv5s) {
  39118. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39119. }
  39120. // uv6s
  39121. var uv6s = parsedVertexData.uv6s;
  39122. if (uv6s) {
  39123. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39124. }
  39125. // colors
  39126. var colors = parsedVertexData.colors;
  39127. if (colors) {
  39128. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39129. }
  39130. // matricesIndices
  39131. var matricesIndices = parsedVertexData.matricesIndices;
  39132. if (matricesIndices) {
  39133. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39134. }
  39135. // matricesWeights
  39136. var matricesWeights = parsedVertexData.matricesWeights;
  39137. if (matricesWeights) {
  39138. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39139. }
  39140. // indices
  39141. var indices = parsedVertexData.indices;
  39142. if (indices) {
  39143. vertexData.indices = indices;
  39144. }
  39145. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39146. };
  39147. return VertexData;
  39148. }());
  39149. BABYLON.VertexData = VertexData;
  39150. })(BABYLON || (BABYLON = {}));
  39151. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39152. var BABYLON;
  39153. (function (BABYLON) {
  39154. /**
  39155. * Class used to store geometry data (vertex buffers + index buffer)
  39156. */
  39157. var Geometry = /** @class */ (function () {
  39158. /**
  39159. * Creates a new geometry
  39160. * @param id defines the unique ID
  39161. * @param scene defines the hosting scene
  39162. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39163. * @param updatable defines if geometry must be updatable (false by default)
  39164. * @param mesh defines the mesh that will be associated with the geometry
  39165. */
  39166. function Geometry(id, scene, vertexData, updatable, mesh) {
  39167. if (updatable === void 0) { updatable = false; }
  39168. if (mesh === void 0) { mesh = null; }
  39169. /**
  39170. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39171. */
  39172. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39173. this._totalVertices = 0;
  39174. this._isDisposed = false;
  39175. this._indexBufferIsUpdatable = false;
  39176. this.id = id;
  39177. this._engine = scene.getEngine();
  39178. this._meshes = [];
  39179. this._scene = scene;
  39180. //Init vertex buffer cache
  39181. this._vertexBuffers = {};
  39182. this._indices = [];
  39183. this._updatable = updatable;
  39184. // vertexData
  39185. if (vertexData) {
  39186. this.setAllVerticesData(vertexData, updatable);
  39187. }
  39188. else {
  39189. this._totalVertices = 0;
  39190. this._indices = [];
  39191. }
  39192. if (this._engine.getCaps().vertexArrayObject) {
  39193. this._vertexArrayObjects = {};
  39194. }
  39195. // applyToMesh
  39196. if (mesh) {
  39197. if (mesh.getClassName() === "LinesMesh") {
  39198. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39199. this._updateExtend();
  39200. }
  39201. this.applyToMesh(mesh);
  39202. mesh.computeWorldMatrix(true);
  39203. }
  39204. }
  39205. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39206. /**
  39207. * 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
  39208. */
  39209. get: function () {
  39210. return this._boundingBias;
  39211. },
  39212. /**
  39213. * 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
  39214. */
  39215. set: function (value) {
  39216. if (this._boundingBias && this._boundingBias.equals(value)) {
  39217. return;
  39218. }
  39219. this._boundingBias = value.clone();
  39220. this._updateBoundingInfo(true, null);
  39221. },
  39222. enumerable: true,
  39223. configurable: true
  39224. });
  39225. /**
  39226. * Static function used to attach a new empty geometry to a mesh
  39227. * @param mesh defines the mesh to attach the geometry to
  39228. * @returns the new {BABYLON.Geometry}
  39229. */
  39230. Geometry.CreateGeometryForMesh = function (mesh) {
  39231. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39232. geometry.applyToMesh(mesh);
  39233. return geometry;
  39234. };
  39235. Object.defineProperty(Geometry.prototype, "extend", {
  39236. /**
  39237. * Gets the current extend of the geometry
  39238. */
  39239. get: function () {
  39240. return this._extend;
  39241. },
  39242. enumerable: true,
  39243. configurable: true
  39244. });
  39245. /**
  39246. * Gets the hosting scene
  39247. * @returns the hosting {BABYLON.Scene}
  39248. */
  39249. Geometry.prototype.getScene = function () {
  39250. return this._scene;
  39251. };
  39252. /**
  39253. * Gets the hosting engine
  39254. * @returns the hosting {BABYLON.Engine}
  39255. */
  39256. Geometry.prototype.getEngine = function () {
  39257. return this._engine;
  39258. };
  39259. /**
  39260. * Defines if the geometry is ready to use
  39261. * @returns true if the geometry is ready to be used
  39262. */
  39263. Geometry.prototype.isReady = function () {
  39264. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39265. };
  39266. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39267. /**
  39268. * Gets a value indicating that the geometry should not be serialized
  39269. */
  39270. get: function () {
  39271. for (var index = 0; index < this._meshes.length; index++) {
  39272. if (!this._meshes[index].doNotSerialize) {
  39273. return false;
  39274. }
  39275. }
  39276. return true;
  39277. },
  39278. enumerable: true,
  39279. configurable: true
  39280. });
  39281. /** @hidden */
  39282. Geometry.prototype._rebuild = function () {
  39283. if (this._vertexArrayObjects) {
  39284. this._vertexArrayObjects = {};
  39285. }
  39286. // Index buffer
  39287. if (this._meshes.length !== 0 && this._indices) {
  39288. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39289. }
  39290. // Vertex buffers
  39291. for (var key in this._vertexBuffers) {
  39292. var vertexBuffer = this._vertexBuffers[key];
  39293. vertexBuffer._rebuild();
  39294. }
  39295. };
  39296. /**
  39297. * Affects all geometry data in one call
  39298. * @param vertexData defines the geometry data
  39299. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39300. */
  39301. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39302. vertexData.applyToGeometry(this, updatable);
  39303. this.notifyUpdate();
  39304. };
  39305. /**
  39306. * Set specific vertex data
  39307. * @param kind defines the data kind (Position, normal, etc...)
  39308. * @param data defines the vertex data to use
  39309. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39310. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39311. */
  39312. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39313. if (updatable === void 0) { updatable = false; }
  39314. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39315. this.setVerticesBuffer(buffer);
  39316. };
  39317. /**
  39318. * Removes a specific vertex data
  39319. * @param kind defines the data kind (Position, normal, etc...)
  39320. */
  39321. Geometry.prototype.removeVerticesData = function (kind) {
  39322. if (this._vertexBuffers[kind]) {
  39323. this._vertexBuffers[kind].dispose();
  39324. delete this._vertexBuffers[kind];
  39325. }
  39326. };
  39327. /**
  39328. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39329. * @param buffer defines the vertex buffer to use
  39330. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39331. */
  39332. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39333. if (totalVertices === void 0) { totalVertices = null; }
  39334. var kind = buffer.getKind();
  39335. if (this._vertexBuffers[kind]) {
  39336. this._vertexBuffers[kind].dispose();
  39337. }
  39338. this._vertexBuffers[kind] = buffer;
  39339. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39340. var data = buffer.getData();
  39341. if (totalVertices != null) {
  39342. this._totalVertices = totalVertices;
  39343. }
  39344. else {
  39345. if (data != null) {
  39346. this._totalVertices = data.length / (buffer.byteStride / 4);
  39347. }
  39348. }
  39349. this._updateExtend(data);
  39350. this._resetPointsArrayCache();
  39351. var meshes = this._meshes;
  39352. var numOfMeshes = meshes.length;
  39353. for (var index = 0; index < numOfMeshes; index++) {
  39354. var mesh = meshes[index];
  39355. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39356. mesh._createGlobalSubMesh(false);
  39357. mesh.computeWorldMatrix(true);
  39358. }
  39359. }
  39360. this.notifyUpdate(kind);
  39361. if (this._vertexArrayObjects) {
  39362. this._disposeVertexArrayObjects();
  39363. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39364. }
  39365. };
  39366. /**
  39367. * Update a specific vertex buffer
  39368. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39369. * It will do nothing if the buffer is not updatable
  39370. * @param kind defines the data kind (Position, normal, etc...)
  39371. * @param data defines the data to use
  39372. * @param offset defines the offset in the target buffer where to store the data
  39373. * @param useBytes set to true if the offset is in bytes
  39374. */
  39375. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39376. if (useBytes === void 0) { useBytes = false; }
  39377. var vertexBuffer = this.getVertexBuffer(kind);
  39378. if (!vertexBuffer) {
  39379. return;
  39380. }
  39381. vertexBuffer.updateDirectly(data, offset, useBytes);
  39382. this.notifyUpdate(kind);
  39383. };
  39384. /**
  39385. * Update a specific vertex buffer
  39386. * This function will create a new buffer if the current one is not updatable
  39387. * @param kind defines the data kind (Position, normal, etc...)
  39388. * @param data defines the data to use
  39389. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39390. */
  39391. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39392. if (updateExtends === void 0) { updateExtends = false; }
  39393. var vertexBuffer = this.getVertexBuffer(kind);
  39394. if (!vertexBuffer) {
  39395. return;
  39396. }
  39397. vertexBuffer.update(data);
  39398. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39399. this._updateBoundingInfo(updateExtends, data);
  39400. }
  39401. this.notifyUpdate(kind);
  39402. };
  39403. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39404. if (updateExtends) {
  39405. this._updateExtend(data);
  39406. }
  39407. var meshes = this._meshes;
  39408. var numOfMeshes = meshes.length;
  39409. this._resetPointsArrayCache();
  39410. for (var index = 0; index < numOfMeshes; index++) {
  39411. var mesh = meshes[index];
  39412. if (updateExtends) {
  39413. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39414. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39415. var subMesh = mesh.subMeshes[subIndex];
  39416. subMesh.refreshBoundingInfo();
  39417. }
  39418. }
  39419. }
  39420. };
  39421. /** @hidden */
  39422. Geometry.prototype._bind = function (effect, indexToBind) {
  39423. if (!effect) {
  39424. return;
  39425. }
  39426. if (indexToBind === undefined) {
  39427. indexToBind = this._indexBuffer;
  39428. }
  39429. var vbs = this.getVertexBuffers();
  39430. if (!vbs) {
  39431. return;
  39432. }
  39433. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39434. this._engine.bindBuffers(vbs, indexToBind, effect);
  39435. return;
  39436. }
  39437. // Using VAO
  39438. if (!this._vertexArrayObjects[effect.key]) {
  39439. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39440. }
  39441. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39442. };
  39443. /**
  39444. * Gets total number of vertices
  39445. * @returns the total number of vertices
  39446. */
  39447. Geometry.prototype.getTotalVertices = function () {
  39448. if (!this.isReady()) {
  39449. return 0;
  39450. }
  39451. return this._totalVertices;
  39452. };
  39453. /**
  39454. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39455. * @param kind defines the data kind (Position, normal, etc...)
  39456. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39457. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39458. * @returns a float array containing vertex data
  39459. */
  39460. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39461. var vertexBuffer = this.getVertexBuffer(kind);
  39462. if (!vertexBuffer) {
  39463. return null;
  39464. }
  39465. var data = vertexBuffer.getData();
  39466. if (!data) {
  39467. return null;
  39468. }
  39469. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39470. var count = this._totalVertices * vertexBuffer.getSize();
  39471. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39472. var copy_1 = new Array(count);
  39473. vertexBuffer.forEach(count, function (value, index) {
  39474. copy_1[index] = value;
  39475. });
  39476. return copy_1;
  39477. }
  39478. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39479. if (data instanceof Array) {
  39480. var offset = vertexBuffer.byteOffset / 4;
  39481. return BABYLON.Tools.Slice(data, offset, offset + count);
  39482. }
  39483. else if (data instanceof ArrayBuffer) {
  39484. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39485. }
  39486. else {
  39487. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39488. }
  39489. }
  39490. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39491. return BABYLON.Tools.Slice(data);
  39492. }
  39493. return data;
  39494. };
  39495. /**
  39496. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39497. * @param kind defines the data kind (Position, normal, etc...)
  39498. * @returns true if the vertex buffer with the specified kind is updatable
  39499. */
  39500. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39501. var vb = this._vertexBuffers[kind];
  39502. if (!vb) {
  39503. return false;
  39504. }
  39505. return vb.isUpdatable();
  39506. };
  39507. /**
  39508. * Gets a specific vertex buffer
  39509. * @param kind defines the data kind (Position, normal, etc...)
  39510. * @returns a {BABYLON.VertexBuffer}
  39511. */
  39512. Geometry.prototype.getVertexBuffer = function (kind) {
  39513. if (!this.isReady()) {
  39514. return null;
  39515. }
  39516. return this._vertexBuffers[kind];
  39517. };
  39518. /**
  39519. * Returns all vertex buffers
  39520. * @return an object holding all vertex buffers indexed by kind
  39521. */
  39522. Geometry.prototype.getVertexBuffers = function () {
  39523. if (!this.isReady()) {
  39524. return null;
  39525. }
  39526. return this._vertexBuffers;
  39527. };
  39528. /**
  39529. * Gets a boolean indicating if specific vertex buffer is present
  39530. * @param kind defines the data kind (Position, normal, etc...)
  39531. * @returns true if data is present
  39532. */
  39533. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39534. if (!this._vertexBuffers) {
  39535. if (this._delayInfo) {
  39536. return this._delayInfo.indexOf(kind) !== -1;
  39537. }
  39538. return false;
  39539. }
  39540. return this._vertexBuffers[kind] !== undefined;
  39541. };
  39542. /**
  39543. * Gets a list of all attached data kinds (Position, normal, etc...)
  39544. * @returns a list of string containing all kinds
  39545. */
  39546. Geometry.prototype.getVerticesDataKinds = function () {
  39547. var result = [];
  39548. var kind;
  39549. if (!this._vertexBuffers && this._delayInfo) {
  39550. for (kind in this._delayInfo) {
  39551. result.push(kind);
  39552. }
  39553. }
  39554. else {
  39555. for (kind in this._vertexBuffers) {
  39556. result.push(kind);
  39557. }
  39558. }
  39559. return result;
  39560. };
  39561. /**
  39562. * Update index buffer
  39563. * @param indices defines the indices to store in the index buffer
  39564. * @param offset defines the offset in the target buffer where to store the data
  39565. */
  39566. Geometry.prototype.updateIndices = function (indices, offset) {
  39567. if (!this._indexBuffer) {
  39568. return;
  39569. }
  39570. if (!this._indexBufferIsUpdatable) {
  39571. this.setIndices(indices, null, true);
  39572. }
  39573. else {
  39574. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39575. }
  39576. };
  39577. /**
  39578. * Creates a new index buffer
  39579. * @param indices defines the indices to store in the index buffer
  39580. * @param totalVertices defines the total number of vertices (could be null)
  39581. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39582. */
  39583. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39584. if (totalVertices === void 0) { totalVertices = null; }
  39585. if (updatable === void 0) { updatable = false; }
  39586. if (this._indexBuffer) {
  39587. this._engine._releaseBuffer(this._indexBuffer);
  39588. }
  39589. this._disposeVertexArrayObjects();
  39590. this._indices = indices;
  39591. this._indexBufferIsUpdatable = updatable;
  39592. if (this._meshes.length !== 0 && this._indices) {
  39593. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39594. }
  39595. if (totalVertices != undefined) { // including null and undefined
  39596. this._totalVertices = totalVertices;
  39597. }
  39598. var meshes = this._meshes;
  39599. var numOfMeshes = meshes.length;
  39600. for (var index = 0; index < numOfMeshes; index++) {
  39601. meshes[index]._createGlobalSubMesh(true);
  39602. }
  39603. this.notifyUpdate();
  39604. };
  39605. /**
  39606. * Return the total number of indices
  39607. * @returns the total number of indices
  39608. */
  39609. Geometry.prototype.getTotalIndices = function () {
  39610. if (!this.isReady()) {
  39611. return 0;
  39612. }
  39613. return this._indices.length;
  39614. };
  39615. /**
  39616. * Gets the index buffer array
  39617. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39618. * @returns the index buffer array
  39619. */
  39620. Geometry.prototype.getIndices = function (copyWhenShared) {
  39621. if (!this.isReady()) {
  39622. return null;
  39623. }
  39624. var orig = this._indices;
  39625. if (!copyWhenShared || this._meshes.length === 1) {
  39626. return orig;
  39627. }
  39628. else {
  39629. var len = orig.length;
  39630. var copy = [];
  39631. for (var i = 0; i < len; i++) {
  39632. copy.push(orig[i]);
  39633. }
  39634. return copy;
  39635. }
  39636. };
  39637. /**
  39638. * Gets the index buffer
  39639. * @return the index buffer
  39640. */
  39641. Geometry.prototype.getIndexBuffer = function () {
  39642. if (!this.isReady()) {
  39643. return null;
  39644. }
  39645. return this._indexBuffer;
  39646. };
  39647. /** @hidden */
  39648. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39649. if (effect === void 0) { effect = null; }
  39650. if (!effect || !this._vertexArrayObjects) {
  39651. return;
  39652. }
  39653. if (this._vertexArrayObjects[effect.key]) {
  39654. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39655. delete this._vertexArrayObjects[effect.key];
  39656. }
  39657. };
  39658. /**
  39659. * Release the associated resources for a specific mesh
  39660. * @param mesh defines the source mesh
  39661. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39662. */
  39663. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39664. var meshes = this._meshes;
  39665. var index = meshes.indexOf(mesh);
  39666. if (index === -1) {
  39667. return;
  39668. }
  39669. meshes.splice(index, 1);
  39670. mesh._geometry = null;
  39671. if (meshes.length === 0 && shouldDispose) {
  39672. this.dispose();
  39673. }
  39674. };
  39675. /**
  39676. * Apply current geometry to a given mesh
  39677. * @param mesh defines the mesh to apply geometry to
  39678. */
  39679. Geometry.prototype.applyToMesh = function (mesh) {
  39680. if (mesh._geometry === this) {
  39681. return;
  39682. }
  39683. var previousGeometry = mesh._geometry;
  39684. if (previousGeometry) {
  39685. previousGeometry.releaseForMesh(mesh);
  39686. }
  39687. var meshes = this._meshes;
  39688. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39689. mesh._geometry = this;
  39690. this._scene.pushGeometry(this);
  39691. meshes.push(mesh);
  39692. if (this.isReady()) {
  39693. this._applyToMesh(mesh);
  39694. }
  39695. else {
  39696. mesh._boundingInfo = this._boundingInfo;
  39697. }
  39698. };
  39699. Geometry.prototype._updateExtend = function (data) {
  39700. if (data === void 0) { data = null; }
  39701. if (!data) {
  39702. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39703. }
  39704. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39705. };
  39706. Geometry.prototype._applyToMesh = function (mesh) {
  39707. var numOfMeshes = this._meshes.length;
  39708. // vertexBuffers
  39709. for (var kind in this._vertexBuffers) {
  39710. if (numOfMeshes === 1) {
  39711. this._vertexBuffers[kind].create();
  39712. }
  39713. var buffer = this._vertexBuffers[kind].getBuffer();
  39714. if (buffer)
  39715. buffer.references = numOfMeshes;
  39716. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39717. if (!this._extend) {
  39718. this._updateExtend();
  39719. }
  39720. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39721. mesh._createGlobalSubMesh(false);
  39722. //bounding info was just created again, world matrix should be applied again.
  39723. mesh._updateBoundingInfo();
  39724. }
  39725. }
  39726. // indexBuffer
  39727. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39728. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39729. }
  39730. if (this._indexBuffer) {
  39731. this._indexBuffer.references = numOfMeshes;
  39732. }
  39733. };
  39734. Geometry.prototype.notifyUpdate = function (kind) {
  39735. if (this.onGeometryUpdated) {
  39736. this.onGeometryUpdated(this, kind);
  39737. }
  39738. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39739. var mesh = _a[_i];
  39740. mesh._markSubMeshesAsAttributesDirty();
  39741. }
  39742. };
  39743. /**
  39744. * Load the geometry if it was flagged as delay loaded
  39745. * @param scene defines the hosting scene
  39746. * @param onLoaded defines a callback called when the geometry is loaded
  39747. */
  39748. Geometry.prototype.load = function (scene, onLoaded) {
  39749. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39750. return;
  39751. }
  39752. if (this.isReady()) {
  39753. if (onLoaded) {
  39754. onLoaded();
  39755. }
  39756. return;
  39757. }
  39758. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39759. this._queueLoad(scene, onLoaded);
  39760. };
  39761. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39762. var _this = this;
  39763. if (!this.delayLoadingFile) {
  39764. return;
  39765. }
  39766. scene._addPendingData(this);
  39767. scene._loadFile(this.delayLoadingFile, function (data) {
  39768. if (!_this._delayLoadingFunction) {
  39769. return;
  39770. }
  39771. _this._delayLoadingFunction(JSON.parse(data), _this);
  39772. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39773. _this._delayInfo = [];
  39774. scene._removePendingData(_this);
  39775. var meshes = _this._meshes;
  39776. var numOfMeshes = meshes.length;
  39777. for (var index = 0; index < numOfMeshes; index++) {
  39778. _this._applyToMesh(meshes[index]);
  39779. }
  39780. if (onLoaded) {
  39781. onLoaded();
  39782. }
  39783. }, undefined, true);
  39784. };
  39785. /**
  39786. * Invert the geometry to move from a right handed system to a left handed one.
  39787. */
  39788. Geometry.prototype.toLeftHanded = function () {
  39789. // Flip faces
  39790. var tIndices = this.getIndices(false);
  39791. if (tIndices != null && tIndices.length > 0) {
  39792. for (var i = 0; i < tIndices.length; i += 3) {
  39793. var tTemp = tIndices[i + 0];
  39794. tIndices[i + 0] = tIndices[i + 2];
  39795. tIndices[i + 2] = tTemp;
  39796. }
  39797. this.setIndices(tIndices);
  39798. }
  39799. // Negate position.z
  39800. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39801. if (tPositions != null && tPositions.length > 0) {
  39802. for (var i = 0; i < tPositions.length; i += 3) {
  39803. tPositions[i + 2] = -tPositions[i + 2];
  39804. }
  39805. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39806. }
  39807. // Negate normal.z
  39808. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39809. if (tNormals != null && tNormals.length > 0) {
  39810. for (var i = 0; i < tNormals.length; i += 3) {
  39811. tNormals[i + 2] = -tNormals[i + 2];
  39812. }
  39813. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39814. }
  39815. };
  39816. // Cache
  39817. /** @hidden */
  39818. Geometry.prototype._resetPointsArrayCache = function () {
  39819. this._positions = null;
  39820. };
  39821. /** @hidden */
  39822. Geometry.prototype._generatePointsArray = function () {
  39823. if (this._positions)
  39824. return true;
  39825. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39826. if (!data || data.length === 0) {
  39827. return false;
  39828. }
  39829. this._positions = [];
  39830. for (var index = 0; index < data.length; index += 3) {
  39831. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39832. }
  39833. return true;
  39834. };
  39835. /**
  39836. * Gets a value indicating if the geometry is disposed
  39837. * @returns true if the geometry was disposed
  39838. */
  39839. Geometry.prototype.isDisposed = function () {
  39840. return this._isDisposed;
  39841. };
  39842. Geometry.prototype._disposeVertexArrayObjects = function () {
  39843. if (this._vertexArrayObjects) {
  39844. for (var kind in this._vertexArrayObjects) {
  39845. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39846. }
  39847. this._vertexArrayObjects = {};
  39848. }
  39849. };
  39850. /**
  39851. * Free all associated resources
  39852. */
  39853. Geometry.prototype.dispose = function () {
  39854. var meshes = this._meshes;
  39855. var numOfMeshes = meshes.length;
  39856. var index;
  39857. for (index = 0; index < numOfMeshes; index++) {
  39858. this.releaseForMesh(meshes[index]);
  39859. }
  39860. this._meshes = [];
  39861. this._disposeVertexArrayObjects();
  39862. for (var kind in this._vertexBuffers) {
  39863. this._vertexBuffers[kind].dispose();
  39864. }
  39865. this._vertexBuffers = {};
  39866. this._totalVertices = 0;
  39867. if (this._indexBuffer) {
  39868. this._engine._releaseBuffer(this._indexBuffer);
  39869. }
  39870. this._indexBuffer = null;
  39871. this._indices = [];
  39872. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39873. this.delayLoadingFile = null;
  39874. this._delayLoadingFunction = null;
  39875. this._delayInfo = [];
  39876. this._boundingInfo = null;
  39877. this._scene.removeGeometry(this);
  39878. this._isDisposed = true;
  39879. };
  39880. /**
  39881. * Clone the current geometry into a new geometry
  39882. * @param id defines the unique ID of the new geometry
  39883. * @returns a new geometry object
  39884. */
  39885. Geometry.prototype.copy = function (id) {
  39886. var vertexData = new BABYLON.VertexData();
  39887. vertexData.indices = [];
  39888. var indices = this.getIndices();
  39889. if (indices) {
  39890. for (var index = 0; index < indices.length; index++) {
  39891. vertexData.indices.push(indices[index]);
  39892. }
  39893. }
  39894. var updatable = false;
  39895. var stopChecking = false;
  39896. var kind;
  39897. for (kind in this._vertexBuffers) {
  39898. // using slice() to make a copy of the array and not just reference it
  39899. var data = this.getVerticesData(kind);
  39900. if (data instanceof Float32Array) {
  39901. vertexData.set(new Float32Array(data), kind);
  39902. }
  39903. else {
  39904. vertexData.set(data.slice(0), kind);
  39905. }
  39906. if (!stopChecking) {
  39907. var vb = this.getVertexBuffer(kind);
  39908. if (vb) {
  39909. updatable = vb.isUpdatable();
  39910. stopChecking = !updatable;
  39911. }
  39912. }
  39913. }
  39914. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39915. geometry.delayLoadState = this.delayLoadState;
  39916. geometry.delayLoadingFile = this.delayLoadingFile;
  39917. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39918. for (kind in this._delayInfo) {
  39919. geometry._delayInfo = geometry._delayInfo || [];
  39920. geometry._delayInfo.push(kind);
  39921. }
  39922. // Bounding info
  39923. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39924. return geometry;
  39925. };
  39926. /**
  39927. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39928. * @return a JSON representation of the current geometry data (without the vertices data)
  39929. */
  39930. Geometry.prototype.serialize = function () {
  39931. var serializationObject = {};
  39932. serializationObject.id = this.id;
  39933. serializationObject.updatable = this._updatable;
  39934. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39935. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39936. }
  39937. return serializationObject;
  39938. };
  39939. Geometry.prototype.toNumberArray = function (origin) {
  39940. if (Array.isArray(origin)) {
  39941. return origin;
  39942. }
  39943. else {
  39944. return Array.prototype.slice.call(origin);
  39945. }
  39946. };
  39947. /**
  39948. * Serialize all vertices data into a JSON oject
  39949. * @returns a JSON representation of the current geometry data
  39950. */
  39951. Geometry.prototype.serializeVerticeData = function () {
  39952. var serializationObject = this.serialize();
  39953. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39954. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39955. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39956. serializationObject.positions._updatable = true;
  39957. }
  39958. }
  39959. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39960. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39961. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39962. serializationObject.normals._updatable = true;
  39963. }
  39964. }
  39965. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39966. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39967. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39968. serializationObject.tangets._updatable = true;
  39969. }
  39970. }
  39971. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39972. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39973. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39974. serializationObject.uvs._updatable = true;
  39975. }
  39976. }
  39977. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39978. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39979. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39980. serializationObject.uv2s._updatable = true;
  39981. }
  39982. }
  39983. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39984. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39985. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39986. serializationObject.uv3s._updatable = true;
  39987. }
  39988. }
  39989. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39990. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39991. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39992. serializationObject.uv4s._updatable = true;
  39993. }
  39994. }
  39995. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39996. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39997. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39998. serializationObject.uv5s._updatable = true;
  39999. }
  40000. }
  40001. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40002. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40003. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40004. serializationObject.uv6s._updatable = true;
  40005. }
  40006. }
  40007. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40008. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40009. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40010. serializationObject.colors._updatable = true;
  40011. }
  40012. }
  40013. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40014. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40015. serializationObject.matricesIndices._isExpanded = true;
  40016. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40017. serializationObject.matricesIndices._updatable = true;
  40018. }
  40019. }
  40020. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40021. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40022. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40023. serializationObject.matricesWeights._updatable = true;
  40024. }
  40025. }
  40026. serializationObject.indices = this.toNumberArray(this.getIndices());
  40027. return serializationObject;
  40028. };
  40029. // Statics
  40030. /**
  40031. * Extracts a clone of a mesh geometry
  40032. * @param mesh defines the source mesh
  40033. * @param id defines the unique ID of the new geometry object
  40034. * @returns the new geometry object
  40035. */
  40036. Geometry.ExtractFromMesh = function (mesh, id) {
  40037. var geometry = mesh._geometry;
  40038. if (!geometry) {
  40039. return null;
  40040. }
  40041. return geometry.copy(id);
  40042. };
  40043. /**
  40044. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40045. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40046. * Be aware Math.random() could cause collisions, but:
  40047. * "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"
  40048. * @returns a string containing a new GUID
  40049. */
  40050. Geometry.RandomId = function () {
  40051. return BABYLON.Tools.RandomId();
  40052. };
  40053. /** @hidden */
  40054. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40055. var scene = mesh.getScene();
  40056. // Geometry
  40057. var geometryId = parsedGeometry.geometryId;
  40058. if (geometryId) {
  40059. var geometry = scene.getGeometryByID(geometryId);
  40060. if (geometry) {
  40061. geometry.applyToMesh(mesh);
  40062. }
  40063. }
  40064. else if (parsedGeometry instanceof ArrayBuffer) {
  40065. var binaryInfo = mesh._binaryInfo;
  40066. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40067. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40068. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40069. }
  40070. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40071. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40072. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40073. }
  40074. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40075. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40076. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40077. }
  40078. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40079. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40080. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40081. }
  40082. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40083. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40084. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40085. }
  40086. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40087. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40088. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40089. }
  40090. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40091. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40092. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40093. }
  40094. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40095. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40096. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40097. }
  40098. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40099. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40100. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40101. }
  40102. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40103. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40104. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40105. }
  40106. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40107. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40108. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40109. }
  40110. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40111. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40112. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40113. }
  40114. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40115. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40116. mesh.setIndices(indicesData, null);
  40117. }
  40118. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40119. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40120. mesh.subMeshes = [];
  40121. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40122. var materialIndex = subMeshesData[(i * 5) + 0];
  40123. var verticesStart = subMeshesData[(i * 5) + 1];
  40124. var verticesCount = subMeshesData[(i * 5) + 2];
  40125. var indexStart = subMeshesData[(i * 5) + 3];
  40126. var indexCount = subMeshesData[(i * 5) + 4];
  40127. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40128. }
  40129. }
  40130. }
  40131. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40132. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40133. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40134. if (parsedGeometry.tangents) {
  40135. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40136. }
  40137. if (parsedGeometry.uvs) {
  40138. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40139. }
  40140. if (parsedGeometry.uvs2) {
  40141. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40142. }
  40143. if (parsedGeometry.uvs3) {
  40144. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40145. }
  40146. if (parsedGeometry.uvs4) {
  40147. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40148. }
  40149. if (parsedGeometry.uvs5) {
  40150. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40151. }
  40152. if (parsedGeometry.uvs6) {
  40153. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40154. }
  40155. if (parsedGeometry.colors) {
  40156. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40157. }
  40158. if (parsedGeometry.matricesIndices) {
  40159. if (!parsedGeometry.matricesIndices._isExpanded) {
  40160. var floatIndices = [];
  40161. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40162. var matricesIndex = parsedGeometry.matricesIndices[i];
  40163. floatIndices.push(matricesIndex & 0x000000FF);
  40164. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40165. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40166. floatIndices.push(matricesIndex >> 24);
  40167. }
  40168. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40169. }
  40170. else {
  40171. delete parsedGeometry.matricesIndices._isExpanded;
  40172. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40173. }
  40174. }
  40175. if (parsedGeometry.matricesIndicesExtra) {
  40176. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40177. var floatIndices = [];
  40178. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40179. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40180. floatIndices.push(matricesIndex & 0x000000FF);
  40181. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40182. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40183. floatIndices.push(matricesIndex >> 24);
  40184. }
  40185. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40186. }
  40187. else {
  40188. delete parsedGeometry.matricesIndices._isExpanded;
  40189. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40190. }
  40191. }
  40192. if (parsedGeometry.matricesWeights) {
  40193. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40194. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40195. }
  40196. if (parsedGeometry.matricesWeightsExtra) {
  40197. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40198. }
  40199. mesh.setIndices(parsedGeometry.indices, null);
  40200. }
  40201. // SubMeshes
  40202. if (parsedGeometry.subMeshes) {
  40203. mesh.subMeshes = [];
  40204. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40205. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40206. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40207. }
  40208. }
  40209. // Flat shading
  40210. if (mesh._shouldGenerateFlatShading) {
  40211. mesh.convertToFlatShadedMesh();
  40212. delete mesh._shouldGenerateFlatShading;
  40213. }
  40214. // Update
  40215. mesh.computeWorldMatrix(true);
  40216. // Octree
  40217. var sceneOctree = scene.selectionOctree;
  40218. if (sceneOctree !== undefined && sceneOctree !== null) {
  40219. sceneOctree.addMesh(mesh);
  40220. }
  40221. };
  40222. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40223. var epsilon = 1e-3;
  40224. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40225. return;
  40226. }
  40227. var noInfluenceBoneIndex = 0.0;
  40228. if (parsedGeometry.skeletonId > -1) {
  40229. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40230. if (!skeleton) {
  40231. return;
  40232. }
  40233. noInfluenceBoneIndex = skeleton.bones.length;
  40234. }
  40235. else {
  40236. return;
  40237. }
  40238. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40239. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40240. var matricesWeights = parsedGeometry.matricesWeights;
  40241. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40242. var influencers = parsedGeometry.numBoneInfluencer;
  40243. var size = matricesWeights.length;
  40244. for (var i = 0; i < size; i += 4) {
  40245. var weight = 0.0;
  40246. var firstZeroWeight = -1;
  40247. for (var j = 0; j < 4; j++) {
  40248. var w = matricesWeights[i + j];
  40249. weight += w;
  40250. if (w < epsilon && firstZeroWeight < 0) {
  40251. firstZeroWeight = j;
  40252. }
  40253. }
  40254. if (matricesWeightsExtra) {
  40255. for (var j = 0; j < 4; j++) {
  40256. var w = matricesWeightsExtra[i + j];
  40257. weight += w;
  40258. if (w < epsilon && firstZeroWeight < 0) {
  40259. firstZeroWeight = j + 4;
  40260. }
  40261. }
  40262. }
  40263. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40264. firstZeroWeight = influencers - 1;
  40265. }
  40266. if (weight > epsilon) {
  40267. var mweight = 1.0 / weight;
  40268. for (var j = 0; j < 4; j++) {
  40269. matricesWeights[i + j] *= mweight;
  40270. }
  40271. if (matricesWeightsExtra) {
  40272. for (var j = 0; j < 4; j++) {
  40273. matricesWeightsExtra[i + j] *= mweight;
  40274. }
  40275. }
  40276. }
  40277. else {
  40278. if (firstZeroWeight >= 4) {
  40279. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40280. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40281. }
  40282. else {
  40283. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40284. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40285. }
  40286. }
  40287. }
  40288. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40289. if (parsedGeometry.matricesWeightsExtra) {
  40290. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40291. }
  40292. };
  40293. /**
  40294. * Create a new geometry from persisted data (Using .babylon file format)
  40295. * @param parsedVertexData defines the persisted data
  40296. * @param scene defines the hosting scene
  40297. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40298. * @returns the new geometry object
  40299. */
  40300. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40301. if (scene.getGeometryByID(parsedVertexData.id)) {
  40302. return null; // null since geometry could be something else than a box...
  40303. }
  40304. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40305. if (BABYLON.Tags) {
  40306. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40307. }
  40308. if (parsedVertexData.delayLoadingFile) {
  40309. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40310. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40311. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40312. geometry._delayInfo = [];
  40313. if (parsedVertexData.hasUVs) {
  40314. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40315. }
  40316. if (parsedVertexData.hasUVs2) {
  40317. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40318. }
  40319. if (parsedVertexData.hasUVs3) {
  40320. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40321. }
  40322. if (parsedVertexData.hasUVs4) {
  40323. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40324. }
  40325. if (parsedVertexData.hasUVs5) {
  40326. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40327. }
  40328. if (parsedVertexData.hasUVs6) {
  40329. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40330. }
  40331. if (parsedVertexData.hasColors) {
  40332. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40333. }
  40334. if (parsedVertexData.hasMatricesIndices) {
  40335. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40336. }
  40337. if (parsedVertexData.hasMatricesWeights) {
  40338. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40339. }
  40340. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40341. }
  40342. else {
  40343. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40344. }
  40345. scene.pushGeometry(geometry, true);
  40346. return geometry;
  40347. };
  40348. return Geometry;
  40349. }());
  40350. BABYLON.Geometry = Geometry;
  40351. // Primitives
  40352. /// Abstract class
  40353. /**
  40354. * Abstract class used to provide common services for all typed geometries
  40355. * @hidden
  40356. */
  40357. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40358. __extends(_PrimitiveGeometry, _super);
  40359. /**
  40360. * Creates a new typed geometry
  40361. * @param id defines the unique ID of the geometry
  40362. * @param scene defines the hosting scene
  40363. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40364. * @param mesh defines the hosting mesh (can be null)
  40365. */
  40366. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40367. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40368. if (mesh === void 0) { mesh = null; }
  40369. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40370. _this._canBeRegenerated = _canBeRegenerated;
  40371. _this._beingRegenerated = true;
  40372. _this.regenerate();
  40373. _this._beingRegenerated = false;
  40374. return _this;
  40375. }
  40376. /**
  40377. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40378. * @returns true if the geometry can be regenerated
  40379. */
  40380. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40381. return this._canBeRegenerated;
  40382. };
  40383. /**
  40384. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40385. */
  40386. _PrimitiveGeometry.prototype.regenerate = function () {
  40387. if (!this._canBeRegenerated) {
  40388. return;
  40389. }
  40390. this._beingRegenerated = true;
  40391. this.setAllVerticesData(this._regenerateVertexData(), false);
  40392. this._beingRegenerated = false;
  40393. };
  40394. /**
  40395. * Clone the geometry
  40396. * @param id defines the unique ID of the new geometry
  40397. * @returns the new geometry
  40398. */
  40399. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40400. return _super.prototype.copy.call(this, id);
  40401. };
  40402. // overrides
  40403. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40404. if (!this._beingRegenerated) {
  40405. return;
  40406. }
  40407. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40408. };
  40409. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40410. if (!this._beingRegenerated) {
  40411. return;
  40412. }
  40413. _super.prototype.setVerticesData.call(this, kind, data, false);
  40414. };
  40415. // to override
  40416. /** @hidden */
  40417. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40418. throw new Error("Abstract method");
  40419. };
  40420. _PrimitiveGeometry.prototype.copy = function (id) {
  40421. throw new Error("Must be overriden in sub-classes.");
  40422. };
  40423. _PrimitiveGeometry.prototype.serialize = function () {
  40424. var serializationObject = _super.prototype.serialize.call(this);
  40425. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40426. return serializationObject;
  40427. };
  40428. return _PrimitiveGeometry;
  40429. }(Geometry));
  40430. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40431. /**
  40432. * Creates a ribbon geometry
  40433. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40434. */
  40435. var RibbonGeometry = /** @class */ (function (_super) {
  40436. __extends(RibbonGeometry, _super);
  40437. /**
  40438. * Creates a ribbon geometry
  40439. * @param id defines the unique ID of the geometry
  40440. * @param scene defines the hosting scene
  40441. * @param pathArray defines the array of paths to use
  40442. * @param closeArray defines if the last path and the first path must be joined
  40443. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40444. * @param offset defines the offset between points
  40445. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40446. * @param mesh defines the hosting mesh (can be null)
  40447. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40448. */
  40449. function RibbonGeometry(id, scene,
  40450. /**
  40451. * Defines the array of paths to use
  40452. */
  40453. pathArray,
  40454. /**
  40455. * Defines if the last and first points of each path in your pathArray must be joined
  40456. */
  40457. closeArray,
  40458. /**
  40459. * Defines if the last and first points of each path in your pathArray must be joined
  40460. */
  40461. closePath,
  40462. /**
  40463. * Defines the offset between points
  40464. */
  40465. offset, canBeRegenerated, mesh,
  40466. /**
  40467. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40468. */
  40469. side) {
  40470. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40471. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40472. _this.pathArray = pathArray;
  40473. _this.closeArray = closeArray;
  40474. _this.closePath = closePath;
  40475. _this.offset = offset;
  40476. _this.side = side;
  40477. return _this;
  40478. }
  40479. /** @hidden */
  40480. RibbonGeometry.prototype._regenerateVertexData = function () {
  40481. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40482. };
  40483. RibbonGeometry.prototype.copy = function (id) {
  40484. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40485. };
  40486. return RibbonGeometry;
  40487. }(_PrimitiveGeometry));
  40488. BABYLON.RibbonGeometry = RibbonGeometry;
  40489. /**
  40490. * Creates a box geometry
  40491. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40492. */
  40493. var BoxGeometry = /** @class */ (function (_super) {
  40494. __extends(BoxGeometry, _super);
  40495. /**
  40496. * Creates a box geometry
  40497. * @param id defines the unique ID of the geometry
  40498. * @param scene defines the hosting scene
  40499. * @param size defines the zise of the box (width, height and depth are the same)
  40500. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40501. * @param mesh defines the hosting mesh (can be null)
  40502. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40503. */
  40504. function BoxGeometry(id, scene,
  40505. /**
  40506. * Defines the zise of the box (width, height and depth are the same)
  40507. */
  40508. size, canBeRegenerated, mesh,
  40509. /**
  40510. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40511. */
  40512. side) {
  40513. if (mesh === void 0) { mesh = null; }
  40514. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40515. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40516. _this.size = size;
  40517. _this.side = side;
  40518. return _this;
  40519. }
  40520. BoxGeometry.prototype._regenerateVertexData = function () {
  40521. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40522. };
  40523. BoxGeometry.prototype.copy = function (id) {
  40524. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40525. };
  40526. BoxGeometry.prototype.serialize = function () {
  40527. var serializationObject = _super.prototype.serialize.call(this);
  40528. serializationObject.size = this.size;
  40529. return serializationObject;
  40530. };
  40531. BoxGeometry.Parse = function (parsedBox, scene) {
  40532. if (scene.getGeometryByID(parsedBox.id)) {
  40533. return null; // null since geometry could be something else than a box...
  40534. }
  40535. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40536. if (BABYLON.Tags) {
  40537. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40538. }
  40539. scene.pushGeometry(box, true);
  40540. return box;
  40541. };
  40542. return BoxGeometry;
  40543. }(_PrimitiveGeometry));
  40544. BABYLON.BoxGeometry = BoxGeometry;
  40545. /**
  40546. * Creates a sphere geometry
  40547. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40548. */
  40549. var SphereGeometry = /** @class */ (function (_super) {
  40550. __extends(SphereGeometry, _super);
  40551. /**
  40552. * Create a new sphere geometry
  40553. * @param id defines the unique ID of the geometry
  40554. * @param scene defines the hosting scene
  40555. * @param segments defines the number of segments to use to create the sphere
  40556. * @param diameter defines the diameter of the sphere
  40557. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40558. * @param mesh defines the hosting mesh (can be null)
  40559. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40560. */
  40561. function SphereGeometry(id, scene,
  40562. /**
  40563. * Defines the number of segments to use to create the sphere
  40564. */
  40565. segments,
  40566. /**
  40567. * Defines the diameter of the sphere
  40568. */
  40569. diameter, canBeRegenerated, mesh,
  40570. /**
  40571. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40572. */
  40573. side) {
  40574. if (mesh === void 0) { mesh = null; }
  40575. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40576. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40577. _this.segments = segments;
  40578. _this.diameter = diameter;
  40579. _this.side = side;
  40580. return _this;
  40581. }
  40582. SphereGeometry.prototype._regenerateVertexData = function () {
  40583. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40584. };
  40585. SphereGeometry.prototype.copy = function (id) {
  40586. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40587. };
  40588. SphereGeometry.prototype.serialize = function () {
  40589. var serializationObject = _super.prototype.serialize.call(this);
  40590. serializationObject.segments = this.segments;
  40591. serializationObject.diameter = this.diameter;
  40592. return serializationObject;
  40593. };
  40594. SphereGeometry.Parse = function (parsedSphere, scene) {
  40595. if (scene.getGeometryByID(parsedSphere.id)) {
  40596. return null; // null since geometry could be something else than a sphere...
  40597. }
  40598. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40599. if (BABYLON.Tags) {
  40600. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40601. }
  40602. scene.pushGeometry(sphere, true);
  40603. return sphere;
  40604. };
  40605. return SphereGeometry;
  40606. }(_PrimitiveGeometry));
  40607. BABYLON.SphereGeometry = SphereGeometry;
  40608. /**
  40609. * Creates a disc geometry
  40610. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40611. */
  40612. var DiscGeometry = /** @class */ (function (_super) {
  40613. __extends(DiscGeometry, _super);
  40614. /**
  40615. * Creates a new disc geometry
  40616. * @param id defines the unique ID of the geometry
  40617. * @param scene defines the hosting scene
  40618. * @param radius defines the radius of the disc
  40619. * @param tessellation defines the tesselation factor to apply to the disc
  40620. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40621. * @param mesh defines the hosting mesh (can be null)
  40622. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40623. */
  40624. function DiscGeometry(id, scene,
  40625. /**
  40626. * Defines the radius of the disc
  40627. */
  40628. radius,
  40629. /**
  40630. * Defines the tesselation factor to apply to the disc
  40631. */
  40632. tessellation, canBeRegenerated, mesh,
  40633. /**
  40634. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40635. */
  40636. side) {
  40637. if (mesh === void 0) { mesh = null; }
  40638. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40639. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40640. _this.radius = radius;
  40641. _this.tessellation = tessellation;
  40642. _this.side = side;
  40643. return _this;
  40644. }
  40645. DiscGeometry.prototype._regenerateVertexData = function () {
  40646. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40647. };
  40648. DiscGeometry.prototype.copy = function (id) {
  40649. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40650. };
  40651. return DiscGeometry;
  40652. }(_PrimitiveGeometry));
  40653. BABYLON.DiscGeometry = DiscGeometry;
  40654. /**
  40655. * Creates a new cylinder geometry
  40656. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40657. */
  40658. var CylinderGeometry = /** @class */ (function (_super) {
  40659. __extends(CylinderGeometry, _super);
  40660. /**
  40661. * Creates a new cylinder geometry
  40662. * @param id defines the unique ID of the geometry
  40663. * @param scene defines the hosting scene
  40664. * @param height defines the height of the cylinder
  40665. * @param diameterTop defines the diameter of the cylinder's top cap
  40666. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40667. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40668. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40669. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40670. * @param mesh defines the hosting mesh (can be null)
  40671. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40672. */
  40673. function CylinderGeometry(id, scene,
  40674. /**
  40675. * Defines the height of the cylinder
  40676. */
  40677. height,
  40678. /**
  40679. * Defines the diameter of the cylinder's top cap
  40680. */
  40681. diameterTop,
  40682. /**
  40683. * Defines the diameter of the cylinder's bottom cap
  40684. */
  40685. diameterBottom,
  40686. /**
  40687. * Defines the tessellation factor to apply to the cylinder
  40688. */
  40689. tessellation,
  40690. /**
  40691. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40692. */
  40693. subdivisions, canBeRegenerated, mesh,
  40694. /**
  40695. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40696. */
  40697. side) {
  40698. if (subdivisions === void 0) { subdivisions = 1; }
  40699. if (mesh === void 0) { mesh = null; }
  40700. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40701. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40702. _this.height = height;
  40703. _this.diameterTop = diameterTop;
  40704. _this.diameterBottom = diameterBottom;
  40705. _this.tessellation = tessellation;
  40706. _this.subdivisions = subdivisions;
  40707. _this.side = side;
  40708. return _this;
  40709. }
  40710. CylinderGeometry.prototype._regenerateVertexData = function () {
  40711. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40712. };
  40713. CylinderGeometry.prototype.copy = function (id) {
  40714. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40715. };
  40716. CylinderGeometry.prototype.serialize = function () {
  40717. var serializationObject = _super.prototype.serialize.call(this);
  40718. serializationObject.height = this.height;
  40719. serializationObject.diameterTop = this.diameterTop;
  40720. serializationObject.diameterBottom = this.diameterBottom;
  40721. serializationObject.tessellation = this.tessellation;
  40722. return serializationObject;
  40723. };
  40724. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40725. if (scene.getGeometryByID(parsedCylinder.id)) {
  40726. return null; // null since geometry could be something else than a cylinder...
  40727. }
  40728. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40729. if (BABYLON.Tags) {
  40730. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40731. }
  40732. scene.pushGeometry(cylinder, true);
  40733. return cylinder;
  40734. };
  40735. return CylinderGeometry;
  40736. }(_PrimitiveGeometry));
  40737. BABYLON.CylinderGeometry = CylinderGeometry;
  40738. /**
  40739. * Creates a new torus geometry
  40740. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40741. */
  40742. var TorusGeometry = /** @class */ (function (_super) {
  40743. __extends(TorusGeometry, _super);
  40744. /**
  40745. * Creates a new torus geometry
  40746. * @param id defines the unique ID of the geometry
  40747. * @param scene defines the hosting scene
  40748. * @param diameter defines the diameter of the torus
  40749. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40750. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40751. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40752. * @param mesh defines the hosting mesh (can be null)
  40753. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40754. */
  40755. function TorusGeometry(id, scene,
  40756. /**
  40757. * Defines the diameter of the torus
  40758. */
  40759. diameter,
  40760. /**
  40761. * Defines the thickness of the torus (ie. internal diameter)
  40762. */
  40763. thickness,
  40764. /**
  40765. * Defines the tesselation factor to apply to the torus
  40766. */
  40767. tessellation, canBeRegenerated, mesh,
  40768. /**
  40769. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40770. */
  40771. side) {
  40772. if (mesh === void 0) { mesh = null; }
  40773. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40774. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40775. _this.diameter = diameter;
  40776. _this.thickness = thickness;
  40777. _this.tessellation = tessellation;
  40778. _this.side = side;
  40779. return _this;
  40780. }
  40781. TorusGeometry.prototype._regenerateVertexData = function () {
  40782. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40783. };
  40784. TorusGeometry.prototype.copy = function (id) {
  40785. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40786. };
  40787. TorusGeometry.prototype.serialize = function () {
  40788. var serializationObject = _super.prototype.serialize.call(this);
  40789. serializationObject.diameter = this.diameter;
  40790. serializationObject.thickness = this.thickness;
  40791. serializationObject.tessellation = this.tessellation;
  40792. return serializationObject;
  40793. };
  40794. TorusGeometry.Parse = function (parsedTorus, scene) {
  40795. if (scene.getGeometryByID(parsedTorus.id)) {
  40796. return null; // null since geometry could be something else than a torus...
  40797. }
  40798. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40799. if (BABYLON.Tags) {
  40800. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40801. }
  40802. scene.pushGeometry(torus, true);
  40803. return torus;
  40804. };
  40805. return TorusGeometry;
  40806. }(_PrimitiveGeometry));
  40807. BABYLON.TorusGeometry = TorusGeometry;
  40808. /**
  40809. * Creates a new ground geometry
  40810. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40811. */
  40812. var GroundGeometry = /** @class */ (function (_super) {
  40813. __extends(GroundGeometry, _super);
  40814. /**
  40815. * Creates a new ground geometry
  40816. * @param id defines the unique ID of the geometry
  40817. * @param scene defines the hosting scene
  40818. * @param width defines the width of the ground
  40819. * @param height defines the height of the ground
  40820. * @param subdivisions defines the subdivisions to apply to the ground
  40821. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40822. * @param mesh defines the hosting mesh (can be null)
  40823. */
  40824. function GroundGeometry(id, scene,
  40825. /**
  40826. * Defines the width of the ground
  40827. */
  40828. width,
  40829. /**
  40830. * Defines the height of the ground
  40831. */
  40832. height,
  40833. /**
  40834. * Defines the subdivisions to apply to the ground
  40835. */
  40836. subdivisions, canBeRegenerated, mesh) {
  40837. if (mesh === void 0) { mesh = null; }
  40838. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40839. _this.width = width;
  40840. _this.height = height;
  40841. _this.subdivisions = subdivisions;
  40842. return _this;
  40843. }
  40844. GroundGeometry.prototype._regenerateVertexData = function () {
  40845. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40846. };
  40847. GroundGeometry.prototype.copy = function (id) {
  40848. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40849. };
  40850. GroundGeometry.prototype.serialize = function () {
  40851. var serializationObject = _super.prototype.serialize.call(this);
  40852. serializationObject.width = this.width;
  40853. serializationObject.height = this.height;
  40854. serializationObject.subdivisions = this.subdivisions;
  40855. return serializationObject;
  40856. };
  40857. GroundGeometry.Parse = function (parsedGround, scene) {
  40858. if (scene.getGeometryByID(parsedGround.id)) {
  40859. return null; // null since geometry could be something else than a ground...
  40860. }
  40861. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40862. if (BABYLON.Tags) {
  40863. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40864. }
  40865. scene.pushGeometry(ground, true);
  40866. return ground;
  40867. };
  40868. return GroundGeometry;
  40869. }(_PrimitiveGeometry));
  40870. BABYLON.GroundGeometry = GroundGeometry;
  40871. /**
  40872. * Creates a tiled ground geometry
  40873. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40874. */
  40875. var TiledGroundGeometry = /** @class */ (function (_super) {
  40876. __extends(TiledGroundGeometry, _super);
  40877. /**
  40878. * Creates a tiled ground geometry
  40879. * @param id defines the unique ID of the geometry
  40880. * @param scene defines the hosting scene
  40881. * @param xmin defines the minimum value on X axis
  40882. * @param zmin defines the minimum value on Z axis
  40883. * @param xmax defines the maximum value on X axis
  40884. * @param zmax defines the maximum value on Z axis
  40885. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40886. * @param precision defines the precision to use when computing the tiles
  40887. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40888. * @param mesh defines the hosting mesh (can be null)
  40889. */
  40890. function TiledGroundGeometry(id, scene,
  40891. /**
  40892. * Defines the minimum value on X axis
  40893. */
  40894. xmin,
  40895. /**
  40896. * Defines the minimum value on Z axis
  40897. */
  40898. zmin,
  40899. /**
  40900. * Defines the maximum value on X axis
  40901. */
  40902. xmax,
  40903. /**
  40904. * Defines the maximum value on Z axis
  40905. */
  40906. zmax,
  40907. /**
  40908. * Defines the subdivisions to apply to the ground
  40909. */
  40910. subdivisions,
  40911. /**
  40912. * Defines the precision to use when computing the tiles
  40913. */
  40914. precision, canBeRegenerated, mesh) {
  40915. if (mesh === void 0) { mesh = null; }
  40916. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40917. _this.xmin = xmin;
  40918. _this.zmin = zmin;
  40919. _this.xmax = xmax;
  40920. _this.zmax = zmax;
  40921. _this.subdivisions = subdivisions;
  40922. _this.precision = precision;
  40923. return _this;
  40924. }
  40925. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40926. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40927. };
  40928. TiledGroundGeometry.prototype.copy = function (id) {
  40929. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40930. };
  40931. return TiledGroundGeometry;
  40932. }(_PrimitiveGeometry));
  40933. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40934. /**
  40935. * Creates a plane geometry
  40936. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40937. */
  40938. var PlaneGeometry = /** @class */ (function (_super) {
  40939. __extends(PlaneGeometry, _super);
  40940. /**
  40941. * Creates a plane geometry
  40942. * @param id defines the unique ID of the geometry
  40943. * @param scene defines the hosting scene
  40944. * @param size defines the size of the plane (width === height)
  40945. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40946. * @param mesh defines the hosting mesh (can be null)
  40947. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40948. */
  40949. function PlaneGeometry(id, scene,
  40950. /**
  40951. * Defines the size of the plane (width === height)
  40952. */
  40953. size, canBeRegenerated, mesh,
  40954. /**
  40955. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40956. */
  40957. side) {
  40958. if (mesh === void 0) { mesh = null; }
  40959. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40960. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40961. _this.size = size;
  40962. _this.side = side;
  40963. return _this;
  40964. }
  40965. PlaneGeometry.prototype._regenerateVertexData = function () {
  40966. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40967. };
  40968. PlaneGeometry.prototype.copy = function (id) {
  40969. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40970. };
  40971. PlaneGeometry.prototype.serialize = function () {
  40972. var serializationObject = _super.prototype.serialize.call(this);
  40973. serializationObject.size = this.size;
  40974. return serializationObject;
  40975. };
  40976. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40977. if (scene.getGeometryByID(parsedPlane.id)) {
  40978. return null; // null since geometry could be something else than a ground...
  40979. }
  40980. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40981. if (BABYLON.Tags) {
  40982. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40983. }
  40984. scene.pushGeometry(plane, true);
  40985. return plane;
  40986. };
  40987. return PlaneGeometry;
  40988. }(_PrimitiveGeometry));
  40989. BABYLON.PlaneGeometry = PlaneGeometry;
  40990. /**
  40991. * Creates a torus knot geometry
  40992. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40993. */
  40994. var TorusKnotGeometry = /** @class */ (function (_super) {
  40995. __extends(TorusKnotGeometry, _super);
  40996. /**
  40997. * Creates a torus knot geometry
  40998. * @param id defines the unique ID of the geometry
  40999. * @param scene defines the hosting scene
  41000. * @param radius defines the radius of the torus knot
  41001. * @param tube defines the thickness of the torus knot tube
  41002. * @param radialSegments defines the number of radial segments
  41003. * @param tubularSegments defines the number of tubular segments
  41004. * @param p defines the first number of windings
  41005. * @param q defines the second number of windings
  41006. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41007. * @param mesh defines the hosting mesh (can be null)
  41008. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41009. */
  41010. function TorusKnotGeometry(id, scene,
  41011. /**
  41012. * Defines the radius of the torus knot
  41013. */
  41014. radius,
  41015. /**
  41016. * Defines the thickness of the torus knot tube
  41017. */
  41018. tube,
  41019. /**
  41020. * Defines the number of radial segments
  41021. */
  41022. radialSegments,
  41023. /**
  41024. * Defines the number of tubular segments
  41025. */
  41026. tubularSegments,
  41027. /**
  41028. * Defines the first number of windings
  41029. */
  41030. p,
  41031. /**
  41032. * Defines the second number of windings
  41033. */
  41034. q, canBeRegenerated, mesh,
  41035. /**
  41036. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41037. */
  41038. side) {
  41039. if (mesh === void 0) { mesh = null; }
  41040. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41041. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41042. _this.radius = radius;
  41043. _this.tube = tube;
  41044. _this.radialSegments = radialSegments;
  41045. _this.tubularSegments = tubularSegments;
  41046. _this.p = p;
  41047. _this.q = q;
  41048. _this.side = side;
  41049. return _this;
  41050. }
  41051. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41052. 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 });
  41053. };
  41054. TorusKnotGeometry.prototype.copy = function (id) {
  41055. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41056. };
  41057. TorusKnotGeometry.prototype.serialize = function () {
  41058. var serializationObject = _super.prototype.serialize.call(this);
  41059. serializationObject.radius = this.radius;
  41060. serializationObject.tube = this.tube;
  41061. serializationObject.radialSegments = this.radialSegments;
  41062. serializationObject.tubularSegments = this.tubularSegments;
  41063. serializationObject.p = this.p;
  41064. serializationObject.q = this.q;
  41065. return serializationObject;
  41066. };
  41067. ;
  41068. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41069. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41070. return null; // null since geometry could be something else than a ground...
  41071. }
  41072. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41073. if (BABYLON.Tags) {
  41074. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41075. }
  41076. scene.pushGeometry(torusKnot, true);
  41077. return torusKnot;
  41078. };
  41079. return TorusKnotGeometry;
  41080. }(_PrimitiveGeometry));
  41081. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41082. //}
  41083. })(BABYLON || (BABYLON = {}));
  41084. //# sourceMappingURL=babylon.geometry.js.map
  41085. var BABYLON;
  41086. (function (BABYLON) {
  41087. /**
  41088. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41089. */
  41090. var PerformanceMonitor = /** @class */ (function () {
  41091. /**
  41092. * constructor
  41093. * @param frameSampleSize The number of samples required to saturate the sliding window
  41094. */
  41095. function PerformanceMonitor(frameSampleSize) {
  41096. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41097. this._enabled = true;
  41098. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41099. }
  41100. /**
  41101. * Samples current frame
  41102. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41103. */
  41104. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41105. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41106. if (!this._enabled)
  41107. return;
  41108. if (this._lastFrameTimeMs != null) {
  41109. var dt = timeMs - this._lastFrameTimeMs;
  41110. this._rollingFrameTime.add(dt);
  41111. }
  41112. this._lastFrameTimeMs = timeMs;
  41113. };
  41114. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41115. /**
  41116. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41117. * @return Average frame time in milliseconds
  41118. */
  41119. get: function () {
  41120. return this._rollingFrameTime.average;
  41121. },
  41122. enumerable: true,
  41123. configurable: true
  41124. });
  41125. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41126. /**
  41127. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41128. * @return Frame time variance in milliseconds squared
  41129. */
  41130. get: function () {
  41131. return this._rollingFrameTime.variance;
  41132. },
  41133. enumerable: true,
  41134. configurable: true
  41135. });
  41136. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41137. /**
  41138. * Returns the frame time of the most recent frame
  41139. * @return Frame time in milliseconds
  41140. */
  41141. get: function () {
  41142. return this._rollingFrameTime.history(0);
  41143. },
  41144. enumerable: true,
  41145. configurable: true
  41146. });
  41147. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41148. /**
  41149. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41150. * @return Framerate in frames per second
  41151. */
  41152. get: function () {
  41153. return 1000.0 / this._rollingFrameTime.average;
  41154. },
  41155. enumerable: true,
  41156. configurable: true
  41157. });
  41158. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41159. /**
  41160. * Returns the average framerate in frames per second using the most recent frame time
  41161. * @return Framerate in frames per second
  41162. */
  41163. get: function () {
  41164. var history = this._rollingFrameTime.history(0);
  41165. if (history === 0) {
  41166. return 0;
  41167. }
  41168. return 1000.0 / history;
  41169. },
  41170. enumerable: true,
  41171. configurable: true
  41172. });
  41173. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41174. /**
  41175. * Returns true if enough samples have been taken to completely fill the sliding window
  41176. * @return true if saturated
  41177. */
  41178. get: function () {
  41179. return this._rollingFrameTime.isSaturated();
  41180. },
  41181. enumerable: true,
  41182. configurable: true
  41183. });
  41184. /**
  41185. * Enables contributions to the sliding window sample set
  41186. */
  41187. PerformanceMonitor.prototype.enable = function () {
  41188. this._enabled = true;
  41189. };
  41190. /**
  41191. * Disables contributions to the sliding window sample set
  41192. * Samples will not be interpolated over the disabled period
  41193. */
  41194. PerformanceMonitor.prototype.disable = function () {
  41195. this._enabled = false;
  41196. //clear last sample to avoid interpolating over the disabled period when next enabled
  41197. this._lastFrameTimeMs = null;
  41198. };
  41199. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41200. /**
  41201. * Returns true if sampling is enabled
  41202. * @return true if enabled
  41203. */
  41204. get: function () {
  41205. return this._enabled;
  41206. },
  41207. enumerable: true,
  41208. configurable: true
  41209. });
  41210. /**
  41211. * Resets performance monitor
  41212. */
  41213. PerformanceMonitor.prototype.reset = function () {
  41214. //clear last sample to avoid interpolating over the disabled period when next enabled
  41215. this._lastFrameTimeMs = null;
  41216. //wipe record
  41217. this._rollingFrameTime.reset();
  41218. };
  41219. return PerformanceMonitor;
  41220. }());
  41221. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41222. /**
  41223. * RollingAverage
  41224. *
  41225. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41226. */
  41227. var RollingAverage = /** @class */ (function () {
  41228. /**
  41229. * constructor
  41230. * @param length The number of samples required to saturate the sliding window
  41231. */
  41232. function RollingAverage(length) {
  41233. this._samples = new Array(length);
  41234. this.reset();
  41235. }
  41236. /**
  41237. * Adds a sample to the sample set
  41238. * @param v The sample value
  41239. */
  41240. RollingAverage.prototype.add = function (v) {
  41241. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41242. var delta;
  41243. //we need to check if we've already wrapped round
  41244. if (this.isSaturated()) {
  41245. //remove bottom of stack from mean
  41246. var bottomValue = this._samples[this._pos];
  41247. delta = bottomValue - this.average;
  41248. this.average -= delta / (this._sampleCount - 1);
  41249. this._m2 -= delta * (bottomValue - this.average);
  41250. }
  41251. else {
  41252. this._sampleCount++;
  41253. }
  41254. //add new value to mean
  41255. delta = v - this.average;
  41256. this.average += delta / (this._sampleCount);
  41257. this._m2 += delta * (v - this.average);
  41258. //set the new variance
  41259. this.variance = this._m2 / (this._sampleCount - 1);
  41260. this._samples[this._pos] = v;
  41261. this._pos++;
  41262. this._pos %= this._samples.length; //positive wrap around
  41263. };
  41264. /**
  41265. * Returns previously added values or null if outside of history or outside the sliding window domain
  41266. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41267. * @return Value previously recorded with add() or null if outside of range
  41268. */
  41269. RollingAverage.prototype.history = function (i) {
  41270. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41271. return 0;
  41272. }
  41273. var i0 = this._wrapPosition(this._pos - 1.0);
  41274. return this._samples[this._wrapPosition(i0 - i)];
  41275. };
  41276. /**
  41277. * Returns true if enough samples have been taken to completely fill the sliding window
  41278. * @return true if sample-set saturated
  41279. */
  41280. RollingAverage.prototype.isSaturated = function () {
  41281. return this._sampleCount >= this._samples.length;
  41282. };
  41283. /**
  41284. * Resets the rolling average (equivalent to 0 samples taken so far)
  41285. */
  41286. RollingAverage.prototype.reset = function () {
  41287. this.average = 0;
  41288. this.variance = 0;
  41289. this._sampleCount = 0;
  41290. this._pos = 0;
  41291. this._m2 = 0;
  41292. };
  41293. /**
  41294. * Wraps a value around the sample range boundaries
  41295. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41296. * @return Wrapped position in sample range
  41297. */
  41298. RollingAverage.prototype._wrapPosition = function (i) {
  41299. var max = this._samples.length;
  41300. return ((i % max) + max) % max;
  41301. };
  41302. return RollingAverage;
  41303. }());
  41304. BABYLON.RollingAverage = RollingAverage;
  41305. })(BABYLON || (BABYLON = {}));
  41306. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41307. var BABYLON;
  41308. (function (BABYLON) {
  41309. /**
  41310. * "Static Class" containing the most commonly used helper while dealing with material for
  41311. * rendering purpose.
  41312. *
  41313. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41314. *
  41315. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41316. */
  41317. var MaterialHelper = /** @class */ (function () {
  41318. function MaterialHelper() {
  41319. }
  41320. /**
  41321. * Bind the current view position to an effect.
  41322. * @param effect The effect to be bound
  41323. * @param scene The scene the eyes position is used from
  41324. */
  41325. MaterialHelper.BindEyePosition = function (effect, scene) {
  41326. if (scene._forcedViewPosition) {
  41327. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41328. return;
  41329. }
  41330. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41331. };
  41332. /**
  41333. * Helps preparing the defines values about the UVs in used in the effect.
  41334. * UVs are shared as much as we can accross chanels in the shaders.
  41335. * @param texture The texture we are preparing the UVs for
  41336. * @param defines The defines to update
  41337. * @param key The chanel key "diffuse", "specular"... used in the shader
  41338. */
  41339. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41340. defines._needUVs = true;
  41341. defines[key] = true;
  41342. if (texture.getTextureMatrix().isIdentity(true)) {
  41343. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41344. if (texture.coordinatesIndex === 0) {
  41345. defines["MAINUV1"] = true;
  41346. }
  41347. else {
  41348. defines["MAINUV2"] = true;
  41349. }
  41350. }
  41351. else {
  41352. defines[key + "DIRECTUV"] = 0;
  41353. }
  41354. };
  41355. /**
  41356. * Binds a texture matrix value to its corrsponding uniform
  41357. * @param texture The texture to bind the matrix for
  41358. * @param uniformBuffer The uniform buffer receivin the data
  41359. * @param key The chanel key "diffuse", "specular"... used in the shader
  41360. */
  41361. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41362. var matrix = texture.getTextureMatrix();
  41363. if (!matrix.isIdentity(true)) {
  41364. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41365. }
  41366. };
  41367. /**
  41368. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41369. * @param mesh defines the current mesh
  41370. * @param scene defines the current scene
  41371. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41372. * @param pointsCloud defines if point cloud rendering has to be turned on
  41373. * @param fogEnabled defines if fog has to be turned on
  41374. * @param alphaTest defines if alpha testing has to be turned on
  41375. * @param defines defines the current list of defines
  41376. */
  41377. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41378. if (defines._areMiscDirty) {
  41379. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41380. defines["POINTSIZE"] = pointsCloud;
  41381. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41382. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41383. defines["ALPHATEST"] = alphaTest;
  41384. }
  41385. };
  41386. /**
  41387. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41388. * @param scene defines the current scene
  41389. * @param engine defines the current engine
  41390. * @param defines specifies the list of active defines
  41391. * @param useInstances defines if instances have to be turned on
  41392. * @param useClipPlane defines if clip plane have to be turned on
  41393. */
  41394. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41395. if (useClipPlane === void 0) { useClipPlane = null; }
  41396. var changed = false;
  41397. if (useClipPlane == null) {
  41398. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41399. }
  41400. if (defines["CLIPPLANE"] !== useClipPlane) {
  41401. defines["CLIPPLANE"] = useClipPlane;
  41402. changed = true;
  41403. }
  41404. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41405. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41406. changed = true;
  41407. }
  41408. if (defines["INSTANCES"] !== useInstances) {
  41409. defines["INSTANCES"] = useInstances;
  41410. changed = true;
  41411. }
  41412. if (changed) {
  41413. defines.markAsUnprocessed();
  41414. }
  41415. };
  41416. /**
  41417. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41418. * @param mesh The mesh containing the geometry data we will draw
  41419. * @param defines The defines to update
  41420. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41421. * @param useBones Precise whether bones should be used or not (override mesh info)
  41422. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41423. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41424. * @returns false if defines are considered not dirty and have not been checked
  41425. */
  41426. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41427. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41428. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41429. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41430. return false;
  41431. }
  41432. defines._normals = defines._needNormals;
  41433. defines._uvs = defines._needUVs;
  41434. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41435. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41436. defines["TANGENT"] = true;
  41437. }
  41438. if (defines._needUVs) {
  41439. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41440. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41441. }
  41442. else {
  41443. defines["UV1"] = false;
  41444. defines["UV2"] = false;
  41445. }
  41446. if (useVertexColor) {
  41447. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41448. defines["VERTEXCOLOR"] = hasVertexColors;
  41449. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41450. }
  41451. if (useBones) {
  41452. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41453. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41454. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41455. }
  41456. else {
  41457. defines["NUM_BONE_INFLUENCERS"] = 0;
  41458. defines["BonesPerMesh"] = 0;
  41459. }
  41460. }
  41461. if (useMorphTargets) {
  41462. var manager = mesh.morphTargetManager;
  41463. if (manager) {
  41464. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41465. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41466. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41467. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41468. }
  41469. else {
  41470. defines["MORPHTARGETS_TANGENT"] = false;
  41471. defines["MORPHTARGETS_NORMAL"] = false;
  41472. defines["MORPHTARGETS"] = false;
  41473. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41474. }
  41475. }
  41476. return true;
  41477. };
  41478. /**
  41479. * Prepares the defines related to the light information passed in parameter
  41480. * @param scene The scene we are intending to draw
  41481. * @param mesh The mesh the effect is compiling for
  41482. * @param defines The defines to update
  41483. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41484. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41485. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41486. * @returns true if normals will be required for the rest of the effect
  41487. */
  41488. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41489. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41490. if (disableLighting === void 0) { disableLighting = false; }
  41491. if (!defines._areLightsDirty) {
  41492. return defines._needNormals;
  41493. }
  41494. var lightIndex = 0;
  41495. var needNormals = false;
  41496. var needRebuild = false;
  41497. var lightmapMode = false;
  41498. var shadowEnabled = false;
  41499. var specularEnabled = false;
  41500. if (scene.lightsEnabled && !disableLighting) {
  41501. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41502. var light = _a[_i];
  41503. needNormals = true;
  41504. if (defines["LIGHT" + lightIndex] === undefined) {
  41505. needRebuild = true;
  41506. }
  41507. defines["LIGHT" + lightIndex] = true;
  41508. defines["SPOTLIGHT" + lightIndex] = false;
  41509. defines["HEMILIGHT" + lightIndex] = false;
  41510. defines["POINTLIGHT" + lightIndex] = false;
  41511. defines["DIRLIGHT" + lightIndex] = false;
  41512. var type;
  41513. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41514. type = "SPOTLIGHT" + lightIndex;
  41515. var spotLight = light;
  41516. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41517. }
  41518. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41519. type = "HEMILIGHT" + lightIndex;
  41520. }
  41521. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41522. type = "POINTLIGHT" + lightIndex;
  41523. }
  41524. else {
  41525. type = "DIRLIGHT" + lightIndex;
  41526. }
  41527. defines[type] = true;
  41528. // Specular
  41529. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41530. specularEnabled = true;
  41531. }
  41532. // Shadows
  41533. defines["SHADOW" + lightIndex] = false;
  41534. defines["SHADOWPCF" + lightIndex] = false;
  41535. defines["SHADOWPCSS" + lightIndex] = false;
  41536. defines["SHADOWPOISSON" + lightIndex] = false;
  41537. defines["SHADOWESM" + lightIndex] = false;
  41538. defines["SHADOWCUBE" + lightIndex] = false;
  41539. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41540. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41541. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41542. var shadowGenerator = light.getShadowGenerator();
  41543. if (shadowGenerator) {
  41544. shadowEnabled = true;
  41545. shadowGenerator.prepareDefines(defines, lightIndex);
  41546. }
  41547. }
  41548. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41549. lightmapMode = true;
  41550. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41551. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41552. }
  41553. else {
  41554. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41555. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41556. }
  41557. lightIndex++;
  41558. if (lightIndex === maxSimultaneousLights)
  41559. break;
  41560. }
  41561. }
  41562. defines["SPECULARTERM"] = specularEnabled;
  41563. defines["SHADOWS"] = shadowEnabled;
  41564. // Resetting all other lights if any
  41565. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41566. if (defines["LIGHT" + index] !== undefined) {
  41567. defines["LIGHT" + index] = false;
  41568. defines["HEMILIGHT" + lightIndex] = false;
  41569. defines["POINTLIGHT" + lightIndex] = false;
  41570. defines["DIRLIGHT" + lightIndex] = false;
  41571. defines["SPOTLIGHT" + lightIndex] = false;
  41572. defines["SHADOW" + lightIndex] = false;
  41573. }
  41574. }
  41575. var caps = scene.getEngine().getCaps();
  41576. if (defines["SHADOWFLOAT"] === undefined) {
  41577. needRebuild = true;
  41578. }
  41579. defines["SHADOWFLOAT"] = shadowEnabled &&
  41580. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41581. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41582. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41583. if (needRebuild) {
  41584. defines.rebuild();
  41585. }
  41586. return needNormals;
  41587. };
  41588. /**
  41589. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41590. * that won t be acctive due to defines being turned off.
  41591. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41592. * @param samplersList The samplers list
  41593. * @param defines The defines helping in the list generation
  41594. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41595. */
  41596. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41597. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41598. var uniformsList;
  41599. var uniformBuffersList = null;
  41600. if (uniformsListOrOptions.uniformsNames) {
  41601. var options = uniformsListOrOptions;
  41602. uniformsList = options.uniformsNames;
  41603. uniformBuffersList = options.uniformBuffersNames;
  41604. samplersList = options.samplers;
  41605. defines = options.defines;
  41606. maxSimultaneousLights = options.maxSimultaneousLights;
  41607. }
  41608. else {
  41609. uniformsList = uniformsListOrOptions;
  41610. if (!samplersList) {
  41611. samplersList = [];
  41612. }
  41613. }
  41614. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41615. if (!defines["LIGHT" + lightIndex]) {
  41616. break;
  41617. }
  41618. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41619. if (uniformBuffersList) {
  41620. uniformBuffersList.push("Light" + lightIndex);
  41621. }
  41622. samplersList.push("shadowSampler" + lightIndex);
  41623. samplersList.push("depthSampler" + lightIndex);
  41624. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41625. samplersList.push("projectionLightSampler" + lightIndex);
  41626. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41627. }
  41628. }
  41629. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41630. uniformsList.push("morphTargetInfluences");
  41631. }
  41632. };
  41633. /**
  41634. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41635. * @param defines The defines to update while falling back
  41636. * @param fallbacks The authorized effect fallbacks
  41637. * @param maxSimultaneousLights The maximum number of lights allowed
  41638. * @param rank the current rank of the Effect
  41639. * @returns The newly affected rank
  41640. */
  41641. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41642. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41643. if (rank === void 0) { rank = 0; }
  41644. var lightFallbackRank = 0;
  41645. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41646. if (!defines["LIGHT" + lightIndex]) {
  41647. break;
  41648. }
  41649. if (lightIndex > 0) {
  41650. lightFallbackRank = rank + lightIndex;
  41651. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41652. }
  41653. if (!defines["SHADOWS"]) {
  41654. if (defines["SHADOW" + lightIndex]) {
  41655. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41656. }
  41657. if (defines["SHADOWPCF" + lightIndex]) {
  41658. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41659. }
  41660. if (defines["SHADOWPCSS" + lightIndex]) {
  41661. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41662. }
  41663. if (defines["SHADOWPOISSON" + lightIndex]) {
  41664. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41665. }
  41666. if (defines["SHADOWESM" + lightIndex]) {
  41667. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41668. }
  41669. }
  41670. }
  41671. return lightFallbackRank++;
  41672. };
  41673. /**
  41674. * Prepares the list of attributes required for morph targets according to the effect defines.
  41675. * @param attribs The current list of supported attribs
  41676. * @param mesh The mesh to prepare the morph targets attributes for
  41677. * @param defines The current Defines of the effect
  41678. */
  41679. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41680. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41681. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41682. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41683. var manager = mesh.morphTargetManager;
  41684. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41685. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41686. for (var index = 0; index < influencers; index++) {
  41687. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41688. if (normal) {
  41689. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41690. }
  41691. if (tangent) {
  41692. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41693. }
  41694. if (attribs.length > maxAttributesCount) {
  41695. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41696. }
  41697. }
  41698. }
  41699. };
  41700. /**
  41701. * Prepares the list of attributes required for bones according to the effect defines.
  41702. * @param attribs The current list of supported attribs
  41703. * @param mesh The mesh to prepare the bones attributes for
  41704. * @param defines The current Defines of the effect
  41705. * @param fallbacks The current efffect fallback strategy
  41706. */
  41707. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41708. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41709. fallbacks.addCPUSkinningFallback(0, mesh);
  41710. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41711. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41712. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41713. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41714. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41715. }
  41716. }
  41717. };
  41718. /**
  41719. * Prepares the list of attributes required for instances according to the effect defines.
  41720. * @param attribs The current list of supported attribs
  41721. * @param defines The current Defines of the effect
  41722. */
  41723. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41724. if (defines["INSTANCES"]) {
  41725. attribs.push("world0");
  41726. attribs.push("world1");
  41727. attribs.push("world2");
  41728. attribs.push("world3");
  41729. }
  41730. };
  41731. /**
  41732. * Binds the light shadow information to the effect for the given mesh.
  41733. * @param light The light containing the generator
  41734. * @param scene The scene the lights belongs to
  41735. * @param mesh The mesh we are binding the information to render
  41736. * @param lightIndex The light index in the effect used to render the mesh
  41737. * @param effect The effect we are binding the data to
  41738. */
  41739. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41740. if (light.shadowEnabled && mesh.receiveShadows) {
  41741. var shadowGenerator = light.getShadowGenerator();
  41742. if (shadowGenerator) {
  41743. shadowGenerator.bindShadowLight(lightIndex, effect);
  41744. }
  41745. }
  41746. };
  41747. /**
  41748. * Binds the light information to the effect.
  41749. * @param light The light containing the generator
  41750. * @param effect The effect we are binding the data to
  41751. * @param lightIndex The light index in the effect used to render
  41752. */
  41753. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41754. light.transferToEffect(effect, lightIndex + "");
  41755. };
  41756. /**
  41757. * Binds the lights information from the scene to the effect for the given mesh.
  41758. * @param scene The scene the lights belongs to
  41759. * @param mesh The mesh we are binding the information to render
  41760. * @param effect The effect we are binding the data to
  41761. * @param defines The generated defines for the effect
  41762. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41763. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41764. */
  41765. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41766. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41767. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41768. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41769. for (var i = 0; i < len; i++) {
  41770. var light = mesh._lightSources[i];
  41771. var iAsString = i.toString();
  41772. var scaledIntensity = light.getScaledIntensity();
  41773. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41774. MaterialHelper.BindLightProperties(light, effect, i);
  41775. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41776. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41777. if (defines["SPECULARTERM"]) {
  41778. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41779. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41780. }
  41781. // Shadows
  41782. if (scene.shadowsEnabled) {
  41783. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41784. }
  41785. light._uniformBuffer.update();
  41786. }
  41787. };
  41788. /**
  41789. * Binds the fog information from the scene to the effect for the given mesh.
  41790. * @param scene The scene the lights belongs to
  41791. * @param mesh The mesh we are binding the information to render
  41792. * @param effect The effect we are binding the data to
  41793. */
  41794. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41795. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41796. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41797. effect.setColor3("vFogColor", scene.fogColor);
  41798. }
  41799. };
  41800. /**
  41801. * Binds the bones information from the mesh to the effect.
  41802. * @param mesh The mesh we are binding the information to render
  41803. * @param effect The effect we are binding the data to
  41804. */
  41805. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41806. if (!effect || !mesh) {
  41807. return;
  41808. }
  41809. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41810. mesh.computeBonesUsingShaders = false;
  41811. }
  41812. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41813. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41814. if (matrices) {
  41815. effect.setMatrices("mBones", matrices);
  41816. }
  41817. }
  41818. };
  41819. /**
  41820. * Binds the morph targets information from the mesh to the effect.
  41821. * @param abstractMesh The mesh we are binding the information to render
  41822. * @param effect The effect we are binding the data to
  41823. */
  41824. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41825. var manager = abstractMesh.morphTargetManager;
  41826. if (!abstractMesh || !manager) {
  41827. return;
  41828. }
  41829. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41830. };
  41831. /**
  41832. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41833. * @param defines The generated defines used in the effect
  41834. * @param effect The effect we are binding the data to
  41835. * @param scene The scene we are willing to render with logarithmic scale for
  41836. */
  41837. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41838. if (defines["LOGARITHMICDEPTH"]) {
  41839. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41840. }
  41841. };
  41842. /**
  41843. * Binds the clip plane information from the scene to the effect.
  41844. * @param scene The scene the clip plane information are extracted from
  41845. * @param effect The effect we are binding the data to
  41846. */
  41847. MaterialHelper.BindClipPlane = function (effect, scene) {
  41848. if (scene.clipPlane) {
  41849. var clipPlane = scene.clipPlane;
  41850. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41851. }
  41852. };
  41853. return MaterialHelper;
  41854. }());
  41855. BABYLON.MaterialHelper = MaterialHelper;
  41856. })(BABYLON || (BABYLON = {}));
  41857. //# sourceMappingURL=babylon.materialHelper.js.map
  41858. var BABYLON;
  41859. (function (BABYLON) {
  41860. var PushMaterial = /** @class */ (function (_super) {
  41861. __extends(PushMaterial, _super);
  41862. function PushMaterial(name, scene) {
  41863. var _this = _super.call(this, name, scene) || this;
  41864. _this._normalMatrix = new BABYLON.Matrix();
  41865. _this.storeEffectOnSubMeshes = true;
  41866. return _this;
  41867. }
  41868. PushMaterial.prototype.getEffect = function () {
  41869. return this._activeEffect;
  41870. };
  41871. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41872. if (!mesh) {
  41873. return false;
  41874. }
  41875. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41876. return true;
  41877. }
  41878. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41879. };
  41880. /**
  41881. * Binds the given world matrix to the active effect
  41882. *
  41883. * @param world the matrix to bind
  41884. */
  41885. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41886. this._activeEffect.setMatrix("world", world);
  41887. };
  41888. /**
  41889. * Binds the given normal matrix to the active effect
  41890. *
  41891. * @param normalMatrix the matrix to bind
  41892. */
  41893. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41894. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41895. };
  41896. PushMaterial.prototype.bind = function (world, mesh) {
  41897. if (!mesh) {
  41898. return;
  41899. }
  41900. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41901. };
  41902. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41903. if (effect === void 0) { effect = null; }
  41904. _super.prototype._afterBind.call(this, mesh);
  41905. this.getScene()._cachedEffect = effect;
  41906. };
  41907. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41908. if (visibility === void 0) { visibility = 1; }
  41909. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41910. };
  41911. return PushMaterial;
  41912. }(BABYLON.Material));
  41913. BABYLON.PushMaterial = PushMaterial;
  41914. })(BABYLON || (BABYLON = {}));
  41915. //# sourceMappingURL=babylon.pushMaterial.js.map
  41916. var BABYLON;
  41917. (function (BABYLON) {
  41918. /** @hidden */
  41919. var StandardMaterialDefines = /** @class */ (function (_super) {
  41920. __extends(StandardMaterialDefines, _super);
  41921. function StandardMaterialDefines() {
  41922. var _this = _super.call(this) || this;
  41923. _this.MAINUV1 = false;
  41924. _this.MAINUV2 = false;
  41925. _this.DIFFUSE = false;
  41926. _this.DIFFUSEDIRECTUV = 0;
  41927. _this.AMBIENT = false;
  41928. _this.AMBIENTDIRECTUV = 0;
  41929. _this.OPACITY = false;
  41930. _this.OPACITYDIRECTUV = 0;
  41931. _this.OPACITYRGB = false;
  41932. _this.REFLECTION = false;
  41933. _this.EMISSIVE = false;
  41934. _this.EMISSIVEDIRECTUV = 0;
  41935. _this.SPECULAR = false;
  41936. _this.SPECULARDIRECTUV = 0;
  41937. _this.BUMP = false;
  41938. _this.BUMPDIRECTUV = 0;
  41939. _this.PARALLAX = false;
  41940. _this.PARALLAXOCCLUSION = false;
  41941. _this.SPECULAROVERALPHA = false;
  41942. _this.CLIPPLANE = false;
  41943. _this.ALPHATEST = false;
  41944. _this.DEPTHPREPASS = false;
  41945. _this.ALPHAFROMDIFFUSE = false;
  41946. _this.POINTSIZE = false;
  41947. _this.FOG = false;
  41948. _this.SPECULARTERM = false;
  41949. _this.DIFFUSEFRESNEL = false;
  41950. _this.OPACITYFRESNEL = false;
  41951. _this.REFLECTIONFRESNEL = false;
  41952. _this.REFRACTIONFRESNEL = false;
  41953. _this.EMISSIVEFRESNEL = false;
  41954. _this.FRESNEL = false;
  41955. _this.NORMAL = false;
  41956. _this.UV1 = false;
  41957. _this.UV2 = false;
  41958. _this.VERTEXCOLOR = false;
  41959. _this.VERTEXALPHA = false;
  41960. _this.NUM_BONE_INFLUENCERS = 0;
  41961. _this.BonesPerMesh = 0;
  41962. _this.INSTANCES = false;
  41963. _this.GLOSSINESS = false;
  41964. _this.ROUGHNESS = false;
  41965. _this.EMISSIVEASILLUMINATION = false;
  41966. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41967. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41968. _this.LIGHTMAP = false;
  41969. _this.LIGHTMAPDIRECTUV = 0;
  41970. _this.OBJECTSPACE_NORMALMAP = false;
  41971. _this.USELIGHTMAPASSHADOWMAP = false;
  41972. _this.REFLECTIONMAP_3D = false;
  41973. _this.REFLECTIONMAP_SPHERICAL = false;
  41974. _this.REFLECTIONMAP_PLANAR = false;
  41975. _this.REFLECTIONMAP_CUBIC = false;
  41976. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41977. _this.REFLECTIONMAP_PROJECTION = false;
  41978. _this.REFLECTIONMAP_SKYBOX = false;
  41979. _this.REFLECTIONMAP_EXPLICIT = false;
  41980. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41981. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41982. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41983. _this.INVERTCUBICMAP = false;
  41984. _this.LOGARITHMICDEPTH = false;
  41985. _this.REFRACTION = false;
  41986. _this.REFRACTIONMAP_3D = false;
  41987. _this.REFLECTIONOVERALPHA = false;
  41988. _this.TWOSIDEDLIGHTING = false;
  41989. _this.SHADOWFLOAT = false;
  41990. _this.MORPHTARGETS = false;
  41991. _this.MORPHTARGETS_NORMAL = false;
  41992. _this.MORPHTARGETS_TANGENT = false;
  41993. _this.NUM_MORPH_INFLUENCERS = 0;
  41994. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41995. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41996. _this.IMAGEPROCESSING = false;
  41997. _this.VIGNETTE = false;
  41998. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41999. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42000. _this.TONEMAPPING = false;
  42001. _this.CONTRAST = false;
  42002. _this.COLORCURVES = false;
  42003. _this.COLORGRADING = false;
  42004. _this.COLORGRADING3D = false;
  42005. _this.SAMPLER3DGREENDEPTH = false;
  42006. _this.SAMPLER3DBGRMAP = false;
  42007. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42008. /**
  42009. * If the reflection texture on this material is in linear color space
  42010. * @hidden
  42011. */
  42012. _this.IS_REFLECTION_LINEAR = false;
  42013. /**
  42014. * If the refraction texture on this material is in linear color space
  42015. * @hidden
  42016. */
  42017. _this.IS_REFRACTION_LINEAR = false;
  42018. _this.EXPOSURE = false;
  42019. _this.rebuild();
  42020. return _this;
  42021. }
  42022. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42023. var modes = [
  42024. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42025. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42026. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42027. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42028. ];
  42029. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42030. var mode = modes_1[_i];
  42031. this[mode] = (mode === modeToEnable);
  42032. }
  42033. };
  42034. return StandardMaterialDefines;
  42035. }(BABYLON.MaterialDefines));
  42036. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42037. var StandardMaterial = /** @class */ (function (_super) {
  42038. __extends(StandardMaterial, _super);
  42039. function StandardMaterial(name, scene) {
  42040. var _this = _super.call(this, name, scene) || this;
  42041. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42042. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42043. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42044. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42045. _this.specularPower = 64;
  42046. _this._useAlphaFromDiffuseTexture = false;
  42047. _this._useEmissiveAsIllumination = false;
  42048. _this._linkEmissiveWithDiffuse = false;
  42049. _this._useSpecularOverAlpha = false;
  42050. _this._useReflectionOverAlpha = false;
  42051. _this._disableLighting = false;
  42052. _this._useObjectSpaceNormalMap = false;
  42053. _this._useParallax = false;
  42054. _this._useParallaxOcclusion = false;
  42055. _this.parallaxScaleBias = 0.05;
  42056. _this._roughness = 0;
  42057. _this.indexOfRefraction = 0.98;
  42058. _this.invertRefractionY = true;
  42059. /**
  42060. * Defines the alpha limits in alpha test mode
  42061. */
  42062. _this.alphaCutOff = 0.4;
  42063. _this._useLightmapAsShadowmap = false;
  42064. _this._useReflectionFresnelFromSpecular = false;
  42065. _this._useGlossinessFromSpecularMapAlpha = false;
  42066. _this._maxSimultaneousLights = 4;
  42067. /**
  42068. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42069. */
  42070. _this._invertNormalMapX = false;
  42071. /**
  42072. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42073. */
  42074. _this._invertNormalMapY = false;
  42075. /**
  42076. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42077. */
  42078. _this._twoSidedLighting = false;
  42079. _this._renderTargets = new BABYLON.SmartArray(16);
  42080. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42081. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42082. // Setup the default processing configuration to the scene.
  42083. _this._attachImageProcessingConfiguration(null);
  42084. _this.getRenderTargetTextures = function () {
  42085. _this._renderTargets.reset();
  42086. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42087. _this._renderTargets.push(_this._reflectionTexture);
  42088. }
  42089. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42090. _this._renderTargets.push(_this._refractionTexture);
  42091. }
  42092. return _this._renderTargets;
  42093. };
  42094. return _this;
  42095. }
  42096. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42097. /**
  42098. * Gets the image processing configuration used either in this material.
  42099. */
  42100. get: function () {
  42101. return this._imageProcessingConfiguration;
  42102. },
  42103. /**
  42104. * Sets the Default image processing configuration used either in the this material.
  42105. *
  42106. * If sets to null, the scene one is in use.
  42107. */
  42108. set: function (value) {
  42109. this._attachImageProcessingConfiguration(value);
  42110. // Ensure the effect will be rebuilt.
  42111. this._markAllSubMeshesAsTexturesDirty();
  42112. },
  42113. enumerable: true,
  42114. configurable: true
  42115. });
  42116. /**
  42117. * Attaches a new image processing configuration to the Standard Material.
  42118. * @param configuration
  42119. */
  42120. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42121. var _this = this;
  42122. if (configuration === this._imageProcessingConfiguration) {
  42123. return;
  42124. }
  42125. // Detaches observer.
  42126. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42127. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42128. }
  42129. // Pick the scene configuration if needed.
  42130. if (!configuration) {
  42131. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42132. }
  42133. else {
  42134. this._imageProcessingConfiguration = configuration;
  42135. }
  42136. // Attaches observer.
  42137. if (this._imageProcessingConfiguration) {
  42138. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42139. _this._markAllSubMeshesAsImageProcessingDirty();
  42140. });
  42141. }
  42142. };
  42143. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42144. /**
  42145. * Gets wether the color curves effect is enabled.
  42146. */
  42147. get: function () {
  42148. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42149. },
  42150. /**
  42151. * Sets wether the color curves effect is enabled.
  42152. */
  42153. set: function (value) {
  42154. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42155. },
  42156. enumerable: true,
  42157. configurable: true
  42158. });
  42159. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42160. /**
  42161. * Gets wether the color grading effect is enabled.
  42162. */
  42163. get: function () {
  42164. return this.imageProcessingConfiguration.colorGradingEnabled;
  42165. },
  42166. /**
  42167. * Gets wether the color grading effect is enabled.
  42168. */
  42169. set: function (value) {
  42170. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42171. },
  42172. enumerable: true,
  42173. configurable: true
  42174. });
  42175. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42176. /**
  42177. * Gets wether tonemapping is enabled or not.
  42178. */
  42179. get: function () {
  42180. return this._imageProcessingConfiguration.toneMappingEnabled;
  42181. },
  42182. /**
  42183. * Sets wether tonemapping is enabled or not
  42184. */
  42185. set: function (value) {
  42186. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42187. },
  42188. enumerable: true,
  42189. configurable: true
  42190. });
  42191. ;
  42192. ;
  42193. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42194. /**
  42195. * The camera exposure used on this material.
  42196. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42197. * This corresponds to a photographic exposure.
  42198. */
  42199. get: function () {
  42200. return this._imageProcessingConfiguration.exposure;
  42201. },
  42202. /**
  42203. * The camera exposure used on this material.
  42204. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42205. * This corresponds to a photographic exposure.
  42206. */
  42207. set: function (value) {
  42208. this._imageProcessingConfiguration.exposure = value;
  42209. },
  42210. enumerable: true,
  42211. configurable: true
  42212. });
  42213. ;
  42214. ;
  42215. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42216. /**
  42217. * Gets The camera contrast used on this material.
  42218. */
  42219. get: function () {
  42220. return this._imageProcessingConfiguration.contrast;
  42221. },
  42222. /**
  42223. * Sets The camera contrast used on this material.
  42224. */
  42225. set: function (value) {
  42226. this._imageProcessingConfiguration.contrast = value;
  42227. },
  42228. enumerable: true,
  42229. configurable: true
  42230. });
  42231. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42232. /**
  42233. * Gets the Color Grading 2D Lookup Texture.
  42234. */
  42235. get: function () {
  42236. return this._imageProcessingConfiguration.colorGradingTexture;
  42237. },
  42238. /**
  42239. * Sets the Color Grading 2D Lookup Texture.
  42240. */
  42241. set: function (value) {
  42242. this._imageProcessingConfiguration.colorGradingTexture = value;
  42243. },
  42244. enumerable: true,
  42245. configurable: true
  42246. });
  42247. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42248. /**
  42249. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42250. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42251. * 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;
  42252. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42253. */
  42254. get: function () {
  42255. return this._imageProcessingConfiguration.colorCurves;
  42256. },
  42257. /**
  42258. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42259. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42260. * 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;
  42261. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42262. */
  42263. set: function (value) {
  42264. this._imageProcessingConfiguration.colorCurves = value;
  42265. },
  42266. enumerable: true,
  42267. configurable: true
  42268. });
  42269. StandardMaterial.prototype.getClassName = function () {
  42270. return "StandardMaterial";
  42271. };
  42272. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42273. get: function () {
  42274. return this._useLogarithmicDepth;
  42275. },
  42276. set: function (value) {
  42277. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42278. this._markAllSubMeshesAsMiscDirty();
  42279. },
  42280. enumerable: true,
  42281. configurable: true
  42282. });
  42283. StandardMaterial.prototype.needAlphaBlending = function () {
  42284. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42285. };
  42286. StandardMaterial.prototype.needAlphaTesting = function () {
  42287. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42288. };
  42289. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42290. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42291. };
  42292. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42293. return this._diffuseTexture;
  42294. };
  42295. /**
  42296. * Child classes can use it to update shaders
  42297. */
  42298. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42299. if (useInstances === void 0) { useInstances = false; }
  42300. if (subMesh.effect && this.isFrozen) {
  42301. if (this._wasPreviouslyReady && subMesh.effect) {
  42302. return true;
  42303. }
  42304. }
  42305. if (!subMesh._materialDefines) {
  42306. subMesh._materialDefines = new StandardMaterialDefines();
  42307. }
  42308. var scene = this.getScene();
  42309. var defines = subMesh._materialDefines;
  42310. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42311. if (defines._renderId === scene.getRenderId()) {
  42312. return true;
  42313. }
  42314. }
  42315. var engine = scene.getEngine();
  42316. // Lights
  42317. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42318. // Textures
  42319. if (defines._areTexturesDirty) {
  42320. defines._needUVs = false;
  42321. defines.MAINUV1 = false;
  42322. defines.MAINUV2 = false;
  42323. if (scene.texturesEnabled) {
  42324. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42325. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42326. return false;
  42327. }
  42328. else {
  42329. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42330. }
  42331. }
  42332. else {
  42333. defines.DIFFUSE = false;
  42334. }
  42335. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42336. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42337. return false;
  42338. }
  42339. else {
  42340. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42341. }
  42342. }
  42343. else {
  42344. defines.AMBIENT = false;
  42345. }
  42346. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42347. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42348. return false;
  42349. }
  42350. else {
  42351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42352. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42353. }
  42354. }
  42355. else {
  42356. defines.OPACITY = false;
  42357. }
  42358. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42359. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42360. return false;
  42361. }
  42362. else {
  42363. defines._needNormals = true;
  42364. defines.REFLECTION = true;
  42365. defines.ROUGHNESS = (this._roughness > 0);
  42366. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42367. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42368. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42369. switch (this._reflectionTexture.coordinatesMode) {
  42370. case BABYLON.Texture.EXPLICIT_MODE:
  42371. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42372. break;
  42373. case BABYLON.Texture.PLANAR_MODE:
  42374. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42375. break;
  42376. case BABYLON.Texture.PROJECTION_MODE:
  42377. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42378. break;
  42379. case BABYLON.Texture.SKYBOX_MODE:
  42380. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42381. break;
  42382. case BABYLON.Texture.SPHERICAL_MODE:
  42383. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42384. break;
  42385. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42386. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42387. break;
  42388. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42389. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42390. break;
  42391. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42392. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42393. break;
  42394. case BABYLON.Texture.CUBIC_MODE:
  42395. case BABYLON.Texture.INVCUBIC_MODE:
  42396. default:
  42397. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42398. break;
  42399. }
  42400. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42401. }
  42402. }
  42403. else {
  42404. defines.REFLECTION = false;
  42405. }
  42406. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42407. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42408. return false;
  42409. }
  42410. else {
  42411. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42412. }
  42413. }
  42414. else {
  42415. defines.EMISSIVE = false;
  42416. }
  42417. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42418. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42419. return false;
  42420. }
  42421. else {
  42422. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42423. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42424. }
  42425. }
  42426. else {
  42427. defines.LIGHTMAP = false;
  42428. }
  42429. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42430. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42431. return false;
  42432. }
  42433. else {
  42434. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42435. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42436. }
  42437. }
  42438. else {
  42439. defines.SPECULAR = false;
  42440. }
  42441. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42442. // Bump texure can not be not blocking.
  42443. if (!this._bumpTexture.isReady()) {
  42444. return false;
  42445. }
  42446. else {
  42447. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42448. defines.PARALLAX = this._useParallax;
  42449. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42450. }
  42451. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42452. }
  42453. else {
  42454. defines.BUMP = false;
  42455. }
  42456. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42457. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42458. return false;
  42459. }
  42460. else {
  42461. defines._needUVs = true;
  42462. defines.REFRACTION = true;
  42463. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42464. }
  42465. }
  42466. else {
  42467. defines.REFRACTION = false;
  42468. }
  42469. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42470. }
  42471. else {
  42472. defines.DIFFUSE = false;
  42473. defines.AMBIENT = false;
  42474. defines.OPACITY = false;
  42475. defines.REFLECTION = false;
  42476. defines.EMISSIVE = false;
  42477. defines.LIGHTMAP = false;
  42478. defines.BUMP = false;
  42479. defines.REFRACTION = false;
  42480. }
  42481. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42482. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42483. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42484. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42485. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42486. }
  42487. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42488. if (!this._imageProcessingConfiguration.isReady()) {
  42489. return false;
  42490. }
  42491. this._imageProcessingConfiguration.prepareDefines(defines);
  42492. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42493. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42494. }
  42495. if (defines._areFresnelDirty) {
  42496. if (StandardMaterial.FresnelEnabled) {
  42497. // Fresnel
  42498. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42499. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42500. this._reflectionFresnelParameters) {
  42501. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42502. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42503. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42504. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42505. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42506. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42507. defines._needNormals = true;
  42508. defines.FRESNEL = true;
  42509. }
  42510. }
  42511. else {
  42512. defines.FRESNEL = false;
  42513. }
  42514. }
  42515. // Misc.
  42516. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42517. // Attribs
  42518. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42519. // Values that need to be evaluated on every frame
  42520. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42521. // Get correct effect
  42522. if (defines.isDirty) {
  42523. defines.markAsProcessed();
  42524. scene.resetCachedMaterial();
  42525. // Fallbacks
  42526. var fallbacks = new BABYLON.EffectFallbacks();
  42527. if (defines.REFLECTION) {
  42528. fallbacks.addFallback(0, "REFLECTION");
  42529. }
  42530. if (defines.SPECULAR) {
  42531. fallbacks.addFallback(0, "SPECULAR");
  42532. }
  42533. if (defines.BUMP) {
  42534. fallbacks.addFallback(0, "BUMP");
  42535. }
  42536. if (defines.PARALLAX) {
  42537. fallbacks.addFallback(1, "PARALLAX");
  42538. }
  42539. if (defines.PARALLAXOCCLUSION) {
  42540. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42541. }
  42542. if (defines.SPECULAROVERALPHA) {
  42543. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42544. }
  42545. if (defines.FOG) {
  42546. fallbacks.addFallback(1, "FOG");
  42547. }
  42548. if (defines.POINTSIZE) {
  42549. fallbacks.addFallback(0, "POINTSIZE");
  42550. }
  42551. if (defines.LOGARITHMICDEPTH) {
  42552. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42553. }
  42554. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42555. if (defines.SPECULARTERM) {
  42556. fallbacks.addFallback(0, "SPECULARTERM");
  42557. }
  42558. if (defines.DIFFUSEFRESNEL) {
  42559. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42560. }
  42561. if (defines.OPACITYFRESNEL) {
  42562. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42563. }
  42564. if (defines.REFLECTIONFRESNEL) {
  42565. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42566. }
  42567. if (defines.EMISSIVEFRESNEL) {
  42568. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42569. }
  42570. if (defines.FRESNEL) {
  42571. fallbacks.addFallback(4, "FRESNEL");
  42572. }
  42573. //Attributes
  42574. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42575. if (defines.NORMAL) {
  42576. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42577. }
  42578. if (defines.UV1) {
  42579. attribs.push(BABYLON.VertexBuffer.UVKind);
  42580. }
  42581. if (defines.UV2) {
  42582. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42583. }
  42584. if (defines.VERTEXCOLOR) {
  42585. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42586. }
  42587. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42588. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42589. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42590. var shaderName = "default";
  42591. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42592. "vFogInfos", "vFogColor", "pointSize",
  42593. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42594. "mBones",
  42595. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42596. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42597. "vReflectionPosition", "vReflectionSize",
  42598. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42599. ];
  42600. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42601. var uniformBuffers = ["Material", "Scene"];
  42602. if (BABYLON.ImageProcessingConfiguration) {
  42603. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42604. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42605. }
  42606. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42607. uniformsNames: uniforms,
  42608. uniformBuffersNames: uniformBuffers,
  42609. samplers: samplers,
  42610. defines: defines,
  42611. maxSimultaneousLights: this._maxSimultaneousLights
  42612. });
  42613. if (this.customShaderNameResolve) {
  42614. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42615. }
  42616. var join = defines.toString();
  42617. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42618. attributes: attribs,
  42619. uniformsNames: uniforms,
  42620. uniformBuffersNames: uniformBuffers,
  42621. samplers: samplers,
  42622. defines: join,
  42623. fallbacks: fallbacks,
  42624. onCompiled: this.onCompiled,
  42625. onError: this.onError,
  42626. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42627. }, engine), defines);
  42628. this.buildUniformLayout();
  42629. }
  42630. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42631. return false;
  42632. }
  42633. defines._renderId = scene.getRenderId();
  42634. this._wasPreviouslyReady = true;
  42635. return true;
  42636. };
  42637. StandardMaterial.prototype.buildUniformLayout = function () {
  42638. // Order is important !
  42639. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42640. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42641. this._uniformBuffer.addUniform("opacityParts", 4);
  42642. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42643. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42644. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42645. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42646. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42647. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42648. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42649. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42650. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42651. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42652. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42653. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42654. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42655. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42656. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42657. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42658. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42659. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42660. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42661. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42662. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42663. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42664. this._uniformBuffer.addUniform("specularMatrix", 16);
  42665. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42666. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42667. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42668. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42669. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42670. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42671. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42672. this._uniformBuffer.addUniform("pointSize", 1);
  42673. this._uniformBuffer.create();
  42674. };
  42675. StandardMaterial.prototype.unbind = function () {
  42676. if (this._activeEffect) {
  42677. var needFlag = false;
  42678. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42679. this._activeEffect.setTexture("reflection2DSampler", null);
  42680. needFlag = true;
  42681. }
  42682. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42683. this._activeEffect.setTexture("refraction2DSampler", null);
  42684. needFlag = true;
  42685. }
  42686. if (needFlag) {
  42687. this._markAllSubMeshesAsTexturesDirty();
  42688. }
  42689. }
  42690. _super.prototype.unbind.call(this);
  42691. };
  42692. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42693. var scene = this.getScene();
  42694. var defines = subMesh._materialDefines;
  42695. if (!defines) {
  42696. return;
  42697. }
  42698. var effect = subMesh.effect;
  42699. if (!effect) {
  42700. return;
  42701. }
  42702. this._activeEffect = effect;
  42703. // Matrices
  42704. this.bindOnlyWorldMatrix(world);
  42705. // Normal Matrix
  42706. if (defines.OBJECTSPACE_NORMALMAP) {
  42707. world.toNormalMatrix(this._normalMatrix);
  42708. this.bindOnlyNormalMatrix(this._normalMatrix);
  42709. }
  42710. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42711. // Bones
  42712. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42713. if (mustRebind) {
  42714. this._uniformBuffer.bindToEffect(effect, "Material");
  42715. this.bindViewProjection(effect);
  42716. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42717. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42718. // Fresnel
  42719. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42720. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42721. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42722. }
  42723. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42724. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42725. }
  42726. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42727. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42728. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42729. }
  42730. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42731. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42732. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42733. }
  42734. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42735. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42736. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42737. }
  42738. }
  42739. // Textures
  42740. if (scene.texturesEnabled) {
  42741. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42742. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42743. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42744. if (this._diffuseTexture.hasAlpha) {
  42745. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42746. }
  42747. }
  42748. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42749. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42750. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42751. }
  42752. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42753. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42754. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42755. }
  42756. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42757. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42758. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42759. if (this._reflectionTexture.boundingBoxSize) {
  42760. var cubeTexture = this._reflectionTexture;
  42761. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42762. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42763. }
  42764. }
  42765. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42766. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42767. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42768. }
  42769. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42770. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42771. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42772. }
  42773. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42774. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42775. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42776. }
  42777. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42778. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42779. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42780. if (scene._mirroredCameraPosition) {
  42781. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42782. }
  42783. else {
  42784. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42785. }
  42786. }
  42787. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42788. var depth = 1.0;
  42789. if (!this._refractionTexture.isCube) {
  42790. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42791. if (this._refractionTexture.depth) {
  42792. depth = this._refractionTexture.depth;
  42793. }
  42794. }
  42795. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42796. }
  42797. }
  42798. // Point size
  42799. if (this.pointsCloud) {
  42800. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42801. }
  42802. if (defines.SPECULARTERM) {
  42803. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42804. }
  42805. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42806. // Diffuse
  42807. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42808. }
  42809. // Textures
  42810. if (scene.texturesEnabled) {
  42811. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42812. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42813. }
  42814. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42815. effect.setTexture("ambientSampler", this._ambientTexture);
  42816. }
  42817. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42818. effect.setTexture("opacitySampler", this._opacityTexture);
  42819. }
  42820. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42821. if (this._reflectionTexture.isCube) {
  42822. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42823. }
  42824. else {
  42825. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42826. }
  42827. }
  42828. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42829. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42830. }
  42831. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42832. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42833. }
  42834. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42835. effect.setTexture("specularSampler", this._specularTexture);
  42836. }
  42837. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42838. effect.setTexture("bumpSampler", this._bumpTexture);
  42839. }
  42840. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42841. var depth = 1.0;
  42842. if (this._refractionTexture.isCube) {
  42843. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42844. }
  42845. else {
  42846. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42847. }
  42848. }
  42849. }
  42850. // Clip plane
  42851. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42852. // Colors
  42853. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42854. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42855. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42856. }
  42857. if (mustRebind || !this.isFrozen) {
  42858. // Lights
  42859. if (scene.lightsEnabled && !this._disableLighting) {
  42860. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42861. }
  42862. // View
  42863. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42864. this.bindView(effect);
  42865. }
  42866. // Fog
  42867. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42868. // Morph targets
  42869. if (defines.NUM_MORPH_INFLUENCERS) {
  42870. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42871. }
  42872. // Log. depth
  42873. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42874. // image processing
  42875. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42876. this._imageProcessingConfiguration.bind(this._activeEffect);
  42877. }
  42878. }
  42879. this._uniformBuffer.update();
  42880. this._afterBind(mesh, this._activeEffect);
  42881. };
  42882. StandardMaterial.prototype.getAnimatables = function () {
  42883. var results = [];
  42884. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42885. results.push(this._diffuseTexture);
  42886. }
  42887. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42888. results.push(this._ambientTexture);
  42889. }
  42890. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42891. results.push(this._opacityTexture);
  42892. }
  42893. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42894. results.push(this._reflectionTexture);
  42895. }
  42896. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42897. results.push(this._emissiveTexture);
  42898. }
  42899. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42900. results.push(this._specularTexture);
  42901. }
  42902. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42903. results.push(this._bumpTexture);
  42904. }
  42905. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42906. results.push(this._lightmapTexture);
  42907. }
  42908. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42909. results.push(this._refractionTexture);
  42910. }
  42911. return results;
  42912. };
  42913. StandardMaterial.prototype.getActiveTextures = function () {
  42914. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42915. if (this._diffuseTexture) {
  42916. activeTextures.push(this._diffuseTexture);
  42917. }
  42918. if (this._ambientTexture) {
  42919. activeTextures.push(this._ambientTexture);
  42920. }
  42921. if (this._opacityTexture) {
  42922. activeTextures.push(this._opacityTexture);
  42923. }
  42924. if (this._reflectionTexture) {
  42925. activeTextures.push(this._reflectionTexture);
  42926. }
  42927. if (this._emissiveTexture) {
  42928. activeTextures.push(this._emissiveTexture);
  42929. }
  42930. if (this._specularTexture) {
  42931. activeTextures.push(this._specularTexture);
  42932. }
  42933. if (this._bumpTexture) {
  42934. activeTextures.push(this._bumpTexture);
  42935. }
  42936. if (this._lightmapTexture) {
  42937. activeTextures.push(this._lightmapTexture);
  42938. }
  42939. if (this._refractionTexture) {
  42940. activeTextures.push(this._refractionTexture);
  42941. }
  42942. return activeTextures;
  42943. };
  42944. StandardMaterial.prototype.hasTexture = function (texture) {
  42945. if (_super.prototype.hasTexture.call(this, texture)) {
  42946. return true;
  42947. }
  42948. if (this._diffuseTexture === texture) {
  42949. return true;
  42950. }
  42951. if (this._ambientTexture === texture) {
  42952. return true;
  42953. }
  42954. if (this._opacityTexture === texture) {
  42955. return true;
  42956. }
  42957. if (this._reflectionTexture === texture) {
  42958. return true;
  42959. }
  42960. if (this._emissiveTexture === texture) {
  42961. return true;
  42962. }
  42963. if (this._specularTexture === texture) {
  42964. return true;
  42965. }
  42966. if (this._bumpTexture === texture) {
  42967. return true;
  42968. }
  42969. if (this._lightmapTexture === texture) {
  42970. return true;
  42971. }
  42972. if (this._refractionTexture === texture) {
  42973. return true;
  42974. }
  42975. return false;
  42976. };
  42977. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42978. if (forceDisposeTextures) {
  42979. if (this._diffuseTexture) {
  42980. this._diffuseTexture.dispose();
  42981. }
  42982. if (this._ambientTexture) {
  42983. this._ambientTexture.dispose();
  42984. }
  42985. if (this._opacityTexture) {
  42986. this._opacityTexture.dispose();
  42987. }
  42988. if (this._reflectionTexture) {
  42989. this._reflectionTexture.dispose();
  42990. }
  42991. if (this._emissiveTexture) {
  42992. this._emissiveTexture.dispose();
  42993. }
  42994. if (this._specularTexture) {
  42995. this._specularTexture.dispose();
  42996. }
  42997. if (this._bumpTexture) {
  42998. this._bumpTexture.dispose();
  42999. }
  43000. if (this._lightmapTexture) {
  43001. this._lightmapTexture.dispose();
  43002. }
  43003. if (this._refractionTexture) {
  43004. this._refractionTexture.dispose();
  43005. }
  43006. }
  43007. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43008. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43009. }
  43010. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43011. };
  43012. StandardMaterial.prototype.clone = function (name) {
  43013. var _this = this;
  43014. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43015. result.name = name;
  43016. result.id = name;
  43017. return result;
  43018. };
  43019. StandardMaterial.prototype.serialize = function () {
  43020. return BABYLON.SerializationHelper.Serialize(this);
  43021. };
  43022. // Statics
  43023. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43024. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43025. };
  43026. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43027. get: function () {
  43028. return StandardMaterial._DiffuseTextureEnabled;
  43029. },
  43030. set: function (value) {
  43031. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43032. return;
  43033. }
  43034. StandardMaterial._DiffuseTextureEnabled = value;
  43035. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43036. },
  43037. enumerable: true,
  43038. configurable: true
  43039. });
  43040. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43041. get: function () {
  43042. return StandardMaterial._AmbientTextureEnabled;
  43043. },
  43044. set: function (value) {
  43045. if (StandardMaterial._AmbientTextureEnabled === value) {
  43046. return;
  43047. }
  43048. StandardMaterial._AmbientTextureEnabled = value;
  43049. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43050. },
  43051. enumerable: true,
  43052. configurable: true
  43053. });
  43054. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43055. get: function () {
  43056. return StandardMaterial._OpacityTextureEnabled;
  43057. },
  43058. set: function (value) {
  43059. if (StandardMaterial._OpacityTextureEnabled === value) {
  43060. return;
  43061. }
  43062. StandardMaterial._OpacityTextureEnabled = value;
  43063. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43064. },
  43065. enumerable: true,
  43066. configurable: true
  43067. });
  43068. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43069. get: function () {
  43070. return StandardMaterial._ReflectionTextureEnabled;
  43071. },
  43072. set: function (value) {
  43073. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43074. return;
  43075. }
  43076. StandardMaterial._ReflectionTextureEnabled = value;
  43077. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43078. },
  43079. enumerable: true,
  43080. configurable: true
  43081. });
  43082. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43083. get: function () {
  43084. return StandardMaterial._EmissiveTextureEnabled;
  43085. },
  43086. set: function (value) {
  43087. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43088. return;
  43089. }
  43090. StandardMaterial._EmissiveTextureEnabled = value;
  43091. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43092. },
  43093. enumerable: true,
  43094. configurable: true
  43095. });
  43096. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43097. get: function () {
  43098. return StandardMaterial._SpecularTextureEnabled;
  43099. },
  43100. set: function (value) {
  43101. if (StandardMaterial._SpecularTextureEnabled === value) {
  43102. return;
  43103. }
  43104. StandardMaterial._SpecularTextureEnabled = value;
  43105. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43106. },
  43107. enumerable: true,
  43108. configurable: true
  43109. });
  43110. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43111. get: function () {
  43112. return StandardMaterial._BumpTextureEnabled;
  43113. },
  43114. set: function (value) {
  43115. if (StandardMaterial._BumpTextureEnabled === value) {
  43116. return;
  43117. }
  43118. StandardMaterial._BumpTextureEnabled = value;
  43119. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43120. },
  43121. enumerable: true,
  43122. configurable: true
  43123. });
  43124. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43125. get: function () {
  43126. return StandardMaterial._LightmapTextureEnabled;
  43127. },
  43128. set: function (value) {
  43129. if (StandardMaterial._LightmapTextureEnabled === value) {
  43130. return;
  43131. }
  43132. StandardMaterial._LightmapTextureEnabled = value;
  43133. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43134. },
  43135. enumerable: true,
  43136. configurable: true
  43137. });
  43138. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43139. get: function () {
  43140. return StandardMaterial._RefractionTextureEnabled;
  43141. },
  43142. set: function (value) {
  43143. if (StandardMaterial._RefractionTextureEnabled === value) {
  43144. return;
  43145. }
  43146. StandardMaterial._RefractionTextureEnabled = value;
  43147. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43148. },
  43149. enumerable: true,
  43150. configurable: true
  43151. });
  43152. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43153. get: function () {
  43154. return StandardMaterial._ColorGradingTextureEnabled;
  43155. },
  43156. set: function (value) {
  43157. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43158. return;
  43159. }
  43160. StandardMaterial._ColorGradingTextureEnabled = value;
  43161. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43162. },
  43163. enumerable: true,
  43164. configurable: true
  43165. });
  43166. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43167. get: function () {
  43168. return StandardMaterial._FresnelEnabled;
  43169. },
  43170. set: function (value) {
  43171. if (StandardMaterial._FresnelEnabled === value) {
  43172. return;
  43173. }
  43174. StandardMaterial._FresnelEnabled = value;
  43175. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43176. },
  43177. enumerable: true,
  43178. configurable: true
  43179. });
  43180. // Flags used to enable or disable a type of texture for all Standard Materials
  43181. StandardMaterial._DiffuseTextureEnabled = true;
  43182. StandardMaterial._AmbientTextureEnabled = true;
  43183. StandardMaterial._OpacityTextureEnabled = true;
  43184. StandardMaterial._ReflectionTextureEnabled = true;
  43185. StandardMaterial._EmissiveTextureEnabled = true;
  43186. StandardMaterial._SpecularTextureEnabled = true;
  43187. StandardMaterial._BumpTextureEnabled = true;
  43188. StandardMaterial._LightmapTextureEnabled = true;
  43189. StandardMaterial._RefractionTextureEnabled = true;
  43190. StandardMaterial._ColorGradingTextureEnabled = true;
  43191. StandardMaterial._FresnelEnabled = true;
  43192. __decorate([
  43193. BABYLON.serializeAsTexture("diffuseTexture")
  43194. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43195. __decorate([
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43197. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43198. __decorate([
  43199. BABYLON.serializeAsTexture("ambientTexture")
  43200. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43201. __decorate([
  43202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43203. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43204. __decorate([
  43205. BABYLON.serializeAsTexture("opacityTexture")
  43206. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43207. __decorate([
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43209. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43210. __decorate([
  43211. BABYLON.serializeAsTexture("reflectionTexture")
  43212. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43213. __decorate([
  43214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43215. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43216. __decorate([
  43217. BABYLON.serializeAsTexture("emissiveTexture")
  43218. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43219. __decorate([
  43220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43221. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43222. __decorate([
  43223. BABYLON.serializeAsTexture("specularTexture")
  43224. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43225. __decorate([
  43226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43227. ], StandardMaterial.prototype, "specularTexture", void 0);
  43228. __decorate([
  43229. BABYLON.serializeAsTexture("bumpTexture")
  43230. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43231. __decorate([
  43232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43233. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43234. __decorate([
  43235. BABYLON.serializeAsTexture("lightmapTexture")
  43236. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43237. __decorate([
  43238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43239. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43240. __decorate([
  43241. BABYLON.serializeAsTexture("refractionTexture")
  43242. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43243. __decorate([
  43244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43245. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43246. __decorate([
  43247. BABYLON.serializeAsColor3("ambient")
  43248. ], StandardMaterial.prototype, "ambientColor", void 0);
  43249. __decorate([
  43250. BABYLON.serializeAsColor3("diffuse")
  43251. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43252. __decorate([
  43253. BABYLON.serializeAsColor3("specular")
  43254. ], StandardMaterial.prototype, "specularColor", void 0);
  43255. __decorate([
  43256. BABYLON.serializeAsColor3("emissive")
  43257. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43258. __decorate([
  43259. BABYLON.serialize()
  43260. ], StandardMaterial.prototype, "specularPower", void 0);
  43261. __decorate([
  43262. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43263. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43264. __decorate([
  43265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43266. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43267. __decorate([
  43268. BABYLON.serialize("useEmissiveAsIllumination")
  43269. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43270. __decorate([
  43271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43272. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43273. __decorate([
  43274. BABYLON.serialize("linkEmissiveWithDiffuse")
  43275. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43276. __decorate([
  43277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43278. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43279. __decorate([
  43280. BABYLON.serialize("useSpecularOverAlpha")
  43281. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43282. __decorate([
  43283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43284. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43285. __decorate([
  43286. BABYLON.serialize("useReflectionOverAlpha")
  43287. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43288. __decorate([
  43289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43290. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43291. __decorate([
  43292. BABYLON.serialize("disableLighting")
  43293. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43294. __decorate([
  43295. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43296. ], StandardMaterial.prototype, "disableLighting", void 0);
  43297. __decorate([
  43298. BABYLON.serialize("useObjectSpaceNormalMap")
  43299. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43300. __decorate([
  43301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43302. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43303. __decorate([
  43304. BABYLON.serialize("useParallax")
  43305. ], StandardMaterial.prototype, "_useParallax", void 0);
  43306. __decorate([
  43307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43308. ], StandardMaterial.prototype, "useParallax", void 0);
  43309. __decorate([
  43310. BABYLON.serialize("useParallaxOcclusion")
  43311. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43312. __decorate([
  43313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43314. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43315. __decorate([
  43316. BABYLON.serialize()
  43317. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43318. __decorate([
  43319. BABYLON.serialize("roughness")
  43320. ], StandardMaterial.prototype, "_roughness", void 0);
  43321. __decorate([
  43322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43323. ], StandardMaterial.prototype, "roughness", void 0);
  43324. __decorate([
  43325. BABYLON.serialize()
  43326. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43327. __decorate([
  43328. BABYLON.serialize()
  43329. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43330. __decorate([
  43331. BABYLON.serialize()
  43332. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43333. __decorate([
  43334. BABYLON.serialize("useLightmapAsShadowmap")
  43335. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43336. __decorate([
  43337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43338. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43339. __decorate([
  43340. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43341. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43342. __decorate([
  43343. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43344. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43345. __decorate([
  43346. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43347. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43348. __decorate([
  43349. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43350. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43351. __decorate([
  43352. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43353. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43354. __decorate([
  43355. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43356. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43357. __decorate([
  43358. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43359. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43360. __decorate([
  43361. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43362. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43363. __decorate([
  43364. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43365. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43366. __decorate([
  43367. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43368. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43369. __decorate([
  43370. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43371. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43372. __decorate([
  43373. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43374. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43375. __decorate([
  43376. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43377. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43378. __decorate([
  43379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43380. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43381. __decorate([
  43382. BABYLON.serialize("maxSimultaneousLights")
  43383. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43384. __decorate([
  43385. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43386. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43387. __decorate([
  43388. BABYLON.serialize("invertNormalMapX")
  43389. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43390. __decorate([
  43391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43392. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43393. __decorate([
  43394. BABYLON.serialize("invertNormalMapY")
  43395. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43396. __decorate([
  43397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43398. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43399. __decorate([
  43400. BABYLON.serialize("twoSidedLighting")
  43401. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43402. __decorate([
  43403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43404. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43405. __decorate([
  43406. BABYLON.serialize()
  43407. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43408. return StandardMaterial;
  43409. }(BABYLON.PushMaterial));
  43410. BABYLON.StandardMaterial = StandardMaterial;
  43411. })(BABYLON || (BABYLON = {}));
  43412. //# sourceMappingURL=babylon.standardMaterial.js.map
  43413. var BABYLON;
  43414. (function (BABYLON) {
  43415. /**
  43416. * Manages the defines for the PBR Material.
  43417. * @hiddenChildren
  43418. */
  43419. var PBRMaterialDefines = /** @class */ (function (_super) {
  43420. __extends(PBRMaterialDefines, _super);
  43421. /**
  43422. * Initializes the PBR Material defines.
  43423. */
  43424. function PBRMaterialDefines() {
  43425. var _this = _super.call(this) || this;
  43426. _this.PBR = true;
  43427. _this.MAINUV1 = false;
  43428. _this.MAINUV2 = false;
  43429. _this.UV1 = false;
  43430. _this.UV2 = false;
  43431. _this.ALBEDO = false;
  43432. _this.ALBEDODIRECTUV = 0;
  43433. _this.VERTEXCOLOR = false;
  43434. _this.AMBIENT = false;
  43435. _this.AMBIENTDIRECTUV = 0;
  43436. _this.AMBIENTINGRAYSCALE = false;
  43437. _this.OPACITY = false;
  43438. _this.VERTEXALPHA = false;
  43439. _this.OPACITYDIRECTUV = 0;
  43440. _this.OPACITYRGB = false;
  43441. _this.ALPHATEST = false;
  43442. _this.DEPTHPREPASS = false;
  43443. _this.ALPHABLEND = false;
  43444. _this.ALPHAFROMALBEDO = false;
  43445. _this.ALPHATESTVALUE = "0.5";
  43446. _this.SPECULAROVERALPHA = false;
  43447. _this.RADIANCEOVERALPHA = false;
  43448. _this.ALPHAFRESNEL = false;
  43449. _this.LINEARALPHAFRESNEL = false;
  43450. _this.PREMULTIPLYALPHA = false;
  43451. _this.EMISSIVE = false;
  43452. _this.EMISSIVEDIRECTUV = 0;
  43453. _this.REFLECTIVITY = false;
  43454. _this.REFLECTIVITYDIRECTUV = 0;
  43455. _this.SPECULARTERM = false;
  43456. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43457. _this.MICROSURFACEAUTOMATIC = false;
  43458. _this.LODBASEDMICROSFURACE = false;
  43459. _this.MICROSURFACEMAP = false;
  43460. _this.MICROSURFACEMAPDIRECTUV = 0;
  43461. _this.METALLICWORKFLOW = false;
  43462. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43463. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43464. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43465. _this.AOSTOREINMETALMAPRED = false;
  43466. _this.ENVIRONMENTBRDF = false;
  43467. _this.NORMAL = false;
  43468. _this.TANGENT = false;
  43469. _this.BUMP = false;
  43470. _this.BUMPDIRECTUV = 0;
  43471. _this.OBJECTSPACE_NORMALMAP = false;
  43472. _this.PARALLAX = false;
  43473. _this.PARALLAXOCCLUSION = false;
  43474. _this.NORMALXYSCALE = true;
  43475. _this.LIGHTMAP = false;
  43476. _this.LIGHTMAPDIRECTUV = 0;
  43477. _this.USELIGHTMAPASSHADOWMAP = false;
  43478. _this.GAMMALIGHTMAP = false;
  43479. _this.REFLECTION = false;
  43480. _this.REFLECTIONMAP_3D = false;
  43481. _this.REFLECTIONMAP_SPHERICAL = false;
  43482. _this.REFLECTIONMAP_PLANAR = false;
  43483. _this.REFLECTIONMAP_CUBIC = false;
  43484. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43485. _this.REFLECTIONMAP_PROJECTION = false;
  43486. _this.REFLECTIONMAP_SKYBOX = false;
  43487. _this.REFLECTIONMAP_EXPLICIT = false;
  43488. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43489. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43490. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43491. _this.INVERTCUBICMAP = false;
  43492. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43493. _this.USESPHERICALINVERTEX = false;
  43494. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43495. _this.LODINREFLECTIONALPHA = false;
  43496. _this.GAMMAREFLECTION = false;
  43497. _this.RGBDREFLECTION = false;
  43498. _this.RADIANCEOCCLUSION = false;
  43499. _this.HORIZONOCCLUSION = false;
  43500. _this.REFRACTION = false;
  43501. _this.REFRACTIONMAP_3D = false;
  43502. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43503. _this.LODINREFRACTIONALPHA = false;
  43504. _this.GAMMAREFRACTION = false;
  43505. _this.RGBDREFRACTION = false;
  43506. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43507. _this.INSTANCES = false;
  43508. _this.NUM_BONE_INFLUENCERS = 0;
  43509. _this.BonesPerMesh = 0;
  43510. _this.NONUNIFORMSCALING = false;
  43511. _this.MORPHTARGETS = false;
  43512. _this.MORPHTARGETS_NORMAL = false;
  43513. _this.MORPHTARGETS_TANGENT = false;
  43514. _this.NUM_MORPH_INFLUENCERS = 0;
  43515. _this.IMAGEPROCESSING = false;
  43516. _this.VIGNETTE = false;
  43517. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43518. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43519. _this.TONEMAPPING = false;
  43520. _this.CONTRAST = false;
  43521. _this.COLORCURVES = false;
  43522. _this.COLORGRADING = false;
  43523. _this.COLORGRADING3D = false;
  43524. _this.SAMPLER3DGREENDEPTH = false;
  43525. _this.SAMPLER3DBGRMAP = false;
  43526. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43527. _this.EXPOSURE = false;
  43528. _this.USEPHYSICALLIGHTFALLOFF = false;
  43529. _this.TWOSIDEDLIGHTING = false;
  43530. _this.SHADOWFLOAT = false;
  43531. _this.CLIPPLANE = false;
  43532. _this.POINTSIZE = false;
  43533. _this.FOG = false;
  43534. _this.LOGARITHMICDEPTH = false;
  43535. _this.FORCENORMALFORWARD = false;
  43536. _this.SPECULARAA = false;
  43537. _this.UNLIT = false;
  43538. _this.rebuild();
  43539. return _this;
  43540. }
  43541. /**
  43542. * Resets the PBR Material defines.
  43543. */
  43544. PBRMaterialDefines.prototype.reset = function () {
  43545. _super.prototype.reset.call(this);
  43546. this.ALPHATESTVALUE = "0.5";
  43547. this.PBR = true;
  43548. };
  43549. return PBRMaterialDefines;
  43550. }(BABYLON.MaterialDefines));
  43551. /**
  43552. * The Physically based material base class of BJS.
  43553. *
  43554. * This offers the main features of a standard PBR material.
  43555. * For more information, please refer to the documentation :
  43556. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43557. */
  43558. var PBRBaseMaterial = /** @class */ (function (_super) {
  43559. __extends(PBRBaseMaterial, _super);
  43560. /**
  43561. * Instantiates a new PBRMaterial instance.
  43562. *
  43563. * @param name The material name
  43564. * @param scene The scene the material will be use in.
  43565. */
  43566. function PBRBaseMaterial(name, scene) {
  43567. var _this = _super.call(this, name, scene) || this;
  43568. /**
  43569. * Intensity of the direct lights e.g. the four lights available in your scene.
  43570. * This impacts both the direct diffuse and specular highlights.
  43571. */
  43572. _this._directIntensity = 1.0;
  43573. /**
  43574. * Intensity of the emissive part of the material.
  43575. * This helps controlling the emissive effect without modifying the emissive color.
  43576. */
  43577. _this._emissiveIntensity = 1.0;
  43578. /**
  43579. * Intensity of the environment e.g. how much the environment will light the object
  43580. * either through harmonics for rough material or through the refelction for shiny ones.
  43581. */
  43582. _this._environmentIntensity = 1.0;
  43583. /**
  43584. * This is a special control allowing the reduction of the specular highlights coming from the
  43585. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43586. */
  43587. _this._specularIntensity = 1.0;
  43588. /**
  43589. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43590. */
  43591. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43592. /**
  43593. * Debug Control allowing disabling the bump map on this material.
  43594. */
  43595. _this._disableBumpMap = false;
  43596. /**
  43597. * AKA Occlusion Texture Intensity in other nomenclature.
  43598. */
  43599. _this._ambientTextureStrength = 1.0;
  43600. /**
  43601. * The color of a material in ambient lighting.
  43602. */
  43603. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43604. /**
  43605. * AKA Diffuse Color in other nomenclature.
  43606. */
  43607. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43608. /**
  43609. * AKA Specular Color in other nomenclature.
  43610. */
  43611. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43612. /**
  43613. * The color applied when light is reflected from a material.
  43614. */
  43615. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43616. /**
  43617. * The color applied when light is emitted from a material.
  43618. */
  43619. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43620. /**
  43621. * AKA Glossiness in other nomenclature.
  43622. */
  43623. _this._microSurface = 0.9;
  43624. /**
  43625. * source material index of refraction (IOR)' / 'destination material IOR.
  43626. */
  43627. _this._indexOfRefraction = 0.66;
  43628. /**
  43629. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43630. */
  43631. _this._invertRefractionY = false;
  43632. /**
  43633. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43634. * Materials half opaque for instance using refraction could benefit from this control.
  43635. */
  43636. _this._linkRefractionWithTransparency = false;
  43637. /**
  43638. * Specifies that the material will use the light map as a show map.
  43639. */
  43640. _this._useLightmapAsShadowmap = false;
  43641. /**
  43642. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43643. * makes the reflect vector face the model (under horizon).
  43644. */
  43645. _this._useHorizonOcclusion = true;
  43646. /**
  43647. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43648. * too much the area relying on ambient texture to define their ambient occlusion.
  43649. */
  43650. _this._useRadianceOcclusion = true;
  43651. /**
  43652. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43653. */
  43654. _this._useAlphaFromAlbedoTexture = false;
  43655. /**
  43656. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43657. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43658. */
  43659. _this._useSpecularOverAlpha = true;
  43660. /**
  43661. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43662. */
  43663. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43664. /**
  43665. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43666. */
  43667. _this._useRoughnessFromMetallicTextureAlpha = true;
  43668. /**
  43669. * Specifies if the metallic texture contains the roughness information in its green channel.
  43670. */
  43671. _this._useRoughnessFromMetallicTextureGreen = false;
  43672. /**
  43673. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43674. */
  43675. _this._useMetallnessFromMetallicTextureBlue = false;
  43676. /**
  43677. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43678. */
  43679. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43680. /**
  43681. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43682. */
  43683. _this._useAmbientInGrayScale = false;
  43684. /**
  43685. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43686. * The material will try to infer what glossiness each pixel should be.
  43687. */
  43688. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43689. /**
  43690. * BJS is using an harcoded light falloff based on a manually sets up range.
  43691. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43692. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43693. */
  43694. _this._usePhysicalLightFalloff = true;
  43695. /**
  43696. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43697. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43698. */
  43699. _this._useRadianceOverAlpha = true;
  43700. /**
  43701. * Allows using an object space normal map (instead of tangent space).
  43702. */
  43703. _this._useObjectSpaceNormalMap = false;
  43704. /**
  43705. * Allows using the bump map in parallax mode.
  43706. */
  43707. _this._useParallax = false;
  43708. /**
  43709. * Allows using the bump map in parallax occlusion mode.
  43710. */
  43711. _this._useParallaxOcclusion = false;
  43712. /**
  43713. * Controls the scale bias of the parallax mode.
  43714. */
  43715. _this._parallaxScaleBias = 0.05;
  43716. /**
  43717. * If sets to true, disables all the lights affecting the material.
  43718. */
  43719. _this._disableLighting = false;
  43720. /**
  43721. * Number of Simultaneous lights allowed on the material.
  43722. */
  43723. _this._maxSimultaneousLights = 4;
  43724. /**
  43725. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43726. */
  43727. _this._invertNormalMapX = false;
  43728. /**
  43729. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43730. */
  43731. _this._invertNormalMapY = false;
  43732. /**
  43733. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43734. */
  43735. _this._twoSidedLighting = false;
  43736. /**
  43737. * Defines the alpha limits in alpha test mode.
  43738. */
  43739. _this._alphaCutOff = 0.4;
  43740. /**
  43741. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43742. */
  43743. _this._forceAlphaTest = false;
  43744. /**
  43745. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43746. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43747. */
  43748. _this._useAlphaFresnel = false;
  43749. /**
  43750. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43751. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43752. */
  43753. _this._useLinearAlphaFresnel = false;
  43754. /**
  43755. * The transparency mode of the material.
  43756. */
  43757. _this._transparencyMode = null;
  43758. /**
  43759. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43760. * from cos thetav and roughness:
  43761. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43762. */
  43763. _this._environmentBRDFTexture = null;
  43764. /**
  43765. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43766. */
  43767. _this._forceIrradianceInFragment = false;
  43768. /**
  43769. * Force normal to face away from face.
  43770. */
  43771. _this._forceNormalForward = false;
  43772. /**
  43773. * Enables specular anti aliasing in the PBR shader.
  43774. * It will both interacts on the Geometry for analytical and IBL lighting.
  43775. * It also prefilter the roughness map based on the bump values.
  43776. */
  43777. _this._enableSpecularAntiAliasing = false;
  43778. /**
  43779. * Stores the available render targets.
  43780. */
  43781. _this._renderTargets = new BABYLON.SmartArray(16);
  43782. /**
  43783. * Sets the global ambient color for the material used in lighting calculations.
  43784. */
  43785. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43786. /**
  43787. * If set to true, no lighting calculations will be applied.
  43788. */
  43789. _this._unlit = false;
  43790. // Setup the default processing configuration to the scene.
  43791. _this._attachImageProcessingConfiguration(null);
  43792. _this.getRenderTargetTextures = function () {
  43793. _this._renderTargets.reset();
  43794. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43795. _this._renderTargets.push(_this._reflectionTexture);
  43796. }
  43797. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43798. _this._renderTargets.push(_this._refractionTexture);
  43799. }
  43800. return _this._renderTargets;
  43801. };
  43802. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43803. return _this;
  43804. }
  43805. /**
  43806. * Attaches a new image processing configuration to the PBR Material.
  43807. * @param configuration
  43808. */
  43809. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43810. var _this = this;
  43811. if (configuration === this._imageProcessingConfiguration) {
  43812. return;
  43813. }
  43814. // Detaches observer.
  43815. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43816. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43817. }
  43818. // Pick the scene configuration if needed.
  43819. if (!configuration) {
  43820. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43821. }
  43822. else {
  43823. this._imageProcessingConfiguration = configuration;
  43824. }
  43825. // Attaches observer.
  43826. if (this._imageProcessingConfiguration) {
  43827. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43828. _this._markAllSubMeshesAsImageProcessingDirty();
  43829. });
  43830. }
  43831. };
  43832. /**
  43833. * Gets the name of the material class.
  43834. */
  43835. PBRBaseMaterial.prototype.getClassName = function () {
  43836. return "PBRBaseMaterial";
  43837. };
  43838. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43839. /**
  43840. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43841. */
  43842. get: function () {
  43843. return this._useLogarithmicDepth;
  43844. },
  43845. /**
  43846. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43847. */
  43848. set: function (value) {
  43849. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43850. },
  43851. enumerable: true,
  43852. configurable: true
  43853. });
  43854. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43855. /**
  43856. * Gets the current transparency mode.
  43857. */
  43858. get: function () {
  43859. return this._transparencyMode;
  43860. },
  43861. /**
  43862. * Sets the transparency mode of the material.
  43863. *
  43864. * | Value | Type | Description |
  43865. * | ----- | ----------------------------------- | ----------- |
  43866. * | 0 | OPAQUE | |
  43867. * | 1 | ALPHATEST | |
  43868. * | 2 | ALPHABLEND | |
  43869. * | 3 | ALPHATESTANDBLEND | |
  43870. *
  43871. */
  43872. set: function (value) {
  43873. if (this._transparencyMode === value) {
  43874. return;
  43875. }
  43876. this._transparencyMode = value;
  43877. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43878. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43879. },
  43880. enumerable: true,
  43881. configurable: true
  43882. });
  43883. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43884. /**
  43885. * Returns true if alpha blending should be disabled.
  43886. */
  43887. get: function () {
  43888. return (this._linkRefractionWithTransparency ||
  43889. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43890. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43891. },
  43892. enumerable: true,
  43893. configurable: true
  43894. });
  43895. /**
  43896. * Specifies whether or not this material should be rendered in alpha blend mode.
  43897. */
  43898. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43899. if (this._disableAlphaBlending) {
  43900. return false;
  43901. }
  43902. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43903. };
  43904. /**
  43905. * Specifies if the mesh will require alpha blending.
  43906. * @param mesh - BJS mesh.
  43907. */
  43908. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43909. if (this._disableAlphaBlending) {
  43910. return false;
  43911. }
  43912. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43913. };
  43914. /**
  43915. * Specifies whether or not this material should be rendered in alpha test mode.
  43916. */
  43917. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43918. if (this._forceAlphaTest) {
  43919. return true;
  43920. }
  43921. if (this._linkRefractionWithTransparency) {
  43922. return false;
  43923. }
  43924. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43925. };
  43926. /**
  43927. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43928. */
  43929. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43930. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43931. };
  43932. /**
  43933. * Gets the texture used for the alpha test.
  43934. */
  43935. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43936. return this._albedoTexture;
  43937. };
  43938. /**
  43939. * Specifies that the submesh is ready to be used.
  43940. * @param mesh - BJS mesh.
  43941. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43942. * @param useInstances - Specifies that instances should be used.
  43943. * @returns - boolean indicating that the submesh is ready or not.
  43944. */
  43945. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43946. if (subMesh.effect && this.isFrozen) {
  43947. if (this._wasPreviouslyReady) {
  43948. return true;
  43949. }
  43950. }
  43951. if (!subMesh._materialDefines) {
  43952. subMesh._materialDefines = new PBRMaterialDefines();
  43953. }
  43954. var defines = subMesh._materialDefines;
  43955. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43956. if (defines._renderId === this.getScene().getRenderId()) {
  43957. return true;
  43958. }
  43959. }
  43960. var scene = this.getScene();
  43961. var engine = scene.getEngine();
  43962. if (defines._areTexturesDirty) {
  43963. if (scene.texturesEnabled) {
  43964. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43965. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43966. return false;
  43967. }
  43968. }
  43969. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43970. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43971. return false;
  43972. }
  43973. }
  43974. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43975. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43976. return false;
  43977. }
  43978. }
  43979. var reflectionTexture = this._getReflectionTexture();
  43980. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43981. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43982. return false;
  43983. }
  43984. }
  43985. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43986. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43987. return false;
  43988. }
  43989. }
  43990. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43991. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43992. return false;
  43993. }
  43994. }
  43995. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43996. if (this._metallicTexture) {
  43997. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43998. return false;
  43999. }
  44000. }
  44001. else if (this._reflectivityTexture) {
  44002. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44003. return false;
  44004. }
  44005. }
  44006. if (this._microSurfaceTexture) {
  44007. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44008. return false;
  44009. }
  44010. }
  44011. }
  44012. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44013. // Bump texture cannot be not blocking.
  44014. if (!this._bumpTexture.isReady()) {
  44015. return false;
  44016. }
  44017. }
  44018. var refractionTexture = this._getRefractionTexture();
  44019. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44020. if (!refractionTexture.isReadyOrNotBlocking()) {
  44021. return false;
  44022. }
  44023. }
  44024. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44025. // This is blocking.
  44026. if (!this._environmentBRDFTexture.isReady()) {
  44027. return false;
  44028. }
  44029. }
  44030. }
  44031. }
  44032. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44033. if (!this._imageProcessingConfiguration.isReady()) {
  44034. return false;
  44035. }
  44036. }
  44037. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44038. mesh.createNormals(true);
  44039. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44040. }
  44041. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44042. if (effect) {
  44043. scene.resetCachedMaterial();
  44044. subMesh.setEffect(effect, defines);
  44045. this.buildUniformLayout();
  44046. }
  44047. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44048. return false;
  44049. }
  44050. defines._renderId = scene.getRenderId();
  44051. this._wasPreviouslyReady = true;
  44052. return true;
  44053. };
  44054. /**
  44055. * Specifies if the material uses metallic roughness workflow.
  44056. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44057. */
  44058. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44059. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44060. return true;
  44061. }
  44062. return false;
  44063. };
  44064. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44065. if (onCompiled === void 0) { onCompiled = null; }
  44066. if (onError === void 0) { onError = null; }
  44067. if (useInstances === void 0) { useInstances = null; }
  44068. if (useClipPlane === void 0) { useClipPlane = null; }
  44069. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44070. if (!defines.isDirty) {
  44071. return null;
  44072. }
  44073. defines.markAsProcessed();
  44074. var scene = this.getScene();
  44075. var engine = scene.getEngine();
  44076. // Fallbacks
  44077. var fallbacks = new BABYLON.EffectFallbacks();
  44078. var fallbackRank = 0;
  44079. if (defines.USESPHERICALINVERTEX) {
  44080. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44081. }
  44082. if (defines.FOG) {
  44083. fallbacks.addFallback(fallbackRank, "FOG");
  44084. }
  44085. if (defines.SPECULARAA) {
  44086. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44087. }
  44088. if (defines.POINTSIZE) {
  44089. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44090. }
  44091. if (defines.LOGARITHMICDEPTH) {
  44092. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44093. }
  44094. if (defines.PARALLAX) {
  44095. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44096. }
  44097. if (defines.PARALLAXOCCLUSION) {
  44098. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44099. }
  44100. if (defines.ENVIRONMENTBRDF) {
  44101. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44102. }
  44103. if (defines.TANGENT) {
  44104. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44105. }
  44106. if (defines.BUMP) {
  44107. fallbacks.addFallback(fallbackRank++, "BUMP");
  44108. }
  44109. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44110. if (defines.SPECULARTERM) {
  44111. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44112. }
  44113. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44114. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44115. }
  44116. if (defines.LIGHTMAP) {
  44117. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44118. }
  44119. if (defines.NORMAL) {
  44120. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44121. }
  44122. if (defines.AMBIENT) {
  44123. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44124. }
  44125. if (defines.EMISSIVE) {
  44126. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44127. }
  44128. if (defines.VERTEXCOLOR) {
  44129. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44130. }
  44131. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44132. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44133. }
  44134. if (defines.MORPHTARGETS) {
  44135. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44136. }
  44137. //Attributes
  44138. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44139. if (defines.NORMAL) {
  44140. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44141. }
  44142. if (defines.TANGENT) {
  44143. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44144. }
  44145. if (defines.UV1) {
  44146. attribs.push(BABYLON.VertexBuffer.UVKind);
  44147. }
  44148. if (defines.UV2) {
  44149. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44150. }
  44151. if (defines.VERTEXCOLOR) {
  44152. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44153. }
  44154. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44155. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44156. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44157. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44158. "vFogInfos", "vFogColor", "pointSize",
  44159. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44160. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44161. "mBones",
  44162. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44163. "vLightingIntensity",
  44164. "logarithmicDepthConstant",
  44165. "vSphericalX", "vSphericalY", "vSphericalZ",
  44166. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44167. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44168. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44169. "vTangentSpaceParams"
  44170. ];
  44171. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44172. "bumpSampler", "lightmapSampler", "opacitySampler",
  44173. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44174. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44175. "microSurfaceSampler", "environmentBrdfSampler"];
  44176. var uniformBuffers = ["Material", "Scene"];
  44177. if (BABYLON.ImageProcessingConfiguration) {
  44178. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44179. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44180. }
  44181. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44182. uniformsNames: uniforms,
  44183. uniformBuffersNames: uniformBuffers,
  44184. samplers: samplers,
  44185. defines: defines,
  44186. maxSimultaneousLights: this._maxSimultaneousLights
  44187. });
  44188. var join = defines.toString();
  44189. return engine.createEffect("pbr", {
  44190. attributes: attribs,
  44191. uniformsNames: uniforms,
  44192. uniformBuffersNames: uniformBuffers,
  44193. samplers: samplers,
  44194. defines: join,
  44195. fallbacks: fallbacks,
  44196. onCompiled: onCompiled,
  44197. onError: onError,
  44198. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44199. }, engine);
  44200. };
  44201. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44202. if (useInstances === void 0) { useInstances = null; }
  44203. if (useClipPlane === void 0) { useClipPlane = null; }
  44204. var scene = this.getScene();
  44205. var engine = scene.getEngine();
  44206. // Lights
  44207. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44208. defines._needNormals = true;
  44209. // Textures
  44210. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44211. if (defines._areTexturesDirty) {
  44212. defines._needUVs = false;
  44213. if (scene.texturesEnabled) {
  44214. if (scene.getEngine().getCaps().textureLOD) {
  44215. defines.LODBASEDMICROSFURACE = true;
  44216. }
  44217. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44218. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44219. }
  44220. else {
  44221. defines.ALBEDO = false;
  44222. }
  44223. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44224. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44225. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44226. }
  44227. else {
  44228. defines.AMBIENT = false;
  44229. }
  44230. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44231. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44232. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44233. }
  44234. else {
  44235. defines.OPACITY = false;
  44236. }
  44237. var reflectionTexture = this._getReflectionTexture();
  44238. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44239. defines.REFLECTION = true;
  44240. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44241. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44242. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44243. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44244. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44245. defines.INVERTCUBICMAP = true;
  44246. }
  44247. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44248. switch (reflectionTexture.coordinatesMode) {
  44249. case BABYLON.Texture.EXPLICIT_MODE:
  44250. defines.REFLECTIONMAP_EXPLICIT = true;
  44251. break;
  44252. case BABYLON.Texture.PLANAR_MODE:
  44253. defines.REFLECTIONMAP_PLANAR = true;
  44254. break;
  44255. case BABYLON.Texture.PROJECTION_MODE:
  44256. defines.REFLECTIONMAP_PROJECTION = true;
  44257. break;
  44258. case BABYLON.Texture.SKYBOX_MODE:
  44259. defines.REFLECTIONMAP_SKYBOX = true;
  44260. break;
  44261. case BABYLON.Texture.SPHERICAL_MODE:
  44262. defines.REFLECTIONMAP_SPHERICAL = true;
  44263. break;
  44264. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44265. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44266. break;
  44267. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44268. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44269. break;
  44270. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44271. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44272. break;
  44273. case BABYLON.Texture.CUBIC_MODE:
  44274. case BABYLON.Texture.INVCUBIC_MODE:
  44275. default:
  44276. defines.REFLECTIONMAP_CUBIC = true;
  44277. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44278. break;
  44279. }
  44280. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44281. if (reflectionTexture.sphericalPolynomial) {
  44282. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44283. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44284. defines.USESPHERICALINVERTEX = false;
  44285. }
  44286. else {
  44287. defines.USESPHERICALINVERTEX = true;
  44288. }
  44289. }
  44290. }
  44291. }
  44292. else {
  44293. defines.REFLECTION = false;
  44294. defines.REFLECTIONMAP_3D = false;
  44295. defines.REFLECTIONMAP_SPHERICAL = false;
  44296. defines.REFLECTIONMAP_PLANAR = false;
  44297. defines.REFLECTIONMAP_CUBIC = false;
  44298. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44299. defines.REFLECTIONMAP_PROJECTION = false;
  44300. defines.REFLECTIONMAP_SKYBOX = false;
  44301. defines.REFLECTIONMAP_EXPLICIT = false;
  44302. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44303. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44304. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44305. defines.INVERTCUBICMAP = false;
  44306. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44307. defines.USESPHERICALINVERTEX = false;
  44308. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44309. defines.LODINREFLECTIONALPHA = false;
  44310. defines.GAMMAREFLECTION = false;
  44311. defines.RGBDREFLECTION = false;
  44312. }
  44313. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44314. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44315. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44316. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44317. }
  44318. else {
  44319. defines.LIGHTMAP = false;
  44320. }
  44321. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44322. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44323. }
  44324. else {
  44325. defines.EMISSIVE = false;
  44326. }
  44327. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44328. if (this._metallicTexture) {
  44329. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44330. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44331. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44332. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44333. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44334. }
  44335. else if (this._reflectivityTexture) {
  44336. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44337. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44338. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44339. }
  44340. else {
  44341. defines.REFLECTIVITY = false;
  44342. }
  44343. if (this._microSurfaceTexture) {
  44344. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44345. }
  44346. else {
  44347. defines.MICROSURFACEMAP = false;
  44348. }
  44349. }
  44350. else {
  44351. defines.REFLECTIVITY = false;
  44352. defines.MICROSURFACEMAP = false;
  44353. }
  44354. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44356. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44357. defines.PARALLAX = true;
  44358. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44359. }
  44360. else {
  44361. defines.PARALLAX = false;
  44362. }
  44363. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44364. }
  44365. else {
  44366. defines.BUMP = false;
  44367. }
  44368. var refractionTexture = this._getRefractionTexture();
  44369. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44370. defines.REFRACTION = true;
  44371. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44372. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44373. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44374. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44375. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44376. if (this._linkRefractionWithTransparency) {
  44377. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44378. }
  44379. }
  44380. else {
  44381. defines.REFRACTION = false;
  44382. }
  44383. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44384. defines.ENVIRONMENTBRDF = true;
  44385. }
  44386. else {
  44387. defines.ENVIRONMENTBRDF = false;
  44388. }
  44389. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44390. defines.ALPHAFROMALBEDO = true;
  44391. }
  44392. else {
  44393. defines.ALPHAFROMALBEDO = false;
  44394. }
  44395. }
  44396. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44397. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44398. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44399. if (!this.backFaceCulling && this._twoSidedLighting) {
  44400. defines.TWOSIDEDLIGHTING = true;
  44401. }
  44402. else {
  44403. defines.TWOSIDEDLIGHTING = false;
  44404. }
  44405. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44406. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44407. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44408. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44409. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44410. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44411. }
  44412. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44413. this._imageProcessingConfiguration.prepareDefines(defines);
  44414. }
  44415. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44416. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44417. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44418. // Misc.
  44419. if (defines._areMiscDirty) {
  44420. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44421. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44422. }
  44423. // Values that need to be evaluated on every frame
  44424. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44425. // Attribs
  44426. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44427. };
  44428. /**
  44429. * Force shader compilation
  44430. */
  44431. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44432. var _this = this;
  44433. var localOptions = __assign({ clipPlane: false }, options);
  44434. var defines = new PBRMaterialDefines();
  44435. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44436. if (effect.isReady()) {
  44437. if (onCompiled) {
  44438. onCompiled(this);
  44439. }
  44440. }
  44441. else {
  44442. effect.onCompileObservable.add(function () {
  44443. if (onCompiled) {
  44444. onCompiled(_this);
  44445. }
  44446. });
  44447. }
  44448. };
  44449. /**
  44450. * Initializes the uniform buffer layout for the shader.
  44451. */
  44452. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44453. // Order is important !
  44454. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44455. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44456. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44457. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44458. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44459. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44460. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44461. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44462. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44463. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44464. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44465. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44466. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44467. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44468. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44469. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44470. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44471. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44472. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44473. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44474. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44475. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44476. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44477. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44478. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44479. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44480. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44481. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44482. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44483. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44484. this._uniformBuffer.addUniform("pointSize", 1);
  44485. this._uniformBuffer.create();
  44486. };
  44487. /**
  44488. * Unbinds the textures.
  44489. */
  44490. PBRBaseMaterial.prototype.unbind = function () {
  44491. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44492. this._uniformBuffer.setTexture("reflectionSampler", null);
  44493. }
  44494. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44495. this._uniformBuffer.setTexture("refractionSampler", null);
  44496. }
  44497. _super.prototype.unbind.call(this);
  44498. };
  44499. /**
  44500. * Binds the submesh data.
  44501. * @param world - The world matrix.
  44502. * @param mesh - The BJS mesh.
  44503. * @param subMesh - A submesh of the BJS mesh.
  44504. */
  44505. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44506. var scene = this.getScene();
  44507. var defines = subMesh._materialDefines;
  44508. if (!defines) {
  44509. return;
  44510. }
  44511. var effect = subMesh.effect;
  44512. if (!effect) {
  44513. return;
  44514. }
  44515. this._activeEffect = effect;
  44516. // Matrices
  44517. this.bindOnlyWorldMatrix(world);
  44518. // Normal Matrix
  44519. if (defines.OBJECTSPACE_NORMALMAP) {
  44520. world.toNormalMatrix(this._normalMatrix);
  44521. this.bindOnlyNormalMatrix(this._normalMatrix);
  44522. }
  44523. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44524. // Bones
  44525. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44526. var reflectionTexture = null;
  44527. if (mustRebind) {
  44528. this._uniformBuffer.bindToEffect(effect, "Material");
  44529. this.bindViewProjection(effect);
  44530. reflectionTexture = this._getReflectionTexture();
  44531. var refractionTexture = this._getRefractionTexture();
  44532. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44533. // Texture uniforms
  44534. if (scene.texturesEnabled) {
  44535. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44536. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44537. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44538. }
  44539. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44540. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44541. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44542. }
  44543. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44544. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44545. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44546. }
  44547. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44548. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44549. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44550. if (reflectionTexture.boundingBoxSize) {
  44551. var cubeTexture = reflectionTexture;
  44552. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44553. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44554. }
  44555. var polynomials = reflectionTexture.sphericalPolynomial;
  44556. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44557. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44558. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44559. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44560. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44561. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44562. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44563. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44564. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44565. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44566. }
  44567. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44568. }
  44569. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44570. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44571. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44572. }
  44573. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44574. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44575. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44576. }
  44577. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44578. if (this._metallicTexture) {
  44579. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44580. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44581. }
  44582. else if (this._reflectivityTexture) {
  44583. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44584. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44585. }
  44586. if (this._microSurfaceTexture) {
  44587. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44588. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44589. }
  44590. }
  44591. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44592. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44593. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44594. if (scene._mirroredCameraPosition) {
  44595. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44596. }
  44597. else {
  44598. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44599. }
  44600. }
  44601. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44602. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44603. var depth = 1.0;
  44604. if (!refractionTexture.isCube) {
  44605. if (refractionTexture.depth) {
  44606. depth = refractionTexture.depth;
  44607. }
  44608. }
  44609. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44610. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44611. }
  44612. }
  44613. // Point size
  44614. if (this.pointsCloud) {
  44615. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44616. }
  44617. // Colors
  44618. if (defines.METALLICWORKFLOW) {
  44619. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44620. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44621. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44622. }
  44623. else {
  44624. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44625. }
  44626. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44627. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44628. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44629. // Misc
  44630. this._lightingInfos.x = this._directIntensity;
  44631. this._lightingInfos.y = this._emissiveIntensity;
  44632. this._lightingInfos.z = this._environmentIntensity;
  44633. this._lightingInfos.w = this._specularIntensity;
  44634. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44635. }
  44636. // Textures
  44637. if (scene.texturesEnabled) {
  44638. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44639. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44640. }
  44641. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44642. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44643. }
  44644. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44645. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44646. }
  44647. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44648. if (defines.LODBASEDMICROSFURACE) {
  44649. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44650. }
  44651. else {
  44652. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44653. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44654. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44655. }
  44656. }
  44657. if (defines.ENVIRONMENTBRDF) {
  44658. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44659. }
  44660. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44661. if (defines.LODBASEDMICROSFURACE) {
  44662. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44663. }
  44664. else {
  44665. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44666. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44667. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44668. }
  44669. }
  44670. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44671. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44672. }
  44673. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44674. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44675. }
  44676. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44677. if (this._metallicTexture) {
  44678. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44679. }
  44680. else if (this._reflectivityTexture) {
  44681. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44682. }
  44683. if (this._microSurfaceTexture) {
  44684. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44685. }
  44686. }
  44687. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44688. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44689. }
  44690. }
  44691. // Clip plane
  44692. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44693. // Colors
  44694. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44695. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44696. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44697. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44698. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44699. }
  44700. if (mustRebind || !this.isFrozen) {
  44701. // Lights
  44702. if (scene.lightsEnabled && !this._disableLighting) {
  44703. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44704. }
  44705. // View
  44706. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44707. this.bindView(effect);
  44708. }
  44709. // Fog
  44710. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44711. // Morph targets
  44712. if (defines.NUM_MORPH_INFLUENCERS) {
  44713. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44714. }
  44715. // image processing
  44716. this._imageProcessingConfiguration.bind(this._activeEffect);
  44717. // Log. depth
  44718. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44719. }
  44720. this._uniformBuffer.update();
  44721. this._afterBind(mesh, this._activeEffect);
  44722. };
  44723. /**
  44724. * Returns the animatable textures.
  44725. * @returns - Array of animatable textures.
  44726. */
  44727. PBRBaseMaterial.prototype.getAnimatables = function () {
  44728. var results = [];
  44729. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44730. results.push(this._albedoTexture);
  44731. }
  44732. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44733. results.push(this._ambientTexture);
  44734. }
  44735. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44736. results.push(this._opacityTexture);
  44737. }
  44738. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44739. results.push(this._reflectionTexture);
  44740. }
  44741. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44742. results.push(this._emissiveTexture);
  44743. }
  44744. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44745. results.push(this._metallicTexture);
  44746. }
  44747. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44748. results.push(this._reflectivityTexture);
  44749. }
  44750. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44751. results.push(this._bumpTexture);
  44752. }
  44753. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44754. results.push(this._lightmapTexture);
  44755. }
  44756. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44757. results.push(this._refractionTexture);
  44758. }
  44759. return results;
  44760. };
  44761. /**
  44762. * Returns the texture used for reflections.
  44763. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44764. */
  44765. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44766. if (this._reflectionTexture) {
  44767. return this._reflectionTexture;
  44768. }
  44769. return this.getScene().environmentTexture;
  44770. };
  44771. /**
  44772. * Returns the texture used for refraction or null if none is used.
  44773. * @returns - Refection texture if present. If no refraction texture and refraction
  44774. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44775. */
  44776. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44777. if (this._refractionTexture) {
  44778. return this._refractionTexture;
  44779. }
  44780. if (this._linkRefractionWithTransparency) {
  44781. return this.getScene().environmentTexture;
  44782. }
  44783. return null;
  44784. };
  44785. /**
  44786. * Disposes the resources of the material.
  44787. * @param forceDisposeEffect - Forces the disposal of effects.
  44788. * @param forceDisposeTextures - Forces the disposal of all textures.
  44789. */
  44790. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44791. if (forceDisposeTextures) {
  44792. if (this._albedoTexture) {
  44793. this._albedoTexture.dispose();
  44794. }
  44795. if (this._ambientTexture) {
  44796. this._ambientTexture.dispose();
  44797. }
  44798. if (this._opacityTexture) {
  44799. this._opacityTexture.dispose();
  44800. }
  44801. if (this._reflectionTexture) {
  44802. this._reflectionTexture.dispose();
  44803. }
  44804. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44805. this._environmentBRDFTexture.dispose();
  44806. }
  44807. if (this._emissiveTexture) {
  44808. this._emissiveTexture.dispose();
  44809. }
  44810. if (this._metallicTexture) {
  44811. this._metallicTexture.dispose();
  44812. }
  44813. if (this._reflectivityTexture) {
  44814. this._reflectivityTexture.dispose();
  44815. }
  44816. if (this._bumpTexture) {
  44817. this._bumpTexture.dispose();
  44818. }
  44819. if (this._lightmapTexture) {
  44820. this._lightmapTexture.dispose();
  44821. }
  44822. if (this._refractionTexture) {
  44823. this._refractionTexture.dispose();
  44824. }
  44825. }
  44826. this._renderTargets.dispose();
  44827. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44828. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44829. }
  44830. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44831. };
  44832. /**
  44833. * Stores the reflectivity values based on metallic roughness workflow.
  44834. */
  44835. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44836. __decorate([
  44837. BABYLON.serializeAsImageProcessingConfiguration()
  44838. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44839. __decorate([
  44840. BABYLON.serialize()
  44841. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44842. __decorate([
  44843. BABYLON.serialize()
  44844. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44845. return PBRBaseMaterial;
  44846. }(BABYLON.PushMaterial));
  44847. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44848. })(BABYLON || (BABYLON = {}));
  44849. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44850. var BABYLON;
  44851. (function (BABYLON) {
  44852. /**
  44853. * The Physically based simple base material of BJS.
  44854. *
  44855. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44856. * It is used as the base class for both the specGloss and metalRough conventions.
  44857. */
  44858. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44859. __extends(PBRBaseSimpleMaterial, _super);
  44860. /**
  44861. * Instantiates a new PBRMaterial instance.
  44862. *
  44863. * @param name The material name
  44864. * @param scene The scene the material will be use in.
  44865. */
  44866. function PBRBaseSimpleMaterial(name, scene) {
  44867. var _this = _super.call(this, name, scene) || this;
  44868. /**
  44869. * Number of Simultaneous lights allowed on the material.
  44870. */
  44871. _this.maxSimultaneousLights = 4;
  44872. /**
  44873. * If sets to true, disables all the lights affecting the material.
  44874. */
  44875. _this.disableLighting = false;
  44876. /**
  44877. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44878. */
  44879. _this.invertNormalMapX = false;
  44880. /**
  44881. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44882. */
  44883. _this.invertNormalMapY = false;
  44884. /**
  44885. * Emissivie color used to self-illuminate the model.
  44886. */
  44887. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44888. /**
  44889. * Occlusion Channel Strenght.
  44890. */
  44891. _this.occlusionStrength = 1.0;
  44892. _this.useLightmapAsShadowmap = false;
  44893. _this._useAlphaFromAlbedoTexture = true;
  44894. _this._useAmbientInGrayScale = true;
  44895. return _this;
  44896. }
  44897. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44898. /**
  44899. * Gets the current double sided mode.
  44900. */
  44901. get: function () {
  44902. return this._twoSidedLighting;
  44903. },
  44904. /**
  44905. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44906. */
  44907. set: function (value) {
  44908. if (this._twoSidedLighting === value) {
  44909. return;
  44910. }
  44911. this._twoSidedLighting = value;
  44912. this.backFaceCulling = !value;
  44913. this._markAllSubMeshesAsTexturesDirty();
  44914. },
  44915. enumerable: true,
  44916. configurable: true
  44917. });
  44918. /**
  44919. * Return the active textures of the material.
  44920. */
  44921. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44922. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44923. if (this.environmentTexture) {
  44924. activeTextures.push(this.environmentTexture);
  44925. }
  44926. if (this.normalTexture) {
  44927. activeTextures.push(this.normalTexture);
  44928. }
  44929. if (this.emissiveTexture) {
  44930. activeTextures.push(this.emissiveTexture);
  44931. }
  44932. if (this.occlusionTexture) {
  44933. activeTextures.push(this.occlusionTexture);
  44934. }
  44935. if (this.lightmapTexture) {
  44936. activeTextures.push(this.lightmapTexture);
  44937. }
  44938. return activeTextures;
  44939. };
  44940. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44941. if (_super.prototype.hasTexture.call(this, texture)) {
  44942. return true;
  44943. }
  44944. if (this.lightmapTexture === texture) {
  44945. return true;
  44946. }
  44947. return false;
  44948. };
  44949. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44950. return "PBRBaseSimpleMaterial";
  44951. };
  44952. __decorate([
  44953. BABYLON.serialize(),
  44954. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44955. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44956. __decorate([
  44957. BABYLON.serialize(),
  44958. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44959. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44960. __decorate([
  44961. BABYLON.serializeAsTexture(),
  44962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44963. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44964. __decorate([
  44965. BABYLON.serialize(),
  44966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44967. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44968. __decorate([
  44969. BABYLON.serialize(),
  44970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44971. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44972. __decorate([
  44973. BABYLON.serializeAsTexture(),
  44974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44975. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44976. __decorate([
  44977. BABYLON.serializeAsColor3("emissive"),
  44978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44979. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44980. __decorate([
  44981. BABYLON.serializeAsTexture(),
  44982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44983. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44984. __decorate([
  44985. BABYLON.serialize(),
  44986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44987. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44988. __decorate([
  44989. BABYLON.serializeAsTexture(),
  44990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44991. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44992. __decorate([
  44993. BABYLON.serialize(),
  44994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44995. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44996. __decorate([
  44997. BABYLON.serialize()
  44998. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44999. __decorate([
  45000. BABYLON.serializeAsTexture(),
  45001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45002. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45003. __decorate([
  45004. BABYLON.serialize(),
  45005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45006. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45007. return PBRBaseSimpleMaterial;
  45008. }(BABYLON.PBRBaseMaterial));
  45009. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45010. })(BABYLON || (BABYLON = {}));
  45011. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45012. var BABYLON;
  45013. (function (BABYLON) {
  45014. /**
  45015. * The Physically based material of BJS.
  45016. *
  45017. * This offers the main features of a standard PBR material.
  45018. * For more information, please refer to the documentation :
  45019. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45020. */
  45021. var PBRMaterial = /** @class */ (function (_super) {
  45022. __extends(PBRMaterial, _super);
  45023. /**
  45024. * Instantiates a new PBRMaterial instance.
  45025. *
  45026. * @param name The material name
  45027. * @param scene The scene the material will be use in.
  45028. */
  45029. function PBRMaterial(name, scene) {
  45030. var _this = _super.call(this, name, scene) || this;
  45031. /**
  45032. * Intensity of the direct lights e.g. the four lights available in your scene.
  45033. * This impacts both the direct diffuse and specular highlights.
  45034. */
  45035. _this.directIntensity = 1.0;
  45036. /**
  45037. * Intensity of the emissive part of the material.
  45038. * This helps controlling the emissive effect without modifying the emissive color.
  45039. */
  45040. _this.emissiveIntensity = 1.0;
  45041. /**
  45042. * Intensity of the environment e.g. how much the environment will light the object
  45043. * either through harmonics for rough material or through the refelction for shiny ones.
  45044. */
  45045. _this.environmentIntensity = 1.0;
  45046. /**
  45047. * This is a special control allowing the reduction of the specular highlights coming from the
  45048. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45049. */
  45050. _this.specularIntensity = 1.0;
  45051. /**
  45052. * Debug Control allowing disabling the bump map on this material.
  45053. */
  45054. _this.disableBumpMap = false;
  45055. /**
  45056. * AKA Occlusion Texture Intensity in other nomenclature.
  45057. */
  45058. _this.ambientTextureStrength = 1.0;
  45059. /**
  45060. * The color of a material in ambient lighting.
  45061. */
  45062. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45063. /**
  45064. * AKA Diffuse Color in other nomenclature.
  45065. */
  45066. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45067. /**
  45068. * AKA Specular Color in other nomenclature.
  45069. */
  45070. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45071. /**
  45072. * The color reflected from the material.
  45073. */
  45074. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45075. /**
  45076. * The color emitted from the material.
  45077. */
  45078. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45079. /**
  45080. * AKA Glossiness in other nomenclature.
  45081. */
  45082. _this.microSurface = 1.0;
  45083. /**
  45084. * source material index of refraction (IOR)' / 'destination material IOR.
  45085. */
  45086. _this.indexOfRefraction = 0.66;
  45087. /**
  45088. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45089. */
  45090. _this.invertRefractionY = false;
  45091. /**
  45092. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45093. * Materials half opaque for instance using refraction could benefit from this control.
  45094. */
  45095. _this.linkRefractionWithTransparency = false;
  45096. _this.useLightmapAsShadowmap = false;
  45097. /**
  45098. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45099. */
  45100. _this.useAlphaFromAlbedoTexture = false;
  45101. /**
  45102. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45103. */
  45104. _this.forceAlphaTest = false;
  45105. /**
  45106. * Defines the alpha limits in alpha test mode.
  45107. */
  45108. _this.alphaCutOff = 0.4;
  45109. /**
  45110. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45111. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45112. */
  45113. _this.useSpecularOverAlpha = true;
  45114. /**
  45115. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45116. */
  45117. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45118. /**
  45119. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45120. */
  45121. _this.useRoughnessFromMetallicTextureAlpha = true;
  45122. /**
  45123. * Specifies if the metallic texture contains the roughness information in its green channel.
  45124. */
  45125. _this.useRoughnessFromMetallicTextureGreen = false;
  45126. /**
  45127. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45128. */
  45129. _this.useMetallnessFromMetallicTextureBlue = false;
  45130. /**
  45131. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45132. */
  45133. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45134. /**
  45135. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45136. */
  45137. _this.useAmbientInGrayScale = false;
  45138. /**
  45139. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45140. * The material will try to infer what glossiness each pixel should be.
  45141. */
  45142. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45143. /**
  45144. * BJS is using an harcoded light falloff based on a manually sets up range.
  45145. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45146. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45147. */
  45148. _this.usePhysicalLightFalloff = true;
  45149. /**
  45150. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45151. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45152. */
  45153. _this.useRadianceOverAlpha = true;
  45154. /**
  45155. * Allows using an object space normal map (instead of tangent space).
  45156. */
  45157. _this.useObjectSpaceNormalMap = false;
  45158. /**
  45159. * Allows using the bump map in parallax mode.
  45160. */
  45161. _this.useParallax = false;
  45162. /**
  45163. * Allows using the bump map in parallax occlusion mode.
  45164. */
  45165. _this.useParallaxOcclusion = false;
  45166. /**
  45167. * Controls the scale bias of the parallax mode.
  45168. */
  45169. _this.parallaxScaleBias = 0.05;
  45170. /**
  45171. * If sets to true, disables all the lights affecting the material.
  45172. */
  45173. _this.disableLighting = false;
  45174. /**
  45175. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45176. */
  45177. _this.forceIrradianceInFragment = false;
  45178. /**
  45179. * Number of Simultaneous lights allowed on the material.
  45180. */
  45181. _this.maxSimultaneousLights = 4;
  45182. /**
  45183. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45184. */
  45185. _this.invertNormalMapX = false;
  45186. /**
  45187. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45188. */
  45189. _this.invertNormalMapY = false;
  45190. /**
  45191. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45192. */
  45193. _this.twoSidedLighting = false;
  45194. /**
  45195. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45196. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45197. */
  45198. _this.useAlphaFresnel = false;
  45199. /**
  45200. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45201. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45202. */
  45203. _this.useLinearAlphaFresnel = false;
  45204. /**
  45205. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45206. * And/Or occlude the blended part.
  45207. */
  45208. _this.environmentBRDFTexture = null;
  45209. /**
  45210. * Force normal to face away from face.
  45211. */
  45212. _this.forceNormalForward = false;
  45213. /**
  45214. * Enables specular anti aliasing in the PBR shader.
  45215. * It will both interacts on the Geometry for analytical and IBL lighting.
  45216. * It also prefilter the roughness map based on the bump values.
  45217. */
  45218. _this.enableSpecularAntiAliasing = false;
  45219. /**
  45220. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45221. * makes the reflect vector face the model (under horizon).
  45222. */
  45223. _this.useHorizonOcclusion = true;
  45224. /**
  45225. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45226. * too much the area relying on ambient texture to define their ambient occlusion.
  45227. */
  45228. _this.useRadianceOcclusion = true;
  45229. /**
  45230. * If set to true, no lighting calculations will be applied.
  45231. */
  45232. _this.unlit = false;
  45233. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45234. return _this;
  45235. }
  45236. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45237. /**
  45238. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45239. */
  45240. get: function () {
  45241. return this._PBRMATERIAL_OPAQUE;
  45242. },
  45243. enumerable: true,
  45244. configurable: true
  45245. });
  45246. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45247. /**
  45248. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45249. */
  45250. get: function () {
  45251. return this._PBRMATERIAL_ALPHATEST;
  45252. },
  45253. enumerable: true,
  45254. configurable: true
  45255. });
  45256. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45257. /**
  45258. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45259. */
  45260. get: function () {
  45261. return this._PBRMATERIAL_ALPHABLEND;
  45262. },
  45263. enumerable: true,
  45264. configurable: true
  45265. });
  45266. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45267. /**
  45268. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45269. * They are also discarded below the alpha cutoff threshold to improve performances.
  45270. */
  45271. get: function () {
  45272. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45273. },
  45274. enumerable: true,
  45275. configurable: true
  45276. });
  45277. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45278. /**
  45279. * Gets the image processing configuration used either in this material.
  45280. */
  45281. get: function () {
  45282. return this._imageProcessingConfiguration;
  45283. },
  45284. /**
  45285. * Sets the Default image processing configuration used either in the this material.
  45286. *
  45287. * If sets to null, the scene one is in use.
  45288. */
  45289. set: function (value) {
  45290. this._attachImageProcessingConfiguration(value);
  45291. // Ensure the effect will be rebuilt.
  45292. this._markAllSubMeshesAsTexturesDirty();
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45298. /**
  45299. * Gets wether the color curves effect is enabled.
  45300. */
  45301. get: function () {
  45302. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45303. },
  45304. /**
  45305. * Sets wether the color curves effect is enabled.
  45306. */
  45307. set: function (value) {
  45308. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45309. },
  45310. enumerable: true,
  45311. configurable: true
  45312. });
  45313. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45314. /**
  45315. * Gets wether the color grading effect is enabled.
  45316. */
  45317. get: function () {
  45318. return this.imageProcessingConfiguration.colorGradingEnabled;
  45319. },
  45320. /**
  45321. * Gets wether the color grading effect is enabled.
  45322. */
  45323. set: function (value) {
  45324. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45325. },
  45326. enumerable: true,
  45327. configurable: true
  45328. });
  45329. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45330. /**
  45331. * Gets wether tonemapping is enabled or not.
  45332. */
  45333. get: function () {
  45334. return this._imageProcessingConfiguration.toneMappingEnabled;
  45335. },
  45336. /**
  45337. * Sets wether tonemapping is enabled or not
  45338. */
  45339. set: function (value) {
  45340. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. ;
  45346. ;
  45347. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45348. /**
  45349. * The camera exposure used on this material.
  45350. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45351. * This corresponds to a photographic exposure.
  45352. */
  45353. get: function () {
  45354. return this._imageProcessingConfiguration.exposure;
  45355. },
  45356. /**
  45357. * The camera exposure used on this material.
  45358. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45359. * This corresponds to a photographic exposure.
  45360. */
  45361. set: function (value) {
  45362. this._imageProcessingConfiguration.exposure = value;
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. ;
  45368. ;
  45369. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45370. /**
  45371. * Gets The camera contrast used on this material.
  45372. */
  45373. get: function () {
  45374. return this._imageProcessingConfiguration.contrast;
  45375. },
  45376. /**
  45377. * Sets The camera contrast used on this material.
  45378. */
  45379. set: function (value) {
  45380. this._imageProcessingConfiguration.contrast = value;
  45381. },
  45382. enumerable: true,
  45383. configurable: true
  45384. });
  45385. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45386. /**
  45387. * Gets the Color Grading 2D Lookup Texture.
  45388. */
  45389. get: function () {
  45390. return this._imageProcessingConfiguration.colorGradingTexture;
  45391. },
  45392. /**
  45393. * Sets the Color Grading 2D Lookup Texture.
  45394. */
  45395. set: function (value) {
  45396. this._imageProcessingConfiguration.colorGradingTexture = value;
  45397. },
  45398. enumerable: true,
  45399. configurable: true
  45400. });
  45401. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45402. /**
  45403. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45404. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45405. * 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;
  45406. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45407. */
  45408. get: function () {
  45409. return this._imageProcessingConfiguration.colorCurves;
  45410. },
  45411. /**
  45412. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45413. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45414. * 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;
  45415. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45416. */
  45417. set: function (value) {
  45418. this._imageProcessingConfiguration.colorCurves = value;
  45419. },
  45420. enumerable: true,
  45421. configurable: true
  45422. });
  45423. /**
  45424. * Returns the name of this material class.
  45425. */
  45426. PBRMaterial.prototype.getClassName = function () {
  45427. return "PBRMaterial";
  45428. };
  45429. /**
  45430. * Returns an array of the actively used textures.
  45431. * @returns - Array of BaseTextures
  45432. */
  45433. PBRMaterial.prototype.getActiveTextures = function () {
  45434. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45435. if (this._albedoTexture) {
  45436. activeTextures.push(this._albedoTexture);
  45437. }
  45438. if (this._ambientTexture) {
  45439. activeTextures.push(this._ambientTexture);
  45440. }
  45441. if (this._opacityTexture) {
  45442. activeTextures.push(this._opacityTexture);
  45443. }
  45444. if (this._reflectionTexture) {
  45445. activeTextures.push(this._reflectionTexture);
  45446. }
  45447. if (this._emissiveTexture) {
  45448. activeTextures.push(this._emissiveTexture);
  45449. }
  45450. if (this._reflectivityTexture) {
  45451. activeTextures.push(this._reflectivityTexture);
  45452. }
  45453. if (this._metallicTexture) {
  45454. activeTextures.push(this._metallicTexture);
  45455. }
  45456. if (this._microSurfaceTexture) {
  45457. activeTextures.push(this._microSurfaceTexture);
  45458. }
  45459. if (this._bumpTexture) {
  45460. activeTextures.push(this._bumpTexture);
  45461. }
  45462. if (this._lightmapTexture) {
  45463. activeTextures.push(this._lightmapTexture);
  45464. }
  45465. if (this._refractionTexture) {
  45466. activeTextures.push(this._refractionTexture);
  45467. }
  45468. return activeTextures;
  45469. };
  45470. /**
  45471. * Checks to see if a texture is used in the material.
  45472. * @param texture - Base texture to use.
  45473. * @returns - Boolean specifying if a texture is used in the material.
  45474. */
  45475. PBRMaterial.prototype.hasTexture = function (texture) {
  45476. if (_super.prototype.hasTexture.call(this, texture)) {
  45477. return true;
  45478. }
  45479. if (this._albedoTexture === texture) {
  45480. return true;
  45481. }
  45482. if (this._ambientTexture === texture) {
  45483. return true;
  45484. }
  45485. if (this._opacityTexture === texture) {
  45486. return true;
  45487. }
  45488. if (this._reflectionTexture === texture) {
  45489. return true;
  45490. }
  45491. if (this._reflectivityTexture === texture) {
  45492. return true;
  45493. }
  45494. if (this._metallicTexture === texture) {
  45495. return true;
  45496. }
  45497. if (this._microSurfaceTexture === texture) {
  45498. return true;
  45499. }
  45500. if (this._bumpTexture === texture) {
  45501. return true;
  45502. }
  45503. if (this._lightmapTexture === texture) {
  45504. return true;
  45505. }
  45506. if (this._refractionTexture === texture) {
  45507. return true;
  45508. }
  45509. return false;
  45510. };
  45511. /**
  45512. * Makes a duplicate of the current material.
  45513. * @param name - name to use for the new material.
  45514. */
  45515. PBRMaterial.prototype.clone = function (name) {
  45516. var _this = this;
  45517. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45518. clone.id = name;
  45519. clone.name = name;
  45520. return clone;
  45521. };
  45522. /**
  45523. * Serializes this PBR Material.
  45524. * @returns - An object with the serialized material.
  45525. */
  45526. PBRMaterial.prototype.serialize = function () {
  45527. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45528. serializationObject.customType = "BABYLON.PBRMaterial";
  45529. return serializationObject;
  45530. };
  45531. // Statics
  45532. /**
  45533. * Parses a PBR Material from a serialized object.
  45534. * @param source - Serialized object.
  45535. * @param scene - BJS scene instance.
  45536. * @param rootUrl - url for the scene object
  45537. * @returns - PBRMaterial
  45538. */
  45539. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45540. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45541. };
  45542. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45543. /**
  45544. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45545. */
  45546. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45547. /**
  45548. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45549. */
  45550. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45551. /**
  45552. * 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.
  45553. * They are also discarded below the alpha cutoff threshold to improve performances.
  45554. */
  45555. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45556. __decorate([
  45557. BABYLON.serialize(),
  45558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45559. ], PBRMaterial.prototype, "directIntensity", void 0);
  45560. __decorate([
  45561. BABYLON.serialize(),
  45562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45563. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45564. __decorate([
  45565. BABYLON.serialize(),
  45566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45567. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45568. __decorate([
  45569. BABYLON.serialize(),
  45570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45571. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45572. __decorate([
  45573. BABYLON.serialize(),
  45574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45575. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45576. __decorate([
  45577. BABYLON.serializeAsTexture(),
  45578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45579. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45580. __decorate([
  45581. BABYLON.serializeAsTexture(),
  45582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45583. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45584. __decorate([
  45585. BABYLON.serialize(),
  45586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45587. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45588. __decorate([
  45589. BABYLON.serializeAsTexture(),
  45590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45591. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45592. __decorate([
  45593. BABYLON.serializeAsTexture(),
  45594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45595. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45596. __decorate([
  45597. BABYLON.serializeAsTexture(),
  45598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45599. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45600. __decorate([
  45601. BABYLON.serializeAsTexture(),
  45602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45603. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45604. __decorate([
  45605. BABYLON.serializeAsTexture(),
  45606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45607. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45608. __decorate([
  45609. BABYLON.serialize(),
  45610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45611. ], PBRMaterial.prototype, "metallic", void 0);
  45612. __decorate([
  45613. BABYLON.serialize(),
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45615. ], PBRMaterial.prototype, "roughness", void 0);
  45616. __decorate([
  45617. BABYLON.serializeAsTexture(),
  45618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45619. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45620. __decorate([
  45621. BABYLON.serializeAsTexture(),
  45622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45623. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45624. __decorate([
  45625. BABYLON.serializeAsTexture(),
  45626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45627. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45628. __decorate([
  45629. BABYLON.serializeAsTexture(),
  45630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45631. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45632. __decorate([
  45633. BABYLON.serializeAsColor3("ambient"),
  45634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45635. ], PBRMaterial.prototype, "ambientColor", void 0);
  45636. __decorate([
  45637. BABYLON.serializeAsColor3("albedo"),
  45638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45639. ], PBRMaterial.prototype, "albedoColor", void 0);
  45640. __decorate([
  45641. BABYLON.serializeAsColor3("reflectivity"),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45643. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45644. __decorate([
  45645. BABYLON.serializeAsColor3("reflection"),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45647. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45648. __decorate([
  45649. BABYLON.serializeAsColor3("emissive"),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45651. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45652. __decorate([
  45653. BABYLON.serialize(),
  45654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45655. ], PBRMaterial.prototype, "microSurface", void 0);
  45656. __decorate([
  45657. BABYLON.serialize(),
  45658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45659. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45660. __decorate([
  45661. BABYLON.serialize(),
  45662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45663. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45664. __decorate([
  45665. BABYLON.serialize(),
  45666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45667. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45668. __decorate([
  45669. BABYLON.serialize(),
  45670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45671. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45672. __decorate([
  45673. BABYLON.serialize(),
  45674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45675. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45676. __decorate([
  45677. BABYLON.serialize(),
  45678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45679. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45680. __decorate([
  45681. BABYLON.serialize(),
  45682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45683. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45684. __decorate([
  45685. BABYLON.serialize(),
  45686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45687. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45688. __decorate([
  45689. BABYLON.serialize(),
  45690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45691. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45692. __decorate([
  45693. BABYLON.serialize(),
  45694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45695. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45696. __decorate([
  45697. BABYLON.serialize(),
  45698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45699. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45700. __decorate([
  45701. BABYLON.serialize(),
  45702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45703. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45704. __decorate([
  45705. BABYLON.serialize(),
  45706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45707. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45708. __decorate([
  45709. BABYLON.serialize(),
  45710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45711. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45712. __decorate([
  45713. BABYLON.serialize(),
  45714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45715. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45716. __decorate([
  45717. BABYLON.serialize(),
  45718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45719. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45720. __decorate([
  45721. BABYLON.serialize(),
  45722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45723. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45724. __decorate([
  45725. BABYLON.serialize(),
  45726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45727. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45728. __decorate([
  45729. BABYLON.serialize(),
  45730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45731. ], PBRMaterial.prototype, "useParallax", void 0);
  45732. __decorate([
  45733. BABYLON.serialize(),
  45734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45735. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45736. __decorate([
  45737. BABYLON.serialize(),
  45738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45739. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45740. __decorate([
  45741. BABYLON.serialize(),
  45742. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45743. ], PBRMaterial.prototype, "disableLighting", void 0);
  45744. __decorate([
  45745. BABYLON.serialize(),
  45746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45747. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45748. __decorate([
  45749. BABYLON.serialize(),
  45750. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45751. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45752. __decorate([
  45753. BABYLON.serialize(),
  45754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45755. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45756. __decorate([
  45757. BABYLON.serialize(),
  45758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45759. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45760. __decorate([
  45761. BABYLON.serialize(),
  45762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45763. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45764. __decorate([
  45765. BABYLON.serialize(),
  45766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45767. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45768. __decorate([
  45769. BABYLON.serialize(),
  45770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45771. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45772. __decorate([
  45773. BABYLON.serializeAsTexture(),
  45774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45775. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45776. __decorate([
  45777. BABYLON.serialize(),
  45778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45779. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45780. __decorate([
  45781. BABYLON.serialize(),
  45782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45783. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45784. __decorate([
  45785. BABYLON.serialize(),
  45786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45787. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45788. __decorate([
  45789. BABYLON.serialize(),
  45790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45791. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45792. __decorate([
  45793. BABYLON.serialize(),
  45794. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45795. ], PBRMaterial.prototype, "unlit", void 0);
  45796. return PBRMaterial;
  45797. }(BABYLON.PBRBaseMaterial));
  45798. BABYLON.PBRMaterial = PBRMaterial;
  45799. })(BABYLON || (BABYLON = {}));
  45800. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45801. var BABYLON;
  45802. (function (BABYLON) {
  45803. /**
  45804. * The PBR material of BJS following the metal roughness convention.
  45805. *
  45806. * This fits to the PBR convention in the GLTF definition:
  45807. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45808. */
  45809. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45810. __extends(PBRMetallicRoughnessMaterial, _super);
  45811. /**
  45812. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45813. *
  45814. * @param name The material name
  45815. * @param scene The scene the material will be use in.
  45816. */
  45817. function PBRMetallicRoughnessMaterial(name, scene) {
  45818. var _this = _super.call(this, name, scene) || this;
  45819. _this._useRoughnessFromMetallicTextureAlpha = false;
  45820. _this._useRoughnessFromMetallicTextureGreen = true;
  45821. _this._useMetallnessFromMetallicTextureBlue = true;
  45822. _this.metallic = 1.0;
  45823. _this.roughness = 1.0;
  45824. return _this;
  45825. }
  45826. /**
  45827. * Return the currrent class name of the material.
  45828. */
  45829. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45830. return "PBRMetallicRoughnessMaterial";
  45831. };
  45832. /**
  45833. * Return the active textures of the material.
  45834. */
  45835. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45836. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45837. if (this.baseTexture) {
  45838. activeTextures.push(this.baseTexture);
  45839. }
  45840. if (this.metallicRoughnessTexture) {
  45841. activeTextures.push(this.metallicRoughnessTexture);
  45842. }
  45843. return activeTextures;
  45844. };
  45845. /**
  45846. * Checks to see if a texture is used in the material.
  45847. * @param texture - Base texture to use.
  45848. * @returns - Boolean specifying if a texture is used in the material.
  45849. */
  45850. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45851. if (_super.prototype.hasTexture.call(this, texture)) {
  45852. return true;
  45853. }
  45854. if (this.baseTexture === texture) {
  45855. return true;
  45856. }
  45857. if (this.metallicRoughnessTexture === texture) {
  45858. return true;
  45859. }
  45860. return false;
  45861. };
  45862. /**
  45863. * Makes a duplicate of the current material.
  45864. * @param name - name to use for the new material.
  45865. */
  45866. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45867. var _this = this;
  45868. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45869. clone.id = name;
  45870. clone.name = name;
  45871. return clone;
  45872. };
  45873. /**
  45874. * Serialize the material to a parsable JSON object.
  45875. */
  45876. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45877. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45878. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45879. return serializationObject;
  45880. };
  45881. /**
  45882. * Parses a JSON object correponding to the serialize function.
  45883. */
  45884. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45885. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45886. };
  45887. __decorate([
  45888. BABYLON.serializeAsColor3(),
  45889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45890. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45891. __decorate([
  45892. BABYLON.serializeAsTexture(),
  45893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45894. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45895. __decorate([
  45896. BABYLON.serialize(),
  45897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45898. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45899. __decorate([
  45900. BABYLON.serialize(),
  45901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45902. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45903. __decorate([
  45904. BABYLON.serializeAsTexture(),
  45905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45906. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45907. return PBRMetallicRoughnessMaterial;
  45908. }(BABYLON.PBRBaseSimpleMaterial));
  45909. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45910. })(BABYLON || (BABYLON = {}));
  45911. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45912. var BABYLON;
  45913. (function (BABYLON) {
  45914. /**
  45915. * The PBR material of BJS following the specular glossiness convention.
  45916. *
  45917. * This fits to the PBR convention in the GLTF definition:
  45918. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45919. */
  45920. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45921. __extends(PBRSpecularGlossinessMaterial, _super);
  45922. /**
  45923. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45924. *
  45925. * @param name The material name
  45926. * @param scene The scene the material will be use in.
  45927. */
  45928. function PBRSpecularGlossinessMaterial(name, scene) {
  45929. var _this = _super.call(this, name, scene) || this;
  45930. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45931. return _this;
  45932. }
  45933. /**
  45934. * Return the currrent class name of the material.
  45935. */
  45936. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45937. return "PBRSpecularGlossinessMaterial";
  45938. };
  45939. /**
  45940. * Return the active textures of the material.
  45941. */
  45942. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45943. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45944. if (this.diffuseTexture) {
  45945. activeTextures.push(this.diffuseTexture);
  45946. }
  45947. if (this.specularGlossinessTexture) {
  45948. activeTextures.push(this.specularGlossinessTexture);
  45949. }
  45950. return activeTextures;
  45951. };
  45952. /**
  45953. * Checks to see if a texture is used in the material.
  45954. * @param texture - Base texture to use.
  45955. * @returns - Boolean specifying if a texture is used in the material.
  45956. */
  45957. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45958. if (_super.prototype.hasTexture.call(this, texture)) {
  45959. return true;
  45960. }
  45961. if (this.diffuseTexture === texture) {
  45962. return true;
  45963. }
  45964. if (this.specularGlossinessTexture === texture) {
  45965. return true;
  45966. }
  45967. return false;
  45968. };
  45969. /**
  45970. * Makes a duplicate of the current material.
  45971. * @param name - name to use for the new material.
  45972. */
  45973. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45974. var _this = this;
  45975. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45976. clone.id = name;
  45977. clone.name = name;
  45978. return clone;
  45979. };
  45980. /**
  45981. * Serialize the material to a parsable JSON object.
  45982. */
  45983. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45984. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45985. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45986. return serializationObject;
  45987. };
  45988. /**
  45989. * Parses a JSON object correponding to the serialize function.
  45990. */
  45991. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45992. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45993. };
  45994. __decorate([
  45995. BABYLON.serializeAsColor3("diffuse"),
  45996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45997. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45998. __decorate([
  45999. BABYLON.serializeAsTexture(),
  46000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46001. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46002. __decorate([
  46003. BABYLON.serializeAsColor3("specular"),
  46004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46005. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46006. __decorate([
  46007. BABYLON.serialize(),
  46008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46009. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46010. __decorate([
  46011. BABYLON.serializeAsTexture(),
  46012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46013. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46014. return PBRSpecularGlossinessMaterial;
  46015. }(BABYLON.PBRBaseSimpleMaterial));
  46016. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46017. })(BABYLON || (BABYLON = {}));
  46018. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46019. var BABYLON;
  46020. (function (BABYLON) {
  46021. BABYLON.CameraInputTypes = {};
  46022. var CameraInputsManager = /** @class */ (function () {
  46023. function CameraInputsManager(camera) {
  46024. this.attached = {};
  46025. this.camera = camera;
  46026. this.checkInputs = function () { };
  46027. }
  46028. /**
  46029. * Add an input method to a camera.
  46030. * builtin inputs example: camera.inputs.addGamepad();
  46031. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46032. * @param input camera input method
  46033. */
  46034. CameraInputsManager.prototype.add = function (input) {
  46035. var type = input.getSimpleName();
  46036. if (this.attached[type]) {
  46037. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46038. return;
  46039. }
  46040. this.attached[type] = input;
  46041. input.camera = this.camera;
  46042. //for checkInputs, we are dynamically creating a function
  46043. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46044. if (input.checkInputs) {
  46045. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46046. }
  46047. if (this.attachedElement) {
  46048. input.attachControl(this.attachedElement);
  46049. }
  46050. };
  46051. /**
  46052. * Remove a specific input method from a camera
  46053. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46054. * @param inputToRemove camera input method
  46055. */
  46056. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46057. for (var cam in this.attached) {
  46058. var input = this.attached[cam];
  46059. if (input === inputToRemove) {
  46060. input.detachControl(this.attachedElement);
  46061. input.camera = null;
  46062. delete this.attached[cam];
  46063. this.rebuildInputCheck();
  46064. }
  46065. }
  46066. };
  46067. CameraInputsManager.prototype.removeByType = function (inputType) {
  46068. for (var cam in this.attached) {
  46069. var input = this.attached[cam];
  46070. if (input.getClassName() === inputType) {
  46071. input.detachControl(this.attachedElement);
  46072. input.camera = null;
  46073. delete this.attached[cam];
  46074. this.rebuildInputCheck();
  46075. }
  46076. }
  46077. };
  46078. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46079. var current = this.checkInputs;
  46080. return function () {
  46081. current();
  46082. fn();
  46083. };
  46084. };
  46085. CameraInputsManager.prototype.attachInput = function (input) {
  46086. if (this.attachedElement) {
  46087. input.attachControl(this.attachedElement, this.noPreventDefault);
  46088. }
  46089. };
  46090. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46091. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46092. if (this.attachedElement) {
  46093. return;
  46094. }
  46095. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46096. this.attachedElement = element;
  46097. this.noPreventDefault = noPreventDefault;
  46098. for (var cam in this.attached) {
  46099. this.attached[cam].attachControl(element, noPreventDefault);
  46100. }
  46101. };
  46102. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46103. if (disconnect === void 0) { disconnect = false; }
  46104. if (this.attachedElement !== element) {
  46105. return;
  46106. }
  46107. for (var cam in this.attached) {
  46108. this.attached[cam].detachControl(element);
  46109. if (disconnect) {
  46110. this.attached[cam].camera = null;
  46111. }
  46112. }
  46113. this.attachedElement = null;
  46114. };
  46115. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46116. this.checkInputs = function () { };
  46117. for (var cam in this.attached) {
  46118. var input = this.attached[cam];
  46119. if (input.checkInputs) {
  46120. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46121. }
  46122. }
  46123. };
  46124. /**
  46125. * Remove all attached input methods from a camera
  46126. */
  46127. CameraInputsManager.prototype.clear = function () {
  46128. if (this.attachedElement) {
  46129. this.detachElement(this.attachedElement, true);
  46130. }
  46131. this.attached = {};
  46132. this.attachedElement = null;
  46133. this.checkInputs = function () { };
  46134. };
  46135. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46136. var inputs = {};
  46137. for (var cam in this.attached) {
  46138. var input = this.attached[cam];
  46139. var res = BABYLON.SerializationHelper.Serialize(input);
  46140. inputs[input.getClassName()] = res;
  46141. }
  46142. serializedCamera.inputsmgr = inputs;
  46143. };
  46144. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46145. var parsedInputs = parsedCamera.inputsmgr;
  46146. if (parsedInputs) {
  46147. this.clear();
  46148. for (var n in parsedInputs) {
  46149. var construct = BABYLON.CameraInputTypes[n];
  46150. if (construct) {
  46151. var parsedinput = parsedInputs[n];
  46152. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46153. this.add(input);
  46154. }
  46155. }
  46156. }
  46157. else {
  46158. //2016-03-08 this part is for managing backward compatibility
  46159. for (var n in this.attached) {
  46160. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46161. if (construct) {
  46162. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46163. this.remove(this.attached[n]);
  46164. this.add(input);
  46165. }
  46166. }
  46167. }
  46168. };
  46169. return CameraInputsManager;
  46170. }());
  46171. BABYLON.CameraInputsManager = CameraInputsManager;
  46172. })(BABYLON || (BABYLON = {}));
  46173. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46174. var BABYLON;
  46175. (function (BABYLON) {
  46176. var TargetCamera = /** @class */ (function (_super) {
  46177. __extends(TargetCamera, _super);
  46178. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46179. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46180. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46181. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46182. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46183. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46184. _this.speed = 2.0;
  46185. _this.noRotationConstraint = false;
  46186. _this.lockedTarget = null;
  46187. _this._currentTarget = BABYLON.Vector3.Zero();
  46188. _this._viewMatrix = BABYLON.Matrix.Zero();
  46189. _this._camMatrix = BABYLON.Matrix.Zero();
  46190. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46191. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46192. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46193. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46194. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46195. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46196. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46197. return _this;
  46198. }
  46199. TargetCamera.prototype.getFrontPosition = function (distance) {
  46200. this.getWorldMatrix();
  46201. var direction = this.getTarget().subtract(this.position);
  46202. direction.normalize();
  46203. direction.scaleInPlace(distance);
  46204. return this.globalPosition.add(direction);
  46205. };
  46206. TargetCamera.prototype._getLockedTargetPosition = function () {
  46207. if (!this.lockedTarget) {
  46208. return null;
  46209. }
  46210. if (this.lockedTarget.absolutePosition) {
  46211. this.lockedTarget.computeWorldMatrix();
  46212. }
  46213. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46214. };
  46215. TargetCamera.prototype.storeState = function () {
  46216. this._storedPosition = this.position.clone();
  46217. this._storedRotation = this.rotation.clone();
  46218. if (this.rotationQuaternion) {
  46219. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46220. }
  46221. return _super.prototype.storeState.call(this);
  46222. };
  46223. /**
  46224. * Restored camera state. You must call storeState() first
  46225. */
  46226. TargetCamera.prototype._restoreStateValues = function () {
  46227. if (!_super.prototype._restoreStateValues.call(this)) {
  46228. return false;
  46229. }
  46230. this.position = this._storedPosition.clone();
  46231. this.rotation = this._storedRotation.clone();
  46232. if (this.rotationQuaternion) {
  46233. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46234. }
  46235. this.cameraDirection.copyFromFloats(0, 0, 0);
  46236. this.cameraRotation.copyFromFloats(0, 0);
  46237. return true;
  46238. };
  46239. // Cache
  46240. TargetCamera.prototype._initCache = function () {
  46241. _super.prototype._initCache.call(this);
  46242. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46243. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46244. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46245. };
  46246. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46247. if (!ignoreParentClass) {
  46248. _super.prototype._updateCache.call(this);
  46249. }
  46250. var lockedTargetPosition = this._getLockedTargetPosition();
  46251. if (!lockedTargetPosition) {
  46252. this._cache.lockedTarget = null;
  46253. }
  46254. else {
  46255. if (!this._cache.lockedTarget) {
  46256. this._cache.lockedTarget = lockedTargetPosition.clone();
  46257. }
  46258. else {
  46259. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46260. }
  46261. }
  46262. this._cache.rotation.copyFrom(this.rotation);
  46263. if (this.rotationQuaternion)
  46264. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46265. };
  46266. // Synchronized
  46267. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46268. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46269. return false;
  46270. }
  46271. var lockedTargetPosition = this._getLockedTargetPosition();
  46272. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46273. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46274. };
  46275. // Methods
  46276. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46277. var engine = this.getEngine();
  46278. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46279. };
  46280. // Target
  46281. TargetCamera.prototype.setTarget = function (target) {
  46282. this.upVector.normalize();
  46283. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46284. this._camMatrix.invert();
  46285. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46286. var vDir = target.subtract(this.position);
  46287. if (vDir.x >= 0.0) {
  46288. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46289. }
  46290. else {
  46291. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46292. }
  46293. this.rotation.z = 0;
  46294. if (isNaN(this.rotation.x)) {
  46295. this.rotation.x = 0;
  46296. }
  46297. if (isNaN(this.rotation.y)) {
  46298. this.rotation.y = 0;
  46299. }
  46300. if (isNaN(this.rotation.z)) {
  46301. this.rotation.z = 0;
  46302. }
  46303. if (this.rotationQuaternion) {
  46304. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46305. }
  46306. };
  46307. /**
  46308. * Return the current target position of the camera. This value is expressed in local space.
  46309. */
  46310. TargetCamera.prototype.getTarget = function () {
  46311. return this._currentTarget;
  46312. };
  46313. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46314. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46315. };
  46316. TargetCamera.prototype._updatePosition = function () {
  46317. if (this.parent) {
  46318. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46319. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46320. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46321. return;
  46322. }
  46323. this.position.addInPlace(this.cameraDirection);
  46324. };
  46325. TargetCamera.prototype._checkInputs = function () {
  46326. var needToMove = this._decideIfNeedsToMove();
  46327. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46328. // Move
  46329. if (needToMove) {
  46330. this._updatePosition();
  46331. }
  46332. // Rotate
  46333. if (needToRotate) {
  46334. this.rotation.x += this.cameraRotation.x;
  46335. this.rotation.y += this.cameraRotation.y;
  46336. //rotate, if quaternion is set and rotation was used
  46337. if (this.rotationQuaternion) {
  46338. var len = this.rotation.lengthSquared();
  46339. if (len) {
  46340. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46341. }
  46342. }
  46343. if (!this.noRotationConstraint) {
  46344. var limit = (Math.PI / 2) * 0.95;
  46345. if (this.rotation.x > limit)
  46346. this.rotation.x = limit;
  46347. if (this.rotation.x < -limit)
  46348. this.rotation.x = -limit;
  46349. }
  46350. }
  46351. // Inertia
  46352. if (needToMove) {
  46353. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46354. this.cameraDirection.x = 0;
  46355. }
  46356. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46357. this.cameraDirection.y = 0;
  46358. }
  46359. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46360. this.cameraDirection.z = 0;
  46361. }
  46362. this.cameraDirection.scaleInPlace(this.inertia);
  46363. }
  46364. if (needToRotate) {
  46365. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46366. this.cameraRotation.x = 0;
  46367. }
  46368. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46369. this.cameraRotation.y = 0;
  46370. }
  46371. this.cameraRotation.scaleInPlace(this.inertia);
  46372. }
  46373. _super.prototype._checkInputs.call(this);
  46374. };
  46375. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46376. if (this.rotationQuaternion) {
  46377. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46378. }
  46379. else {
  46380. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46381. }
  46382. //update the up vector!
  46383. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46384. };
  46385. TargetCamera.prototype._getViewMatrix = function () {
  46386. if (this.lockedTarget) {
  46387. this.setTarget(this._getLockedTargetPosition());
  46388. }
  46389. // Compute
  46390. this._updateCameraRotationMatrix();
  46391. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46392. // Computing target and final matrix
  46393. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46394. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46395. return this._viewMatrix;
  46396. };
  46397. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46398. if (this.parent) {
  46399. var parentWorldMatrix = this.parent.getWorldMatrix();
  46400. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46401. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46402. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46403. this._markSyncedWithParent();
  46404. }
  46405. else {
  46406. this._globalPosition.copyFrom(this.position);
  46407. this._globalCurrentTarget.copyFrom(target);
  46408. this._globalCurrentUpVector.copyFrom(up);
  46409. }
  46410. if (this.getScene().useRightHandedSystem) {
  46411. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46412. }
  46413. else {
  46414. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46415. }
  46416. };
  46417. /**
  46418. * @override
  46419. * Override Camera.createRigCamera
  46420. */
  46421. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46422. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46423. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46424. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46425. if (!this.rotationQuaternion) {
  46426. this.rotationQuaternion = new BABYLON.Quaternion();
  46427. }
  46428. rigCamera._cameraRigParams = {};
  46429. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46430. }
  46431. return rigCamera;
  46432. }
  46433. return null;
  46434. };
  46435. /**
  46436. * @override
  46437. * Override Camera._updateRigCameras
  46438. */
  46439. TargetCamera.prototype._updateRigCameras = function () {
  46440. var camLeft = this._rigCameras[0];
  46441. var camRight = this._rigCameras[1];
  46442. switch (this.cameraRigMode) {
  46443. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46444. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46445. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46446. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46447. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46448. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46449. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46450. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46451. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46452. camLeft.setTarget(this.getTarget());
  46453. camRight.setTarget(this.getTarget());
  46454. break;
  46455. case BABYLON.Camera.RIG_MODE_VR:
  46456. if (camLeft.rotationQuaternion) {
  46457. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46458. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46459. }
  46460. else {
  46461. camLeft.rotation.copyFrom(this.rotation);
  46462. camRight.rotation.copyFrom(this.rotation);
  46463. }
  46464. camLeft.position.copyFrom(this.position);
  46465. camRight.position.copyFrom(this.position);
  46466. break;
  46467. }
  46468. _super.prototype._updateRigCameras.call(this);
  46469. };
  46470. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46471. if (!this._rigCamTransformMatrix) {
  46472. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46473. }
  46474. var target = this.getTarget();
  46475. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46476. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46477. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46478. };
  46479. TargetCamera.prototype.getClassName = function () {
  46480. return "TargetCamera";
  46481. };
  46482. __decorate([
  46483. BABYLON.serializeAsVector3()
  46484. ], TargetCamera.prototype, "rotation", void 0);
  46485. __decorate([
  46486. BABYLON.serialize()
  46487. ], TargetCamera.prototype, "speed", void 0);
  46488. __decorate([
  46489. BABYLON.serializeAsMeshReference("lockedTargetId")
  46490. ], TargetCamera.prototype, "lockedTarget", void 0);
  46491. return TargetCamera;
  46492. }(BABYLON.Camera));
  46493. BABYLON.TargetCamera = TargetCamera;
  46494. })(BABYLON || (BABYLON = {}));
  46495. //# sourceMappingURL=babylon.targetCamera.js.map
  46496. var BABYLON;
  46497. (function (BABYLON) {
  46498. var FreeCameraMouseInput = /** @class */ (function () {
  46499. function FreeCameraMouseInput(touchEnabled) {
  46500. if (touchEnabled === void 0) { touchEnabled = true; }
  46501. this.touchEnabled = touchEnabled;
  46502. this.buttons = [0, 1, 2];
  46503. this.angularSensibility = 2000.0;
  46504. this.previousPosition = null;
  46505. }
  46506. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46507. var _this = this;
  46508. var engine = this.camera.getEngine();
  46509. if (!this._pointerInput) {
  46510. this._pointerInput = function (p, s) {
  46511. var evt = p.event;
  46512. if (engine.isInVRExclusivePointerMode) {
  46513. return;
  46514. }
  46515. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46516. return;
  46517. }
  46518. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46519. return;
  46520. }
  46521. var srcElement = (evt.srcElement || evt.target);
  46522. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46523. try {
  46524. srcElement.setPointerCapture(evt.pointerId);
  46525. }
  46526. catch (e) {
  46527. //Nothing to do with the error. Execution will continue.
  46528. }
  46529. _this.previousPosition = {
  46530. x: evt.clientX,
  46531. y: evt.clientY
  46532. };
  46533. if (!noPreventDefault) {
  46534. evt.preventDefault();
  46535. element.focus();
  46536. }
  46537. }
  46538. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46539. try {
  46540. srcElement.releasePointerCapture(evt.pointerId);
  46541. }
  46542. catch (e) {
  46543. //Nothing to do with the error.
  46544. }
  46545. _this.previousPosition = null;
  46546. if (!noPreventDefault) {
  46547. evt.preventDefault();
  46548. }
  46549. }
  46550. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46551. if (!_this.previousPosition || engine.isPointerLock) {
  46552. return;
  46553. }
  46554. var offsetX = evt.clientX - _this.previousPosition.x;
  46555. if (_this.camera.getScene().useRightHandedSystem)
  46556. offsetX *= -1;
  46557. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46558. offsetX *= -1;
  46559. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46560. var offsetY = evt.clientY - _this.previousPosition.y;
  46561. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46562. _this.previousPosition = {
  46563. x: evt.clientX,
  46564. y: evt.clientY
  46565. };
  46566. if (!noPreventDefault) {
  46567. evt.preventDefault();
  46568. }
  46569. }
  46570. };
  46571. }
  46572. this._onMouseMove = function (evt) {
  46573. if (!engine.isPointerLock) {
  46574. return;
  46575. }
  46576. if (engine.isInVRExclusivePointerMode) {
  46577. return;
  46578. }
  46579. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46580. if (_this.camera.getScene().useRightHandedSystem)
  46581. offsetX *= -1;
  46582. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46583. offsetX *= -1;
  46584. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46585. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46586. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46587. _this.previousPosition = null;
  46588. if (!noPreventDefault) {
  46589. evt.preventDefault();
  46590. }
  46591. };
  46592. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46593. element.addEventListener("mousemove", this._onMouseMove, false);
  46594. };
  46595. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46596. if (this._observer && element) {
  46597. this.camera.getScene().onPointerObservable.remove(this._observer);
  46598. if (this._onMouseMove) {
  46599. element.removeEventListener("mousemove", this._onMouseMove);
  46600. }
  46601. this._observer = null;
  46602. this._onMouseMove = null;
  46603. this.previousPosition = null;
  46604. }
  46605. };
  46606. FreeCameraMouseInput.prototype.getClassName = function () {
  46607. return "FreeCameraMouseInput";
  46608. };
  46609. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46610. return "mouse";
  46611. };
  46612. __decorate([
  46613. BABYLON.serialize()
  46614. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46615. __decorate([
  46616. BABYLON.serialize()
  46617. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46618. return FreeCameraMouseInput;
  46619. }());
  46620. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46621. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46622. })(BABYLON || (BABYLON = {}));
  46623. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46624. var BABYLON;
  46625. (function (BABYLON) {
  46626. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46627. function FreeCameraKeyboardMoveInput() {
  46628. this._keys = new Array();
  46629. this.keysUp = [38];
  46630. this.keysDown = [40];
  46631. this.keysLeft = [37];
  46632. this.keysRight = [39];
  46633. }
  46634. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46635. var _this = this;
  46636. if (this._onCanvasBlurObserver) {
  46637. return;
  46638. }
  46639. this._scene = this.camera.getScene();
  46640. this._engine = this._scene.getEngine();
  46641. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46642. _this._keys = [];
  46643. });
  46644. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46645. var evt = info.event;
  46646. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46647. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46648. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46649. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46650. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46651. var index = _this._keys.indexOf(evt.keyCode);
  46652. if (index === -1) {
  46653. _this._keys.push(evt.keyCode);
  46654. }
  46655. if (!noPreventDefault) {
  46656. evt.preventDefault();
  46657. }
  46658. }
  46659. }
  46660. else {
  46661. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46662. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46663. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46664. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46665. var index = _this._keys.indexOf(evt.keyCode);
  46666. if (index >= 0) {
  46667. _this._keys.splice(index, 1);
  46668. }
  46669. if (!noPreventDefault) {
  46670. evt.preventDefault();
  46671. }
  46672. }
  46673. }
  46674. });
  46675. };
  46676. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46677. if (this._scene) {
  46678. if (this._onKeyboardObserver) {
  46679. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46680. }
  46681. if (this._onCanvasBlurObserver) {
  46682. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46683. }
  46684. this._onKeyboardObserver = null;
  46685. this._onCanvasBlurObserver = null;
  46686. }
  46687. this._keys = [];
  46688. };
  46689. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46690. if (this._onKeyboardObserver) {
  46691. var camera = this.camera;
  46692. // Keyboard
  46693. for (var index = 0; index < this._keys.length; index++) {
  46694. var keyCode = this._keys[index];
  46695. var speed = camera._computeLocalCameraSpeed();
  46696. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46697. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46698. }
  46699. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46700. camera._localDirection.copyFromFloats(0, 0, speed);
  46701. }
  46702. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46703. camera._localDirection.copyFromFloats(speed, 0, 0);
  46704. }
  46705. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46706. camera._localDirection.copyFromFloats(0, 0, -speed);
  46707. }
  46708. if (camera.getScene().useRightHandedSystem) {
  46709. camera._localDirection.z *= -1;
  46710. }
  46711. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46712. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46713. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46714. }
  46715. }
  46716. };
  46717. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46718. return "FreeCameraKeyboardMoveInput";
  46719. };
  46720. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46721. this._keys = [];
  46722. };
  46723. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46724. return "keyboard";
  46725. };
  46726. __decorate([
  46727. BABYLON.serialize()
  46728. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46729. __decorate([
  46730. BABYLON.serialize()
  46731. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46732. __decorate([
  46733. BABYLON.serialize()
  46734. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46735. __decorate([
  46736. BABYLON.serialize()
  46737. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46738. return FreeCameraKeyboardMoveInput;
  46739. }());
  46740. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46741. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46742. })(BABYLON || (BABYLON = {}));
  46743. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46744. var BABYLON;
  46745. (function (BABYLON) {
  46746. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46747. __extends(FreeCameraInputsManager, _super);
  46748. function FreeCameraInputsManager(camera) {
  46749. return _super.call(this, camera) || this;
  46750. }
  46751. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46752. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46753. return this;
  46754. };
  46755. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46756. if (touchEnabled === void 0) { touchEnabled = true; }
  46757. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46758. return this;
  46759. };
  46760. FreeCameraInputsManager.prototype.addGamepad = function () {
  46761. this.add(new BABYLON.FreeCameraGamepadInput());
  46762. return this;
  46763. };
  46764. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46765. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46766. return this;
  46767. };
  46768. FreeCameraInputsManager.prototype.addTouch = function () {
  46769. this.add(new BABYLON.FreeCameraTouchInput());
  46770. return this;
  46771. };
  46772. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46773. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46774. return this;
  46775. };
  46776. return FreeCameraInputsManager;
  46777. }(BABYLON.CameraInputsManager));
  46778. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46779. })(BABYLON || (BABYLON = {}));
  46780. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46781. var BABYLON;
  46782. (function (BABYLON) {
  46783. var FreeCamera = /** @class */ (function (_super) {
  46784. __extends(FreeCamera, _super);
  46785. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46786. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46787. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46788. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46789. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46790. _this.checkCollisions = false;
  46791. _this.applyGravity = false;
  46792. _this._needMoveForGravity = false;
  46793. _this._oldPosition = BABYLON.Vector3.Zero();
  46794. _this._diffPosition = BABYLON.Vector3.Zero();
  46795. _this._newPosition = BABYLON.Vector3.Zero();
  46796. // Collisions
  46797. _this._collisionMask = -1;
  46798. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46799. if (collidedMesh === void 0) { collidedMesh = null; }
  46800. //TODO move this to the collision coordinator!
  46801. if (_this.getScene().workerCollisions)
  46802. newPosition.multiplyInPlace(_this._collider._radius);
  46803. var updatePosition = function (newPos) {
  46804. _this._newPosition.copyFrom(newPos);
  46805. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46806. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46807. _this.position.addInPlace(_this._diffPosition);
  46808. if (_this.onCollide && collidedMesh) {
  46809. _this.onCollide(collidedMesh);
  46810. }
  46811. }
  46812. };
  46813. updatePosition(newPosition);
  46814. };
  46815. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46816. _this.inputs.addKeyboard().addMouse();
  46817. return _this;
  46818. }
  46819. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46820. //-- begin properties for backward compatibility for inputs
  46821. /**
  46822. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46823. * Higher values reduce sensitivity.
  46824. */
  46825. get: function () {
  46826. var mouse = this.inputs.attached["mouse"];
  46827. if (mouse)
  46828. return mouse.angularSensibility;
  46829. return 0;
  46830. },
  46831. /**
  46832. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46833. * Higher values reduce sensitivity.
  46834. */
  46835. set: function (value) {
  46836. var mouse = this.inputs.attached["mouse"];
  46837. if (mouse)
  46838. mouse.angularSensibility = value;
  46839. },
  46840. enumerable: true,
  46841. configurable: true
  46842. });
  46843. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46844. get: function () {
  46845. var keyboard = this.inputs.attached["keyboard"];
  46846. if (keyboard)
  46847. return keyboard.keysUp;
  46848. return [];
  46849. },
  46850. set: function (value) {
  46851. var keyboard = this.inputs.attached["keyboard"];
  46852. if (keyboard)
  46853. keyboard.keysUp = value;
  46854. },
  46855. enumerable: true,
  46856. configurable: true
  46857. });
  46858. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46859. get: function () {
  46860. var keyboard = this.inputs.attached["keyboard"];
  46861. if (keyboard)
  46862. return keyboard.keysDown;
  46863. return [];
  46864. },
  46865. set: function (value) {
  46866. var keyboard = this.inputs.attached["keyboard"];
  46867. if (keyboard)
  46868. keyboard.keysDown = value;
  46869. },
  46870. enumerable: true,
  46871. configurable: true
  46872. });
  46873. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46874. get: function () {
  46875. var keyboard = this.inputs.attached["keyboard"];
  46876. if (keyboard)
  46877. return keyboard.keysLeft;
  46878. return [];
  46879. },
  46880. set: function (value) {
  46881. var keyboard = this.inputs.attached["keyboard"];
  46882. if (keyboard)
  46883. keyboard.keysLeft = value;
  46884. },
  46885. enumerable: true,
  46886. configurable: true
  46887. });
  46888. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46889. get: function () {
  46890. var keyboard = this.inputs.attached["keyboard"];
  46891. if (keyboard)
  46892. return keyboard.keysRight;
  46893. return [];
  46894. },
  46895. set: function (value) {
  46896. var keyboard = this.inputs.attached["keyboard"];
  46897. if (keyboard)
  46898. keyboard.keysRight = value;
  46899. },
  46900. enumerable: true,
  46901. configurable: true
  46902. });
  46903. // Controls
  46904. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46905. this.inputs.attachElement(element, noPreventDefault);
  46906. };
  46907. FreeCamera.prototype.detachControl = function (element) {
  46908. this.inputs.detachElement(element);
  46909. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46910. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46911. };
  46912. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46913. get: function () {
  46914. return this._collisionMask;
  46915. },
  46916. set: function (mask) {
  46917. this._collisionMask = !isNaN(mask) ? mask : -1;
  46918. },
  46919. enumerable: true,
  46920. configurable: true
  46921. });
  46922. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46923. var globalPosition;
  46924. if (this.parent) {
  46925. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46926. }
  46927. else {
  46928. globalPosition = this.position;
  46929. }
  46930. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46931. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46932. if (!this._collider) {
  46933. this._collider = new BABYLON.Collider();
  46934. }
  46935. this._collider._radius = this.ellipsoid;
  46936. this._collider.collisionMask = this._collisionMask;
  46937. //no need for clone, as long as gravity is not on.
  46938. var actualDisplacement = displacement;
  46939. //add gravity to the direction to prevent the dual-collision checking
  46940. if (this.applyGravity) {
  46941. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46942. actualDisplacement = displacement.add(this.getScene().gravity);
  46943. }
  46944. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46945. };
  46946. FreeCamera.prototype._checkInputs = function () {
  46947. if (!this._localDirection) {
  46948. this._localDirection = BABYLON.Vector3.Zero();
  46949. this._transformedDirection = BABYLON.Vector3.Zero();
  46950. }
  46951. this.inputs.checkInputs();
  46952. _super.prototype._checkInputs.call(this);
  46953. };
  46954. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46955. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46956. };
  46957. FreeCamera.prototype._updatePosition = function () {
  46958. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46959. this._collideWithWorld(this.cameraDirection);
  46960. }
  46961. else {
  46962. _super.prototype._updatePosition.call(this);
  46963. }
  46964. };
  46965. FreeCamera.prototype.dispose = function () {
  46966. this.inputs.clear();
  46967. _super.prototype.dispose.call(this);
  46968. };
  46969. FreeCamera.prototype.getClassName = function () {
  46970. return "FreeCamera";
  46971. };
  46972. __decorate([
  46973. BABYLON.serializeAsVector3()
  46974. ], FreeCamera.prototype, "ellipsoid", void 0);
  46975. __decorate([
  46976. BABYLON.serializeAsVector3()
  46977. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46978. __decorate([
  46979. BABYLON.serialize()
  46980. ], FreeCamera.prototype, "checkCollisions", void 0);
  46981. __decorate([
  46982. BABYLON.serialize()
  46983. ], FreeCamera.prototype, "applyGravity", void 0);
  46984. return FreeCamera;
  46985. }(BABYLON.TargetCamera));
  46986. BABYLON.FreeCamera = FreeCamera;
  46987. })(BABYLON || (BABYLON = {}));
  46988. //# sourceMappingURL=babylon.freeCamera.js.map
  46989. var BABYLON;
  46990. (function (BABYLON) {
  46991. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46992. function ArcRotateCameraKeyboardMoveInput() {
  46993. this._keys = new Array();
  46994. this.keysUp = [38];
  46995. this.keysDown = [40];
  46996. this.keysLeft = [37];
  46997. this.keysRight = [39];
  46998. this.keysReset = [220];
  46999. this.panningSensibility = 50.0;
  47000. this.zoomingSensibility = 25.0;
  47001. this.useAltToZoom = true;
  47002. }
  47003. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47004. var _this = this;
  47005. if (this._onCanvasBlurObserver) {
  47006. return;
  47007. }
  47008. this._scene = this.camera.getScene();
  47009. this._engine = this._scene.getEngine();
  47010. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47011. _this._keys = [];
  47012. });
  47013. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47014. var evt = info.event;
  47015. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47016. _this._ctrlPressed = evt.ctrlKey;
  47017. _this._altPressed = evt.altKey;
  47018. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47019. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47020. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47021. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47022. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47023. var index = _this._keys.indexOf(evt.keyCode);
  47024. if (index === -1) {
  47025. _this._keys.push(evt.keyCode);
  47026. }
  47027. if (evt.preventDefault) {
  47028. if (!noPreventDefault) {
  47029. evt.preventDefault();
  47030. }
  47031. }
  47032. }
  47033. }
  47034. else {
  47035. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47036. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47037. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47038. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47039. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47040. var index = _this._keys.indexOf(evt.keyCode);
  47041. if (index >= 0) {
  47042. _this._keys.splice(index, 1);
  47043. }
  47044. if (evt.preventDefault) {
  47045. if (!noPreventDefault) {
  47046. evt.preventDefault();
  47047. }
  47048. }
  47049. }
  47050. }
  47051. });
  47052. };
  47053. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47054. if (this._scene) {
  47055. if (this._onKeyboardObserver) {
  47056. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47057. }
  47058. if (this._onCanvasBlurObserver) {
  47059. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47060. }
  47061. this._onKeyboardObserver = null;
  47062. this._onCanvasBlurObserver = null;
  47063. }
  47064. this._keys = [];
  47065. };
  47066. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47067. if (this._onKeyboardObserver) {
  47068. var camera = this.camera;
  47069. for (var index = 0; index < this._keys.length; index++) {
  47070. var keyCode = this._keys[index];
  47071. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47072. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47073. camera.inertialPanningX -= 1 / this.panningSensibility;
  47074. }
  47075. else {
  47076. camera.inertialAlphaOffset -= 0.01;
  47077. }
  47078. }
  47079. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47080. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47081. camera.inertialPanningY += 1 / this.panningSensibility;
  47082. }
  47083. else if (this._altPressed && this.useAltToZoom) {
  47084. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47085. }
  47086. else {
  47087. camera.inertialBetaOffset -= 0.01;
  47088. }
  47089. }
  47090. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47091. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47092. camera.inertialPanningX += 1 / this.panningSensibility;
  47093. }
  47094. else {
  47095. camera.inertialAlphaOffset += 0.01;
  47096. }
  47097. }
  47098. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47099. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47100. camera.inertialPanningY -= 1 / this.panningSensibility;
  47101. }
  47102. else if (this._altPressed && this.useAltToZoom) {
  47103. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47104. }
  47105. else {
  47106. camera.inertialBetaOffset += 0.01;
  47107. }
  47108. }
  47109. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47110. camera.restoreState();
  47111. }
  47112. }
  47113. }
  47114. };
  47115. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47116. return "ArcRotateCameraKeyboardMoveInput";
  47117. };
  47118. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47119. return "keyboard";
  47120. };
  47121. __decorate([
  47122. BABYLON.serialize()
  47123. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47124. __decorate([
  47125. BABYLON.serialize()
  47126. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47127. __decorate([
  47128. BABYLON.serialize()
  47129. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47130. __decorate([
  47131. BABYLON.serialize()
  47132. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47133. __decorate([
  47134. BABYLON.serialize()
  47135. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47136. __decorate([
  47137. BABYLON.serialize()
  47138. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47139. __decorate([
  47140. BABYLON.serialize()
  47141. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47142. __decorate([
  47143. BABYLON.serialize()
  47144. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47145. return ArcRotateCameraKeyboardMoveInput;
  47146. }());
  47147. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47148. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47149. })(BABYLON || (BABYLON = {}));
  47150. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47151. var BABYLON;
  47152. (function (BABYLON) {
  47153. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47154. function ArcRotateCameraMouseWheelInput() {
  47155. this.wheelPrecision = 3.0;
  47156. /**
  47157. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47158. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47159. */
  47160. this.wheelDeltaPercentage = 0;
  47161. }
  47162. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47163. var _this = this;
  47164. this._wheel = function (p, s) {
  47165. //sanity check - this should be a PointerWheel event.
  47166. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47167. return;
  47168. var event = p.event;
  47169. var delta = 0;
  47170. if (event.wheelDelta) {
  47171. if (_this.wheelDeltaPercentage) {
  47172. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47173. if (event.wheelDelta > 0) {
  47174. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47175. }
  47176. else {
  47177. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47178. }
  47179. }
  47180. else {
  47181. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47182. }
  47183. }
  47184. else if (event.detail) {
  47185. delta = -event.detail / _this.wheelPrecision;
  47186. }
  47187. if (delta)
  47188. _this.camera.inertialRadiusOffset += delta;
  47189. if (event.preventDefault) {
  47190. if (!noPreventDefault) {
  47191. event.preventDefault();
  47192. }
  47193. }
  47194. };
  47195. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47196. };
  47197. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47198. if (this._observer && element) {
  47199. this.camera.getScene().onPointerObservable.remove(this._observer);
  47200. this._observer = null;
  47201. this._wheel = null;
  47202. }
  47203. };
  47204. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47205. return "ArcRotateCameraMouseWheelInput";
  47206. };
  47207. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47208. return "mousewheel";
  47209. };
  47210. __decorate([
  47211. BABYLON.serialize()
  47212. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47213. __decorate([
  47214. BABYLON.serialize()
  47215. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47216. return ArcRotateCameraMouseWheelInput;
  47217. }());
  47218. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47219. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47220. })(BABYLON || (BABYLON = {}));
  47221. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47222. var BABYLON;
  47223. (function (BABYLON) {
  47224. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47225. function ArcRotateCameraPointersInput() {
  47226. this.buttons = [0, 1, 2];
  47227. this.angularSensibilityX = 1000.0;
  47228. this.angularSensibilityY = 1000.0;
  47229. this.pinchPrecision = 12.0;
  47230. /**
  47231. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47232. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47233. */
  47234. this.pinchDeltaPercentage = 0;
  47235. this.panningSensibility = 1000.0;
  47236. this.multiTouchPanning = true;
  47237. this.multiTouchPanAndZoom = true;
  47238. this._isPanClick = false;
  47239. this.pinchInwards = true;
  47240. }
  47241. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47242. var _this = this;
  47243. var engine = this.camera.getEngine();
  47244. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47245. var pointA = null;
  47246. var pointB = null;
  47247. var previousPinchSquaredDistance = 0;
  47248. var initialDistance = 0;
  47249. var twoFingerActivityCount = 0;
  47250. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47251. this._pointerInput = function (p, s) {
  47252. var evt = p.event;
  47253. var isTouch = p.event.pointerType === "touch";
  47254. if (engine.isInVRExclusivePointerMode) {
  47255. return;
  47256. }
  47257. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47258. return;
  47259. }
  47260. var srcElement = (evt.srcElement || evt.target);
  47261. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47262. try {
  47263. srcElement.setPointerCapture(evt.pointerId);
  47264. }
  47265. catch (e) {
  47266. //Nothing to do with the error. Execution will continue.
  47267. }
  47268. // Manage panning with pan button click
  47269. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47270. // manage pointers
  47271. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47272. if (pointA === null) {
  47273. pointA = cacheSoloPointer;
  47274. }
  47275. else if (pointB === null) {
  47276. pointB = cacheSoloPointer;
  47277. }
  47278. if (!noPreventDefault) {
  47279. evt.preventDefault();
  47280. element.focus();
  47281. }
  47282. }
  47283. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47284. _this.camera.restoreState();
  47285. }
  47286. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47287. try {
  47288. srcElement.releasePointerCapture(evt.pointerId);
  47289. }
  47290. catch (e) {
  47291. //Nothing to do with the error.
  47292. }
  47293. cacheSoloPointer = null;
  47294. previousPinchSquaredDistance = 0;
  47295. previousMultiTouchPanPosition.isPaning = false;
  47296. previousMultiTouchPanPosition.isPinching = false;
  47297. twoFingerActivityCount = 0;
  47298. initialDistance = 0;
  47299. if (!isTouch) {
  47300. pointB = null; // Mouse and pen are mono pointer
  47301. }
  47302. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47303. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47304. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47305. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47306. if (engine._badOS) {
  47307. pointA = pointB = null;
  47308. }
  47309. else {
  47310. //only remove the impacted pointer in case of multitouch allowing on most
  47311. //platforms switching from rotate to zoom and pan seamlessly.
  47312. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47313. pointA = pointB;
  47314. pointB = null;
  47315. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47316. }
  47317. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47318. pointB = null;
  47319. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47320. }
  47321. else {
  47322. pointA = pointB = null;
  47323. }
  47324. }
  47325. if (!noPreventDefault) {
  47326. evt.preventDefault();
  47327. }
  47328. }
  47329. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47330. if (!noPreventDefault) {
  47331. evt.preventDefault();
  47332. }
  47333. // One button down
  47334. if (pointA && pointB === null && cacheSoloPointer) {
  47335. if (_this.panningSensibility !== 0 &&
  47336. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47337. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47338. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47339. }
  47340. else {
  47341. var offsetX = evt.clientX - cacheSoloPointer.x;
  47342. var offsetY = evt.clientY - cacheSoloPointer.y;
  47343. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47344. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47345. }
  47346. cacheSoloPointer.x = evt.clientX;
  47347. cacheSoloPointer.y = evt.clientY;
  47348. }
  47349. // Two buttons down: pinch/pan
  47350. else if (pointA && pointB) {
  47351. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47352. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47353. ed.x = evt.clientX;
  47354. ed.y = evt.clientY;
  47355. var direction = _this.pinchInwards ? 1 : -1;
  47356. var distX = pointA.x - pointB.x;
  47357. var distY = pointA.y - pointB.y;
  47358. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47359. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47360. if (previousPinchSquaredDistance === 0) {
  47361. initialDistance = pinchDistance;
  47362. previousPinchSquaredDistance = pinchSquaredDistance;
  47363. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47364. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47365. return;
  47366. }
  47367. if (_this.multiTouchPanAndZoom) {
  47368. if (_this.pinchDeltaPercentage) {
  47369. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47370. }
  47371. else {
  47372. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47373. (_this.pinchPrecision *
  47374. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47375. direction);
  47376. }
  47377. if (_this.panningSensibility !== 0) {
  47378. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47379. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47380. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47381. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47382. previousMultiTouchPanPosition.x = pointersCenterX;
  47383. previousMultiTouchPanPosition.y = pointersCenterY;
  47384. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47385. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47386. }
  47387. }
  47388. else {
  47389. twoFingerActivityCount++;
  47390. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47391. if (_this.pinchDeltaPercentage) {
  47392. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47393. }
  47394. else {
  47395. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47396. (_this.pinchPrecision *
  47397. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47398. direction);
  47399. }
  47400. previousMultiTouchPanPosition.isPaning = false;
  47401. previousMultiTouchPanPosition.isPinching = true;
  47402. }
  47403. else {
  47404. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47405. if (!previousMultiTouchPanPosition.isPaning) {
  47406. previousMultiTouchPanPosition.isPaning = true;
  47407. previousMultiTouchPanPosition.isPinching = false;
  47408. previousMultiTouchPanPosition.x = ed.x;
  47409. previousMultiTouchPanPosition.y = ed.y;
  47410. return;
  47411. }
  47412. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47413. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47414. }
  47415. }
  47416. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47417. previousMultiTouchPanPosition.x = ed.x;
  47418. previousMultiTouchPanPosition.y = ed.y;
  47419. }
  47420. }
  47421. previousPinchSquaredDistance = pinchSquaredDistance;
  47422. }
  47423. }
  47424. };
  47425. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47426. this._onContextMenu = function (evt) {
  47427. evt.preventDefault();
  47428. };
  47429. if (!this.camera._useCtrlForPanning) {
  47430. element.addEventListener("contextmenu", this._onContextMenu, false);
  47431. }
  47432. this._onLostFocus = function () {
  47433. //this._keys = [];
  47434. pointA = pointB = null;
  47435. previousPinchSquaredDistance = 0;
  47436. previousMultiTouchPanPosition.isPaning = false;
  47437. previousMultiTouchPanPosition.isPinching = false;
  47438. twoFingerActivityCount = 0;
  47439. cacheSoloPointer = null;
  47440. initialDistance = 0;
  47441. };
  47442. this._onMouseMove = function (evt) {
  47443. if (!engine.isPointerLock) {
  47444. return;
  47445. }
  47446. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47447. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47448. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47449. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47450. if (!noPreventDefault) {
  47451. evt.preventDefault();
  47452. }
  47453. };
  47454. this._onGestureStart = function (e) {
  47455. if (window.MSGesture === undefined) {
  47456. return;
  47457. }
  47458. if (!_this._MSGestureHandler) {
  47459. _this._MSGestureHandler = new MSGesture();
  47460. _this._MSGestureHandler.target = element;
  47461. }
  47462. _this._MSGestureHandler.addPointer(e.pointerId);
  47463. };
  47464. this._onGesture = function (e) {
  47465. _this.camera.radius *= e.scale;
  47466. if (e.preventDefault) {
  47467. if (!noPreventDefault) {
  47468. e.stopPropagation();
  47469. e.preventDefault();
  47470. }
  47471. }
  47472. };
  47473. element.addEventListener("mousemove", this._onMouseMove, false);
  47474. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47475. element.addEventListener("MSGestureChange", this._onGesture, false);
  47476. BABYLON.Tools.RegisterTopRootEvents([
  47477. { name: "blur", handler: this._onLostFocus }
  47478. ]);
  47479. };
  47480. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47481. if (this._onLostFocus) {
  47482. BABYLON.Tools.UnregisterTopRootEvents([
  47483. { name: "blur", handler: this._onLostFocus }
  47484. ]);
  47485. }
  47486. if (element && this._observer) {
  47487. this.camera.getScene().onPointerObservable.remove(this._observer);
  47488. this._observer = null;
  47489. if (this._onContextMenu) {
  47490. element.removeEventListener("contextmenu", this._onContextMenu);
  47491. }
  47492. if (this._onMouseMove) {
  47493. element.removeEventListener("mousemove", this._onMouseMove);
  47494. }
  47495. if (this._onGestureStart) {
  47496. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47497. }
  47498. if (this._onGesture) {
  47499. element.removeEventListener("MSGestureChange", this._onGesture);
  47500. }
  47501. this._isPanClick = false;
  47502. this.pinchInwards = true;
  47503. this._onMouseMove = null;
  47504. this._onGestureStart = null;
  47505. this._onGesture = null;
  47506. this._MSGestureHandler = null;
  47507. this._onLostFocus = null;
  47508. this._onContextMenu = null;
  47509. }
  47510. };
  47511. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47512. return "ArcRotateCameraPointersInput";
  47513. };
  47514. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47515. return "pointers";
  47516. };
  47517. __decorate([
  47518. BABYLON.serialize()
  47519. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47520. __decorate([
  47521. BABYLON.serialize()
  47522. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47523. __decorate([
  47524. BABYLON.serialize()
  47525. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47526. __decorate([
  47527. BABYLON.serialize()
  47528. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47529. __decorate([
  47530. BABYLON.serialize()
  47531. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47532. __decorate([
  47533. BABYLON.serialize()
  47534. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47535. __decorate([
  47536. BABYLON.serialize()
  47537. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47538. __decorate([
  47539. BABYLON.serialize()
  47540. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47541. return ArcRotateCameraPointersInput;
  47542. }());
  47543. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47544. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47545. })(BABYLON || (BABYLON = {}));
  47546. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47547. var BABYLON;
  47548. (function (BABYLON) {
  47549. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47550. __extends(ArcRotateCameraInputsManager, _super);
  47551. function ArcRotateCameraInputsManager(camera) {
  47552. return _super.call(this, camera) || this;
  47553. }
  47554. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47555. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47556. return this;
  47557. };
  47558. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47559. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47560. return this;
  47561. };
  47562. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47563. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47564. return this;
  47565. };
  47566. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47567. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47568. return this;
  47569. };
  47570. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47571. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47572. return this;
  47573. };
  47574. return ArcRotateCameraInputsManager;
  47575. }(BABYLON.CameraInputsManager));
  47576. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47577. })(BABYLON || (BABYLON = {}));
  47578. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47579. var BABYLON;
  47580. (function (BABYLON) {
  47581. var ArcRotateCamera = /** @class */ (function (_super) {
  47582. __extends(ArcRotateCamera, _super);
  47583. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47584. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47585. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47586. _this.inertialAlphaOffset = 0;
  47587. _this.inertialBetaOffset = 0;
  47588. _this.inertialRadiusOffset = 0;
  47589. _this.lowerAlphaLimit = null;
  47590. _this.upperAlphaLimit = null;
  47591. _this.lowerBetaLimit = 0.01;
  47592. _this.upperBetaLimit = Math.PI;
  47593. _this.lowerRadiusLimit = null;
  47594. _this.upperRadiusLimit = null;
  47595. _this.inertialPanningX = 0;
  47596. _this.inertialPanningY = 0;
  47597. _this.pinchToPanMaxDistance = 20;
  47598. _this.panningDistanceLimit = null;
  47599. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47600. _this.panningInertia = 0.9;
  47601. //-- end properties for backward compatibility for inputs
  47602. _this.zoomOnFactor = 1;
  47603. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47604. _this.allowUpsideDown = true;
  47605. _this._viewMatrix = new BABYLON.Matrix();
  47606. // Panning
  47607. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47608. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47609. _this.checkCollisions = false;
  47610. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47611. _this._previousPosition = BABYLON.Vector3.Zero();
  47612. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47613. _this._newPosition = BABYLON.Vector3.Zero();
  47614. _this._computationVector = BABYLON.Vector3.Zero();
  47615. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47616. if (collidedMesh === void 0) { collidedMesh = null; }
  47617. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47618. newPosition.multiplyInPlace(_this._collider._radius);
  47619. }
  47620. if (!collidedMesh) {
  47621. _this._previousPosition.copyFrom(_this.position);
  47622. }
  47623. else {
  47624. _this.setPosition(newPosition);
  47625. if (_this.onCollide) {
  47626. _this.onCollide(collidedMesh);
  47627. }
  47628. }
  47629. // Recompute because of constraints
  47630. var cosa = Math.cos(_this.alpha);
  47631. var sina = Math.sin(_this.alpha);
  47632. var cosb = Math.cos(_this.beta);
  47633. var sinb = Math.sin(_this.beta);
  47634. if (sinb === 0) {
  47635. sinb = 0.0001;
  47636. }
  47637. var target = _this._getTargetPosition();
  47638. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47639. target.addToRef(_this._computationVector, _this._newPosition);
  47640. _this.position.copyFrom(_this._newPosition);
  47641. var up = _this.upVector;
  47642. if (_this.allowUpsideDown && _this.beta < 0) {
  47643. up = up.clone();
  47644. up = up.negate();
  47645. }
  47646. _this._computeViewMatrix(_this.position, target, up);
  47647. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47648. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47649. _this._collisionTriggered = false;
  47650. };
  47651. _this._target = BABYLON.Vector3.Zero();
  47652. if (target) {
  47653. _this.setTarget(target);
  47654. }
  47655. _this.alpha = alpha;
  47656. _this.beta = beta;
  47657. _this.radius = radius;
  47658. _this.getViewMatrix();
  47659. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47660. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47661. return _this;
  47662. }
  47663. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47664. get: function () {
  47665. return this._target;
  47666. },
  47667. set: function (value) {
  47668. this.setTarget(value);
  47669. },
  47670. enumerable: true,
  47671. configurable: true
  47672. });
  47673. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47674. //-- begin properties for backward compatibility for inputs
  47675. get: function () {
  47676. var pointers = this.inputs.attached["pointers"];
  47677. if (pointers)
  47678. return pointers.angularSensibilityX;
  47679. return 0;
  47680. },
  47681. set: function (value) {
  47682. var pointers = this.inputs.attached["pointers"];
  47683. if (pointers) {
  47684. pointers.angularSensibilityX = value;
  47685. }
  47686. },
  47687. enumerable: true,
  47688. configurable: true
  47689. });
  47690. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47691. get: function () {
  47692. var pointers = this.inputs.attached["pointers"];
  47693. if (pointers)
  47694. return pointers.angularSensibilityY;
  47695. return 0;
  47696. },
  47697. set: function (value) {
  47698. var pointers = this.inputs.attached["pointers"];
  47699. if (pointers) {
  47700. pointers.angularSensibilityY = value;
  47701. }
  47702. },
  47703. enumerable: true,
  47704. configurable: true
  47705. });
  47706. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47707. get: function () {
  47708. var pointers = this.inputs.attached["pointers"];
  47709. if (pointers)
  47710. return pointers.pinchPrecision;
  47711. return 0;
  47712. },
  47713. set: function (value) {
  47714. var pointers = this.inputs.attached["pointers"];
  47715. if (pointers) {
  47716. pointers.pinchPrecision = value;
  47717. }
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47723. get: function () {
  47724. var pointers = this.inputs.attached["pointers"];
  47725. if (pointers)
  47726. return pointers.pinchDeltaPercentage;
  47727. return 0;
  47728. },
  47729. set: function (value) {
  47730. var pointers = this.inputs.attached["pointers"];
  47731. if (pointers) {
  47732. pointers.pinchDeltaPercentage = value;
  47733. }
  47734. },
  47735. enumerable: true,
  47736. configurable: true
  47737. });
  47738. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47739. get: function () {
  47740. var pointers = this.inputs.attached["pointers"];
  47741. if (pointers)
  47742. return pointers.panningSensibility;
  47743. return 0;
  47744. },
  47745. set: function (value) {
  47746. var pointers = this.inputs.attached["pointers"];
  47747. if (pointers) {
  47748. pointers.panningSensibility = value;
  47749. }
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47755. get: function () {
  47756. var keyboard = this.inputs.attached["keyboard"];
  47757. if (keyboard)
  47758. return keyboard.keysUp;
  47759. return [];
  47760. },
  47761. set: function (value) {
  47762. var keyboard = this.inputs.attached["keyboard"];
  47763. if (keyboard)
  47764. keyboard.keysUp = value;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47770. get: function () {
  47771. var keyboard = this.inputs.attached["keyboard"];
  47772. if (keyboard)
  47773. return keyboard.keysDown;
  47774. return [];
  47775. },
  47776. set: function (value) {
  47777. var keyboard = this.inputs.attached["keyboard"];
  47778. if (keyboard)
  47779. keyboard.keysDown = value;
  47780. },
  47781. enumerable: true,
  47782. configurable: true
  47783. });
  47784. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47785. get: function () {
  47786. var keyboard = this.inputs.attached["keyboard"];
  47787. if (keyboard)
  47788. return keyboard.keysLeft;
  47789. return [];
  47790. },
  47791. set: function (value) {
  47792. var keyboard = this.inputs.attached["keyboard"];
  47793. if (keyboard)
  47794. keyboard.keysLeft = value;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47800. get: function () {
  47801. var keyboard = this.inputs.attached["keyboard"];
  47802. if (keyboard)
  47803. return keyboard.keysRight;
  47804. return [];
  47805. },
  47806. set: function (value) {
  47807. var keyboard = this.inputs.attached["keyboard"];
  47808. if (keyboard)
  47809. keyboard.keysRight = value;
  47810. },
  47811. enumerable: true,
  47812. configurable: true
  47813. });
  47814. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47815. get: function () {
  47816. var mousewheel = this.inputs.attached["mousewheel"];
  47817. if (mousewheel)
  47818. return mousewheel.wheelPrecision;
  47819. return 0;
  47820. },
  47821. set: function (value) {
  47822. var mousewheel = this.inputs.attached["mousewheel"];
  47823. if (mousewheel)
  47824. mousewheel.wheelPrecision = value;
  47825. },
  47826. enumerable: true,
  47827. configurable: true
  47828. });
  47829. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47830. get: function () {
  47831. var mousewheel = this.inputs.attached["mousewheel"];
  47832. if (mousewheel)
  47833. return mousewheel.wheelDeltaPercentage;
  47834. return 0;
  47835. },
  47836. set: function (value) {
  47837. var mousewheel = this.inputs.attached["mousewheel"];
  47838. if (mousewheel)
  47839. mousewheel.wheelDeltaPercentage = value;
  47840. },
  47841. enumerable: true,
  47842. configurable: true
  47843. });
  47844. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47845. get: function () {
  47846. return this._bouncingBehavior;
  47847. },
  47848. enumerable: true,
  47849. configurable: true
  47850. });
  47851. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47852. get: function () {
  47853. return this._bouncingBehavior != null;
  47854. },
  47855. set: function (value) {
  47856. if (value === this.useBouncingBehavior) {
  47857. return;
  47858. }
  47859. if (value) {
  47860. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47861. this.addBehavior(this._bouncingBehavior);
  47862. }
  47863. else if (this._bouncingBehavior) {
  47864. this.removeBehavior(this._bouncingBehavior);
  47865. this._bouncingBehavior = null;
  47866. }
  47867. },
  47868. enumerable: true,
  47869. configurable: true
  47870. });
  47871. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47872. get: function () {
  47873. return this._framingBehavior;
  47874. },
  47875. enumerable: true,
  47876. configurable: true
  47877. });
  47878. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47879. get: function () {
  47880. return this._framingBehavior != null;
  47881. },
  47882. set: function (value) {
  47883. if (value === this.useFramingBehavior) {
  47884. return;
  47885. }
  47886. if (value) {
  47887. this._framingBehavior = new BABYLON.FramingBehavior();
  47888. this.addBehavior(this._framingBehavior);
  47889. }
  47890. else if (this._framingBehavior) {
  47891. this.removeBehavior(this._framingBehavior);
  47892. this._framingBehavior = null;
  47893. }
  47894. },
  47895. enumerable: true,
  47896. configurable: true
  47897. });
  47898. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47899. get: function () {
  47900. return this._autoRotationBehavior;
  47901. },
  47902. enumerable: true,
  47903. configurable: true
  47904. });
  47905. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47906. get: function () {
  47907. return this._autoRotationBehavior != null;
  47908. },
  47909. set: function (value) {
  47910. if (value === this.useAutoRotationBehavior) {
  47911. return;
  47912. }
  47913. if (value) {
  47914. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47915. this.addBehavior(this._autoRotationBehavior);
  47916. }
  47917. else if (this._autoRotationBehavior) {
  47918. this.removeBehavior(this._autoRotationBehavior);
  47919. this._autoRotationBehavior = null;
  47920. }
  47921. },
  47922. enumerable: true,
  47923. configurable: true
  47924. });
  47925. // Cache
  47926. ArcRotateCamera.prototype._initCache = function () {
  47927. _super.prototype._initCache.call(this);
  47928. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47929. this._cache.alpha = undefined;
  47930. this._cache.beta = undefined;
  47931. this._cache.radius = undefined;
  47932. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47933. };
  47934. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47935. if (!ignoreParentClass) {
  47936. _super.prototype._updateCache.call(this);
  47937. }
  47938. this._cache._target.copyFrom(this._getTargetPosition());
  47939. this._cache.alpha = this.alpha;
  47940. this._cache.beta = this.beta;
  47941. this._cache.radius = this.radius;
  47942. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47943. };
  47944. ArcRotateCamera.prototype._getTargetPosition = function () {
  47945. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47946. var pos = this._targetHost.getAbsolutePosition();
  47947. if (this._targetBoundingCenter) {
  47948. pos.addToRef(this._targetBoundingCenter, this._target);
  47949. }
  47950. else {
  47951. this._target.copyFrom(pos);
  47952. }
  47953. }
  47954. var lockedTargetPosition = this._getLockedTargetPosition();
  47955. if (lockedTargetPosition) {
  47956. return lockedTargetPosition;
  47957. }
  47958. return this._target;
  47959. };
  47960. ArcRotateCamera.prototype.storeState = function () {
  47961. this._storedAlpha = this.alpha;
  47962. this._storedBeta = this.beta;
  47963. this._storedRadius = this.radius;
  47964. this._storedTarget = this._getTargetPosition().clone();
  47965. return _super.prototype.storeState.call(this);
  47966. };
  47967. /**
  47968. * Restored camera state. You must call storeState() first
  47969. */
  47970. ArcRotateCamera.prototype._restoreStateValues = function () {
  47971. if (!_super.prototype._restoreStateValues.call(this)) {
  47972. return false;
  47973. }
  47974. this.alpha = this._storedAlpha;
  47975. this.beta = this._storedBeta;
  47976. this.radius = this._storedRadius;
  47977. this.setTarget(this._storedTarget.clone());
  47978. this.inertialAlphaOffset = 0;
  47979. this.inertialBetaOffset = 0;
  47980. this.inertialRadiusOffset = 0;
  47981. this.inertialPanningX = 0;
  47982. this.inertialPanningY = 0;
  47983. return true;
  47984. };
  47985. // Synchronized
  47986. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47987. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47988. return false;
  47989. return this._cache._target.equals(this._getTargetPosition())
  47990. && this._cache.alpha === this.alpha
  47991. && this._cache.beta === this.beta
  47992. && this._cache.radius === this.radius
  47993. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47994. };
  47995. // Methods
  47996. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47997. var _this = this;
  47998. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47999. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48000. this._useCtrlForPanning = useCtrlForPanning;
  48001. this._panningMouseButton = panningMouseButton;
  48002. this.inputs.attachElement(element, noPreventDefault);
  48003. this._reset = function () {
  48004. _this.inertialAlphaOffset = 0;
  48005. _this.inertialBetaOffset = 0;
  48006. _this.inertialRadiusOffset = 0;
  48007. _this.inertialPanningX = 0;
  48008. _this.inertialPanningY = 0;
  48009. };
  48010. };
  48011. ArcRotateCamera.prototype.detachControl = function (element) {
  48012. this.inputs.detachElement(element);
  48013. if (this._reset) {
  48014. this._reset();
  48015. }
  48016. };
  48017. ArcRotateCamera.prototype._checkInputs = function () {
  48018. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48019. if (this._collisionTriggered) {
  48020. return;
  48021. }
  48022. this.inputs.checkInputs();
  48023. // Inertia
  48024. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48025. var inertialAlphaOffset = this.inertialAlphaOffset;
  48026. if (this.beta <= 0)
  48027. inertialAlphaOffset *= -1;
  48028. if (this.getScene().useRightHandedSystem)
  48029. inertialAlphaOffset *= -1;
  48030. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48031. inertialAlphaOffset *= -1;
  48032. this.alpha += inertialAlphaOffset;
  48033. this.beta += this.inertialBetaOffset;
  48034. this.radius -= this.inertialRadiusOffset;
  48035. this.inertialAlphaOffset *= this.inertia;
  48036. this.inertialBetaOffset *= this.inertia;
  48037. this.inertialRadiusOffset *= this.inertia;
  48038. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48039. this.inertialAlphaOffset = 0;
  48040. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48041. this.inertialBetaOffset = 0;
  48042. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48043. this.inertialRadiusOffset = 0;
  48044. }
  48045. // Panning inertia
  48046. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48047. if (!this._localDirection) {
  48048. this._localDirection = BABYLON.Vector3.Zero();
  48049. this._transformedDirection = BABYLON.Vector3.Zero();
  48050. }
  48051. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48052. this._localDirection.multiplyInPlace(this.panningAxis);
  48053. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48054. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48055. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48056. if (!this.panningAxis.y) {
  48057. this._transformedDirection.y = 0;
  48058. }
  48059. if (!this._targetHost) {
  48060. if (this.panningDistanceLimit) {
  48061. this._transformedDirection.addInPlace(this._target);
  48062. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48063. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48064. this._target.copyFrom(this._transformedDirection);
  48065. }
  48066. }
  48067. else {
  48068. this._target.addInPlace(this._transformedDirection);
  48069. }
  48070. }
  48071. this.inertialPanningX *= this.panningInertia;
  48072. this.inertialPanningY *= this.panningInertia;
  48073. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48074. this.inertialPanningX = 0;
  48075. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48076. this.inertialPanningY = 0;
  48077. }
  48078. // Limits
  48079. this._checkLimits();
  48080. _super.prototype._checkInputs.call(this);
  48081. };
  48082. ArcRotateCamera.prototype._checkLimits = function () {
  48083. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48084. if (this.allowUpsideDown && this.beta > Math.PI) {
  48085. this.beta = this.beta - (2 * Math.PI);
  48086. }
  48087. }
  48088. else {
  48089. if (this.beta < this.lowerBetaLimit) {
  48090. this.beta = this.lowerBetaLimit;
  48091. }
  48092. }
  48093. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48094. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48095. this.beta = this.beta + (2 * Math.PI);
  48096. }
  48097. }
  48098. else {
  48099. if (this.beta > this.upperBetaLimit) {
  48100. this.beta = this.upperBetaLimit;
  48101. }
  48102. }
  48103. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48104. this.alpha = this.lowerAlphaLimit;
  48105. }
  48106. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48107. this.alpha = this.upperAlphaLimit;
  48108. }
  48109. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48110. this.radius = this.lowerRadiusLimit;
  48111. }
  48112. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48113. this.radius = this.upperRadiusLimit;
  48114. }
  48115. };
  48116. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48117. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48118. this.radius = this._computationVector.length();
  48119. if (this.radius === 0) {
  48120. this.radius = 0.0001; // Just to avoid division by zero
  48121. }
  48122. // Alpha
  48123. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48124. if (this._computationVector.z < 0) {
  48125. this.alpha = 2 * Math.PI - this.alpha;
  48126. }
  48127. // Beta
  48128. this.beta = Math.acos(this._computationVector.y / this.radius);
  48129. this._checkLimits();
  48130. };
  48131. ArcRotateCamera.prototype.setPosition = function (position) {
  48132. if (this.position.equals(position)) {
  48133. return;
  48134. }
  48135. this.position.copyFrom(position);
  48136. this.rebuildAnglesAndRadius();
  48137. };
  48138. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48139. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48140. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48141. if (target.getBoundingInfo) {
  48142. if (toBoundingCenter) {
  48143. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48144. }
  48145. else {
  48146. this._targetBoundingCenter = null;
  48147. }
  48148. this._targetHost = target;
  48149. this._target = this._getTargetPosition();
  48150. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48151. }
  48152. else {
  48153. var newTarget = target;
  48154. var currentTarget = this._getTargetPosition();
  48155. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48156. return;
  48157. }
  48158. this._targetHost = null;
  48159. this._target = newTarget;
  48160. this._targetBoundingCenter = null;
  48161. this.onMeshTargetChangedObservable.notifyObservers(null);
  48162. }
  48163. this.rebuildAnglesAndRadius();
  48164. };
  48165. ArcRotateCamera.prototype._getViewMatrix = function () {
  48166. // Compute
  48167. var cosa = Math.cos(this.alpha);
  48168. var sina = Math.sin(this.alpha);
  48169. var cosb = Math.cos(this.beta);
  48170. var sinb = Math.sin(this.beta);
  48171. if (sinb === 0) {
  48172. sinb = 0.0001;
  48173. }
  48174. var target = this._getTargetPosition();
  48175. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48176. target.addToRef(this._computationVector, this._newPosition);
  48177. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48178. if (!this._collider) {
  48179. this._collider = new BABYLON.Collider();
  48180. }
  48181. this._collider._radius = this.collisionRadius;
  48182. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48183. this._collisionTriggered = true;
  48184. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48185. }
  48186. else {
  48187. this.position.copyFrom(this._newPosition);
  48188. var up = this.upVector;
  48189. if (this.allowUpsideDown && sinb < 0) {
  48190. up = up.clone();
  48191. up = up.negate();
  48192. }
  48193. this._computeViewMatrix(this.position, target, up);
  48194. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48195. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48196. }
  48197. this._currentTarget = target;
  48198. return this._viewMatrix;
  48199. };
  48200. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48201. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48202. meshes = meshes || this.getScene().meshes;
  48203. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48204. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48205. this.radius = distance * this.zoomOnFactor;
  48206. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48207. };
  48208. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48209. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48210. var meshesOrMinMaxVector;
  48211. var distance;
  48212. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48213. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48214. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48215. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48216. }
  48217. else { //minMaxVector and distance
  48218. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48219. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48220. distance = minMaxVectorAndDistance.distance;
  48221. }
  48222. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48223. if (!doNotUpdateMaxZ) {
  48224. this.maxZ = distance * 2;
  48225. }
  48226. };
  48227. /**
  48228. * @override
  48229. * Override Camera.createRigCamera
  48230. */
  48231. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48232. var alphaShift = 0;
  48233. switch (this.cameraRigMode) {
  48234. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48235. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48236. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48237. case BABYLON.Camera.RIG_MODE_VR:
  48238. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48239. break;
  48240. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48241. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48242. break;
  48243. }
  48244. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48245. rigCam._cameraRigParams = {};
  48246. return rigCam;
  48247. };
  48248. /**
  48249. * @override
  48250. * Override Camera._updateRigCameras
  48251. */
  48252. ArcRotateCamera.prototype._updateRigCameras = function () {
  48253. var camLeft = this._rigCameras[0];
  48254. var camRight = this._rigCameras[1];
  48255. camLeft.beta = camRight.beta = this.beta;
  48256. camLeft.radius = camRight.radius = this.radius;
  48257. switch (this.cameraRigMode) {
  48258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48259. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48260. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48261. case BABYLON.Camera.RIG_MODE_VR:
  48262. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48263. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48264. break;
  48265. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48266. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48267. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48268. break;
  48269. }
  48270. _super.prototype._updateRigCameras.call(this);
  48271. };
  48272. ArcRotateCamera.prototype.dispose = function () {
  48273. this.inputs.clear();
  48274. _super.prototype.dispose.call(this);
  48275. };
  48276. ArcRotateCamera.prototype.getClassName = function () {
  48277. return "ArcRotateCamera";
  48278. };
  48279. __decorate([
  48280. BABYLON.serialize()
  48281. ], ArcRotateCamera.prototype, "alpha", void 0);
  48282. __decorate([
  48283. BABYLON.serialize()
  48284. ], ArcRotateCamera.prototype, "beta", void 0);
  48285. __decorate([
  48286. BABYLON.serialize()
  48287. ], ArcRotateCamera.prototype, "radius", void 0);
  48288. __decorate([
  48289. BABYLON.serializeAsVector3("target")
  48290. ], ArcRotateCamera.prototype, "_target", void 0);
  48291. __decorate([
  48292. BABYLON.serialize()
  48293. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48294. __decorate([
  48295. BABYLON.serialize()
  48296. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48297. __decorate([
  48298. BABYLON.serialize()
  48299. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48300. __decorate([
  48301. BABYLON.serialize()
  48302. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48303. __decorate([
  48304. BABYLON.serialize()
  48305. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48306. __decorate([
  48307. BABYLON.serialize()
  48308. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48309. __decorate([
  48310. BABYLON.serialize()
  48311. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48312. __decorate([
  48313. BABYLON.serialize()
  48314. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48315. __decorate([
  48316. BABYLON.serialize()
  48317. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48318. __decorate([
  48319. BABYLON.serialize()
  48320. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48321. __decorate([
  48322. BABYLON.serialize()
  48323. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48324. __decorate([
  48325. BABYLON.serialize()
  48326. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48327. __decorate([
  48328. BABYLON.serialize()
  48329. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48330. __decorate([
  48331. BABYLON.serializeAsVector3()
  48332. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48333. __decorate([
  48334. BABYLON.serialize()
  48335. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48336. __decorate([
  48337. BABYLON.serialize()
  48338. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48339. __decorate([
  48340. BABYLON.serialize()
  48341. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48342. return ArcRotateCamera;
  48343. }(BABYLON.TargetCamera));
  48344. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48345. })(BABYLON || (BABYLON = {}));
  48346. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48347. var BABYLON;
  48348. (function (BABYLON) {
  48349. /**
  48350. * The HemisphericLight simulates the ambient environment light,
  48351. * so the passed direction is the light reflection direction, not the incoming direction.
  48352. */
  48353. var HemisphericLight = /** @class */ (function (_super) {
  48354. __extends(HemisphericLight, _super);
  48355. /**
  48356. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48357. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48358. * The HemisphericLight can't cast shadows.
  48359. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48360. * @param name The friendly name of the light
  48361. * @param direction The direction of the light reflection
  48362. * @param scene The scene the light belongs to
  48363. */
  48364. function HemisphericLight(name, direction, scene) {
  48365. var _this = _super.call(this, name, scene) || this;
  48366. /**
  48367. * The groundColor is the light in the opposite direction to the one specified during creation.
  48368. * 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.
  48369. */
  48370. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48371. _this.direction = direction || BABYLON.Vector3.Up();
  48372. return _this;
  48373. }
  48374. HemisphericLight.prototype._buildUniformLayout = function () {
  48375. this._uniformBuffer.addUniform("vLightData", 4);
  48376. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48377. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48378. this._uniformBuffer.addUniform("vLightGround", 3);
  48379. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48380. this._uniformBuffer.addUniform("depthValues", 2);
  48381. this._uniformBuffer.create();
  48382. };
  48383. /**
  48384. * Returns the string "HemisphericLight".
  48385. * @return The class name
  48386. */
  48387. HemisphericLight.prototype.getClassName = function () {
  48388. return "HemisphericLight";
  48389. };
  48390. /**
  48391. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48392. * Returns the updated direction.
  48393. * @param target The target the direction should point to
  48394. * @return The computed direction
  48395. */
  48396. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48397. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48398. return this.direction;
  48399. };
  48400. /**
  48401. * Returns the shadow generator associated to the light.
  48402. * @returns Always null for hemispheric lights because it does not support shadows.
  48403. */
  48404. HemisphericLight.prototype.getShadowGenerator = function () {
  48405. return null;
  48406. };
  48407. /**
  48408. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48409. * @param effect The effect to update
  48410. * @param lightIndex The index of the light in the effect to update
  48411. * @returns The hemispheric light
  48412. */
  48413. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48414. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48415. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48416. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48417. return this;
  48418. };
  48419. /**
  48420. * @hidden internal use only.
  48421. */
  48422. HemisphericLight.prototype._getWorldMatrix = function () {
  48423. if (!this._worldMatrix) {
  48424. this._worldMatrix = BABYLON.Matrix.Identity();
  48425. }
  48426. return this._worldMatrix;
  48427. };
  48428. /**
  48429. * Returns the integer 3.
  48430. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48431. */
  48432. HemisphericLight.prototype.getTypeID = function () {
  48433. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48434. };
  48435. __decorate([
  48436. BABYLON.serializeAsColor3()
  48437. ], HemisphericLight.prototype, "groundColor", void 0);
  48438. __decorate([
  48439. BABYLON.serializeAsVector3()
  48440. ], HemisphericLight.prototype, "direction", void 0);
  48441. return HemisphericLight;
  48442. }(BABYLON.Light));
  48443. BABYLON.HemisphericLight = HemisphericLight;
  48444. })(BABYLON || (BABYLON = {}));
  48445. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48446. var BABYLON;
  48447. (function (BABYLON) {
  48448. /**
  48449. * Base implementation IShadowLight
  48450. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48451. */
  48452. var ShadowLight = /** @class */ (function (_super) {
  48453. __extends(ShadowLight, _super);
  48454. function ShadowLight() {
  48455. var _this = _super !== null && _super.apply(this, arguments) || this;
  48456. _this._needProjectionMatrixCompute = true;
  48457. return _this;
  48458. }
  48459. ShadowLight.prototype._setPosition = function (value) {
  48460. this._position = value;
  48461. };
  48462. Object.defineProperty(ShadowLight.prototype, "position", {
  48463. /**
  48464. * Sets the position the shadow will be casted from. Also use as the light position for both
  48465. * point and spot lights.
  48466. */
  48467. get: function () {
  48468. return this._position;
  48469. },
  48470. /**
  48471. * Sets the position the shadow will be casted from. Also use as the light position for both
  48472. * point and spot lights.
  48473. */
  48474. set: function (value) {
  48475. this._setPosition(value);
  48476. },
  48477. enumerable: true,
  48478. configurable: true
  48479. });
  48480. ShadowLight.prototype._setDirection = function (value) {
  48481. this._direction = value;
  48482. };
  48483. Object.defineProperty(ShadowLight.prototype, "direction", {
  48484. /**
  48485. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48486. * Also use as the light direction on spot and directional lights.
  48487. */
  48488. get: function () {
  48489. return this._direction;
  48490. },
  48491. /**
  48492. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48493. * Also use as the light direction on spot and directional lights.
  48494. */
  48495. set: function (value) {
  48496. this._setDirection(value);
  48497. },
  48498. enumerable: true,
  48499. configurable: true
  48500. });
  48501. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48502. /**
  48503. * Gets the shadow projection clipping minimum z value.
  48504. */
  48505. get: function () {
  48506. return this._shadowMinZ;
  48507. },
  48508. /**
  48509. * Sets the shadow projection clipping minimum z value.
  48510. */
  48511. set: function (value) {
  48512. this._shadowMinZ = value;
  48513. this.forceProjectionMatrixCompute();
  48514. },
  48515. enumerable: true,
  48516. configurable: true
  48517. });
  48518. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48519. /**
  48520. * Sets the shadow projection clipping maximum z value.
  48521. */
  48522. get: function () {
  48523. return this._shadowMaxZ;
  48524. },
  48525. /**
  48526. * Gets the shadow projection clipping maximum z value.
  48527. */
  48528. set: function (value) {
  48529. this._shadowMaxZ = value;
  48530. this.forceProjectionMatrixCompute();
  48531. },
  48532. enumerable: true,
  48533. configurable: true
  48534. });
  48535. /**
  48536. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48537. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48538. */
  48539. ShadowLight.prototype.computeTransformedInformation = function () {
  48540. if (this.parent && this.parent.getWorldMatrix) {
  48541. if (!this.transformedPosition) {
  48542. this.transformedPosition = BABYLON.Vector3.Zero();
  48543. }
  48544. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48545. // In case the direction is present.
  48546. if (this.direction) {
  48547. if (!this.transformedDirection) {
  48548. this.transformedDirection = BABYLON.Vector3.Zero();
  48549. }
  48550. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48551. }
  48552. return true;
  48553. }
  48554. return false;
  48555. };
  48556. /**
  48557. * Return the depth scale used for the shadow map.
  48558. * @returns the depth scale.
  48559. */
  48560. ShadowLight.prototype.getDepthScale = function () {
  48561. return 50.0;
  48562. };
  48563. /**
  48564. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48565. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48566. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48567. */
  48568. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48569. return this.transformedDirection ? this.transformedDirection : this.direction;
  48570. };
  48571. /**
  48572. * Returns the ShadowLight absolute position in the World.
  48573. * @returns the position vector in world space
  48574. */
  48575. ShadowLight.prototype.getAbsolutePosition = function () {
  48576. return this.transformedPosition ? this.transformedPosition : this.position;
  48577. };
  48578. /**
  48579. * Sets the ShadowLight direction toward the passed target.
  48580. * @param target The point tot target in local space
  48581. * @returns the updated ShadowLight direction
  48582. */
  48583. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48584. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48585. return this.direction;
  48586. };
  48587. /**
  48588. * Returns the light rotation in euler definition.
  48589. * @returns the x y z rotation in local space.
  48590. */
  48591. ShadowLight.prototype.getRotation = function () {
  48592. this.direction.normalize();
  48593. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48594. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48595. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48596. };
  48597. /**
  48598. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48599. * @returns true if a cube texture needs to be use
  48600. */
  48601. ShadowLight.prototype.needCube = function () {
  48602. return false;
  48603. };
  48604. /**
  48605. * Detects if the projection matrix requires to be recomputed this frame.
  48606. * @returns true if it requires to be recomputed otherwise, false.
  48607. */
  48608. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48609. return this._needProjectionMatrixCompute;
  48610. };
  48611. /**
  48612. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48613. */
  48614. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48615. this._needProjectionMatrixCompute = true;
  48616. };
  48617. /**
  48618. * Get the world matrix of the sahdow lights.
  48619. * @hidden Internal Use Only
  48620. */
  48621. ShadowLight.prototype._getWorldMatrix = function () {
  48622. if (!this._worldMatrix) {
  48623. this._worldMatrix = BABYLON.Matrix.Identity();
  48624. }
  48625. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48626. return this._worldMatrix;
  48627. };
  48628. /**
  48629. * Gets the minZ used for shadow according to both the scene and the light.
  48630. * @param activeCamera The camera we are returning the min for
  48631. * @returns the depth min z
  48632. */
  48633. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48634. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48635. };
  48636. /**
  48637. * Gets the maxZ used for shadow according to both the scene and the light.
  48638. * @param activeCamera The camera we are returning the max for
  48639. * @returns the depth max z
  48640. */
  48641. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48642. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48643. };
  48644. /**
  48645. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48646. * @param matrix The materix to updated with the projection information
  48647. * @param viewMatrix The transform matrix of the light
  48648. * @param renderList The list of mesh to render in the map
  48649. * @returns The current light
  48650. */
  48651. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48652. if (this.customProjectionMatrixBuilder) {
  48653. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48654. }
  48655. else {
  48656. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48657. }
  48658. return this;
  48659. };
  48660. __decorate([
  48661. BABYLON.serializeAsVector3()
  48662. ], ShadowLight.prototype, "position", null);
  48663. __decorate([
  48664. BABYLON.serializeAsVector3()
  48665. ], ShadowLight.prototype, "direction", null);
  48666. __decorate([
  48667. BABYLON.serialize()
  48668. ], ShadowLight.prototype, "shadowMinZ", null);
  48669. __decorate([
  48670. BABYLON.serialize()
  48671. ], ShadowLight.prototype, "shadowMaxZ", null);
  48672. return ShadowLight;
  48673. }(BABYLON.Light));
  48674. BABYLON.ShadowLight = ShadowLight;
  48675. })(BABYLON || (BABYLON = {}));
  48676. //# sourceMappingURL=babylon.shadowLight.js.map
  48677. var BABYLON;
  48678. (function (BABYLON) {
  48679. /**
  48680. * A point light is a light defined by an unique point in world space.
  48681. * The light is emitted in every direction from this point.
  48682. * A good example of a point light is a standard light bulb.
  48683. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48684. */
  48685. var PointLight = /** @class */ (function (_super) {
  48686. __extends(PointLight, _super);
  48687. /**
  48688. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48689. * A PointLight emits the light in every direction.
  48690. * It can cast shadows.
  48691. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48692. * ```javascript
  48693. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48694. * ```
  48695. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48696. * @param name The light friendly name
  48697. * @param position The position of the point light in the scene
  48698. * @param scene The scene the lights belongs to
  48699. */
  48700. function PointLight(name, position, scene) {
  48701. var _this = _super.call(this, name, scene) || this;
  48702. _this._shadowAngle = Math.PI / 2;
  48703. _this.position = position;
  48704. return _this;
  48705. }
  48706. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48707. /**
  48708. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48709. * This specifies what angle the shadow will use to be created.
  48710. *
  48711. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48712. */
  48713. get: function () {
  48714. return this._shadowAngle;
  48715. },
  48716. /**
  48717. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48718. * This specifies what angle the shadow will use to be created.
  48719. *
  48720. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48721. */
  48722. set: function (value) {
  48723. this._shadowAngle = value;
  48724. this.forceProjectionMatrixCompute();
  48725. },
  48726. enumerable: true,
  48727. configurable: true
  48728. });
  48729. Object.defineProperty(PointLight.prototype, "direction", {
  48730. /**
  48731. * Gets the direction if it has been set.
  48732. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48733. */
  48734. get: function () {
  48735. return this._direction;
  48736. },
  48737. /**
  48738. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48739. */
  48740. set: function (value) {
  48741. var previousNeedCube = this.needCube();
  48742. this._direction = value;
  48743. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48744. this._shadowGenerator.recreateShadowMap();
  48745. }
  48746. },
  48747. enumerable: true,
  48748. configurable: true
  48749. });
  48750. /**
  48751. * Returns the string "PointLight"
  48752. * @returns the class name
  48753. */
  48754. PointLight.prototype.getClassName = function () {
  48755. return "PointLight";
  48756. };
  48757. /**
  48758. * Returns the integer 0.
  48759. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48760. */
  48761. PointLight.prototype.getTypeID = function () {
  48762. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48763. };
  48764. /**
  48765. * Specifies wether or not the shadowmap should be a cube texture.
  48766. * @returns true if the shadowmap needs to be a cube texture.
  48767. */
  48768. PointLight.prototype.needCube = function () {
  48769. return !this.direction;
  48770. };
  48771. /**
  48772. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48773. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48774. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48775. */
  48776. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48777. if (this.direction) {
  48778. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48779. }
  48780. else {
  48781. switch (faceIndex) {
  48782. case 0:
  48783. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48784. case 1:
  48785. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48786. case 2:
  48787. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48788. case 3:
  48789. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48790. case 4:
  48791. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48792. case 5:
  48793. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48794. }
  48795. }
  48796. return BABYLON.Vector3.Zero();
  48797. };
  48798. /**
  48799. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48800. * - fov = PI / 2
  48801. * - aspect ratio : 1.0
  48802. * - z-near and far equal to the active camera minZ and maxZ.
  48803. * Returns the PointLight.
  48804. */
  48805. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48806. var activeCamera = this.getScene().activeCamera;
  48807. if (!activeCamera) {
  48808. return;
  48809. }
  48810. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48811. };
  48812. PointLight.prototype._buildUniformLayout = function () {
  48813. this._uniformBuffer.addUniform("vLightData", 4);
  48814. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48815. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48816. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48817. this._uniformBuffer.addUniform("depthValues", 2);
  48818. this._uniformBuffer.create();
  48819. };
  48820. /**
  48821. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48822. * @param effect The effect to update
  48823. * @param lightIndex The index of the light in the effect to update
  48824. * @returns The point light
  48825. */
  48826. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48827. if (this.computeTransformedInformation()) {
  48828. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48829. return this;
  48830. }
  48831. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48832. return this;
  48833. };
  48834. __decorate([
  48835. BABYLON.serialize()
  48836. ], PointLight.prototype, "shadowAngle", null);
  48837. return PointLight;
  48838. }(BABYLON.ShadowLight));
  48839. BABYLON.PointLight = PointLight;
  48840. })(BABYLON || (BABYLON = {}));
  48841. //# sourceMappingURL=babylon.pointLight.js.map
  48842. var BABYLON;
  48843. (function (BABYLON) {
  48844. /**
  48845. * A directional light is defined by a direction (what a surprise!).
  48846. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48847. * 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.
  48848. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48849. */
  48850. var DirectionalLight = /** @class */ (function (_super) {
  48851. __extends(DirectionalLight, _super);
  48852. /**
  48853. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48854. * The directional light is emitted from everywhere in the given direction.
  48855. * It can cast shawdows.
  48856. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48857. * @param name The friendly name of the light
  48858. * @param direction The direction of the light
  48859. * @param scene The scene the light belongs to
  48860. */
  48861. function DirectionalLight(name, direction, scene) {
  48862. var _this = _super.call(this, name, scene) || this;
  48863. _this._shadowFrustumSize = 0;
  48864. _this._shadowOrthoScale = 0.1;
  48865. /**
  48866. * Automatically compute the projection matrix to best fit (including all the casters)
  48867. * on each frame.
  48868. */
  48869. _this.autoUpdateExtends = true;
  48870. // Cache
  48871. _this._orthoLeft = Number.MAX_VALUE;
  48872. _this._orthoRight = Number.MIN_VALUE;
  48873. _this._orthoTop = Number.MIN_VALUE;
  48874. _this._orthoBottom = Number.MAX_VALUE;
  48875. _this.position = direction.scale(-1.0);
  48876. _this.direction = direction;
  48877. return _this;
  48878. }
  48879. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48880. /**
  48881. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48882. */
  48883. get: function () {
  48884. return this._shadowFrustumSize;
  48885. },
  48886. /**
  48887. * Specifies a fix frustum size for the shadow generation.
  48888. */
  48889. set: function (value) {
  48890. this._shadowFrustumSize = value;
  48891. this.forceProjectionMatrixCompute();
  48892. },
  48893. enumerable: true,
  48894. configurable: true
  48895. });
  48896. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48897. /**
  48898. * Gets the shadow projection scale against the optimal computed one.
  48899. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48900. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48901. */
  48902. get: function () {
  48903. return this._shadowOrthoScale;
  48904. },
  48905. /**
  48906. * Sets the shadow projection scale against the optimal computed one.
  48907. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48908. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48909. */
  48910. set: function (value) {
  48911. this._shadowOrthoScale = value;
  48912. this.forceProjectionMatrixCompute();
  48913. },
  48914. enumerable: true,
  48915. configurable: true
  48916. });
  48917. /**
  48918. * Returns the string "DirectionalLight".
  48919. * @return The class name
  48920. */
  48921. DirectionalLight.prototype.getClassName = function () {
  48922. return "DirectionalLight";
  48923. };
  48924. /**
  48925. * Returns the integer 1.
  48926. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48927. */
  48928. DirectionalLight.prototype.getTypeID = function () {
  48929. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48930. };
  48931. /**
  48932. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48933. * Returns the DirectionalLight Shadow projection matrix.
  48934. */
  48935. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48936. if (this.shadowFrustumSize > 0) {
  48937. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48938. }
  48939. else {
  48940. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48941. }
  48942. };
  48943. /**
  48944. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48945. * Returns the DirectionalLight Shadow projection matrix.
  48946. */
  48947. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48948. var activeCamera = this.getScene().activeCamera;
  48949. if (!activeCamera) {
  48950. return;
  48951. }
  48952. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48953. };
  48954. /**
  48955. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48956. * Returns the DirectionalLight Shadow projection matrix.
  48957. */
  48958. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48959. var activeCamera = this.getScene().activeCamera;
  48960. if (!activeCamera) {
  48961. return;
  48962. }
  48963. // Check extends
  48964. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48965. var tempVector3 = BABYLON.Vector3.Zero();
  48966. this._orthoLeft = Number.MAX_VALUE;
  48967. this._orthoRight = Number.MIN_VALUE;
  48968. this._orthoTop = Number.MIN_VALUE;
  48969. this._orthoBottom = Number.MAX_VALUE;
  48970. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48971. var mesh = renderList[meshIndex];
  48972. if (!mesh) {
  48973. continue;
  48974. }
  48975. var boundingInfo = mesh.getBoundingInfo();
  48976. var boundingBox = boundingInfo.boundingBox;
  48977. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48978. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48979. if (tempVector3.x < this._orthoLeft)
  48980. this._orthoLeft = tempVector3.x;
  48981. if (tempVector3.y < this._orthoBottom)
  48982. this._orthoBottom = tempVector3.y;
  48983. if (tempVector3.x > this._orthoRight)
  48984. this._orthoRight = tempVector3.x;
  48985. if (tempVector3.y > this._orthoTop)
  48986. this._orthoTop = tempVector3.y;
  48987. }
  48988. }
  48989. }
  48990. var xOffset = this._orthoRight - this._orthoLeft;
  48991. var yOffset = this._orthoTop - this._orthoBottom;
  48992. 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);
  48993. };
  48994. DirectionalLight.prototype._buildUniformLayout = function () {
  48995. this._uniformBuffer.addUniform("vLightData", 4);
  48996. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48997. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48998. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48999. this._uniformBuffer.addUniform("depthValues", 2);
  49000. this._uniformBuffer.create();
  49001. };
  49002. /**
  49003. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49004. * @param effect The effect to update
  49005. * @param lightIndex The index of the light in the effect to update
  49006. * @returns The directional light
  49007. */
  49008. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49009. if (this.computeTransformedInformation()) {
  49010. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49011. return this;
  49012. }
  49013. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49014. return this;
  49015. };
  49016. /**
  49017. * Gets the minZ used for shadow according to both the scene and the light.
  49018. *
  49019. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49020. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49021. * @param activeCamera The camera we are returning the min for
  49022. * @returns the depth min z
  49023. */
  49024. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49025. return 1;
  49026. };
  49027. /**
  49028. * Gets the maxZ used for shadow according to both the scene and the light.
  49029. *
  49030. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49031. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49032. * @param activeCamera The camera we are returning the max for
  49033. * @returns the depth max z
  49034. */
  49035. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49036. return 1;
  49037. };
  49038. __decorate([
  49039. BABYLON.serialize()
  49040. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49041. __decorate([
  49042. BABYLON.serialize()
  49043. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49044. __decorate([
  49045. BABYLON.serialize()
  49046. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49047. return DirectionalLight;
  49048. }(BABYLON.ShadowLight));
  49049. BABYLON.DirectionalLight = DirectionalLight;
  49050. })(BABYLON || (BABYLON = {}));
  49051. //# sourceMappingURL=babylon.directionalLight.js.map
  49052. var BABYLON;
  49053. (function (BABYLON) {
  49054. /**
  49055. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49056. * These values define a cone of light starting from the position, emitting toward the direction.
  49057. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49058. * and the exponent defines the speed of the decay of the light with distance (reach).
  49059. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49060. */
  49061. var SpotLight = /** @class */ (function (_super) {
  49062. __extends(SpotLight, _super);
  49063. /**
  49064. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49065. * It can cast shadows.
  49066. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49067. * @param name The light friendly name
  49068. * @param position The position of the spot light in the scene
  49069. * @param direction The direction of the light in the scene
  49070. * @param angle The cone angle of the light in Radians
  49071. * @param exponent The light decay speed with the distance from the emission spot
  49072. * @param scene The scene the lights belongs to
  49073. */
  49074. function SpotLight(name, position, direction, angle, exponent, scene) {
  49075. var _this = _super.call(this, name, scene) || this;
  49076. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49077. _this._projectionTextureLightNear = 1e-6;
  49078. _this._projectionTextureLightFar = 1000.0;
  49079. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49080. _this._projectionTextureViewLightDirty = true;
  49081. _this._projectionTextureProjectionLightDirty = true;
  49082. _this._projectionTextureDirty = true;
  49083. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49084. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49085. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49086. _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);
  49087. _this.position = position;
  49088. _this.direction = direction;
  49089. _this.angle = angle;
  49090. _this.exponent = exponent;
  49091. return _this;
  49092. }
  49093. Object.defineProperty(SpotLight.prototype, "angle", {
  49094. /**
  49095. * Gets the cone angle of the spot light in Radians.
  49096. */
  49097. get: function () {
  49098. return this._angle;
  49099. },
  49100. /**
  49101. * Sets the cone angle of the spot light in Radians.
  49102. */
  49103. set: function (value) {
  49104. this._angle = value;
  49105. this._projectionTextureProjectionLightDirty = true;
  49106. this.forceProjectionMatrixCompute();
  49107. },
  49108. enumerable: true,
  49109. configurable: true
  49110. });
  49111. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49112. /**
  49113. * Allows scaling the angle of the light for shadow generation only.
  49114. */
  49115. get: function () {
  49116. return this._shadowAngleScale;
  49117. },
  49118. /**
  49119. * Allows scaling the angle of the light for shadow generation only.
  49120. */
  49121. set: function (value) {
  49122. this._shadowAngleScale = value;
  49123. this.forceProjectionMatrixCompute();
  49124. },
  49125. enumerable: true,
  49126. configurable: true
  49127. });
  49128. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49129. /**
  49130. * Allows reading the projecton texture
  49131. */
  49132. get: function () {
  49133. return this._projectionTextureMatrix;
  49134. },
  49135. enumerable: true,
  49136. configurable: true
  49137. });
  49138. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49139. /**
  49140. * Gets the near clip of the Spotlight for texture projection.
  49141. */
  49142. get: function () {
  49143. return this._projectionTextureLightNear;
  49144. },
  49145. /**
  49146. * Sets the near clip of the Spotlight for texture projection.
  49147. */
  49148. set: function (value) {
  49149. this._projectionTextureLightNear = value;
  49150. this._projectionTextureProjectionLightDirty = true;
  49151. },
  49152. enumerable: true,
  49153. configurable: true
  49154. });
  49155. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49156. /**
  49157. * Gets the far clip of the Spotlight for texture projection.
  49158. */
  49159. get: function () {
  49160. return this._projectionTextureLightFar;
  49161. },
  49162. /**
  49163. * Sets the far clip of the Spotlight for texture projection.
  49164. */
  49165. set: function (value) {
  49166. this._projectionTextureLightFar = value;
  49167. this._projectionTextureProjectionLightDirty = true;
  49168. },
  49169. enumerable: true,
  49170. configurable: true
  49171. });
  49172. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49173. /**
  49174. * Gets the Up vector of the Spotlight for texture projection.
  49175. */
  49176. get: function () {
  49177. return this._projectionTextureUpDirection;
  49178. },
  49179. /**
  49180. * Sets the Up vector of the Spotlight for texture projection.
  49181. */
  49182. set: function (value) {
  49183. this._projectionTextureUpDirection = value;
  49184. this._projectionTextureProjectionLightDirty = true;
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49190. /**
  49191. * Gets the projection texture of the light.
  49192. */
  49193. get: function () {
  49194. return this._projectionTexture;
  49195. },
  49196. /**
  49197. * Sets the projection texture of the light.
  49198. */
  49199. set: function (value) {
  49200. this._projectionTexture = value;
  49201. this._projectionTextureDirty = true;
  49202. },
  49203. enumerable: true,
  49204. configurable: true
  49205. });
  49206. /**
  49207. * Returns the string "SpotLight".
  49208. * @returns the class name
  49209. */
  49210. SpotLight.prototype.getClassName = function () {
  49211. return "SpotLight";
  49212. };
  49213. /**
  49214. * Returns the integer 2.
  49215. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49216. */
  49217. SpotLight.prototype.getTypeID = function () {
  49218. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49219. };
  49220. /**
  49221. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49222. */
  49223. SpotLight.prototype._setDirection = function (value) {
  49224. _super.prototype._setDirection.call(this, value);
  49225. this._projectionTextureViewLightDirty = true;
  49226. };
  49227. /**
  49228. * Overrides the position setter to recompute the projection texture view light Matrix.
  49229. */
  49230. SpotLight.prototype._setPosition = function (value) {
  49231. _super.prototype._setPosition.call(this, value);
  49232. this._projectionTextureViewLightDirty = true;
  49233. };
  49234. /**
  49235. * 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.
  49236. * Returns the SpotLight.
  49237. */
  49238. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49239. var activeCamera = this.getScene().activeCamera;
  49240. if (!activeCamera) {
  49241. return;
  49242. }
  49243. this._shadowAngleScale = this._shadowAngleScale || 1;
  49244. var angle = this._shadowAngleScale * this._angle;
  49245. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49246. };
  49247. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49248. this._projectionTextureViewLightDirty = false;
  49249. this._projectionTextureDirty = true;
  49250. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49251. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49252. };
  49253. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49254. this._projectionTextureProjectionLightDirty = false;
  49255. this._projectionTextureDirty = true;
  49256. var light_far = this.projectionTextureLightFar;
  49257. var light_near = this.projectionTextureLightNear;
  49258. var P = light_far / (light_far - light_near);
  49259. var Q = -P * light_near;
  49260. var S = 1.0 / Math.tan(this._angle / 2.0);
  49261. var A = 1.0;
  49262. 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);
  49263. };
  49264. /**
  49265. * Main function for light texture projection matrix computing.
  49266. */
  49267. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49268. this._projectionTextureDirty = false;
  49269. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49270. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49271. };
  49272. SpotLight.prototype._buildUniformLayout = function () {
  49273. this._uniformBuffer.addUniform("vLightData", 4);
  49274. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49275. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49276. this._uniformBuffer.addUniform("vLightDirection", 3);
  49277. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49278. this._uniformBuffer.addUniform("depthValues", 2);
  49279. this._uniformBuffer.create();
  49280. };
  49281. /**
  49282. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49283. * @param effect The effect to update
  49284. * @param lightIndex The index of the light in the effect to update
  49285. * @returns The spot light
  49286. */
  49287. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49288. var normalizeDirection;
  49289. if (this.computeTransformedInformation()) {
  49290. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49291. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49292. }
  49293. else {
  49294. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49295. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49296. }
  49297. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49298. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49299. if (this._projectionTextureViewLightDirty) {
  49300. this._computeProjectionTextureViewLightMatrix();
  49301. }
  49302. if (this._projectionTextureProjectionLightDirty) {
  49303. this._computeProjectionTextureProjectionLightMatrix();
  49304. }
  49305. if (this._projectionTextureDirty) {
  49306. this._computeProjectionTextureMatrix();
  49307. }
  49308. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49309. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49310. }
  49311. return this;
  49312. };
  49313. /**
  49314. * Disposes the light and the associated resources.
  49315. */
  49316. SpotLight.prototype.dispose = function () {
  49317. _super.prototype.dispose.call(this);
  49318. if (this._projectionTexture) {
  49319. this._projectionTexture.dispose();
  49320. }
  49321. };
  49322. __decorate([
  49323. BABYLON.serialize()
  49324. ], SpotLight.prototype, "angle", null);
  49325. __decorate([
  49326. BABYLON.serialize()
  49327. ], SpotLight.prototype, "shadowAngleScale", null);
  49328. __decorate([
  49329. BABYLON.serialize()
  49330. ], SpotLight.prototype, "exponent", void 0);
  49331. __decorate([
  49332. BABYLON.serialize()
  49333. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49334. __decorate([
  49335. BABYLON.serialize()
  49336. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49337. __decorate([
  49338. BABYLON.serialize()
  49339. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49340. __decorate([
  49341. BABYLON.serializeAsTexture("projectedLightTexture")
  49342. ], SpotLight.prototype, "_projectionTexture", void 0);
  49343. return SpotLight;
  49344. }(BABYLON.ShadowLight));
  49345. BABYLON.SpotLight = SpotLight;
  49346. })(BABYLON || (BABYLON = {}));
  49347. //# sourceMappingURL=babylon.spotLight.js.map
  49348. var BABYLON;
  49349. (function (BABYLON) {
  49350. /**
  49351. * Class used to override all child animations of a given target
  49352. */
  49353. var AnimationPropertiesOverride = /** @class */ (function () {
  49354. function AnimationPropertiesOverride() {
  49355. /**
  49356. * Gets or sets a value indicating if animation blending must be used
  49357. */
  49358. this.enableBlending = false;
  49359. /**
  49360. * Gets or sets the blending speed to use when enableBlending is true
  49361. */
  49362. this.blendingSpeed = 0.01;
  49363. /**
  49364. * Gets or sets the default loop mode to use
  49365. */
  49366. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49367. }
  49368. return AnimationPropertiesOverride;
  49369. }());
  49370. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49371. })(BABYLON || (BABYLON = {}));
  49372. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49373. var BABYLON;
  49374. (function (BABYLON) {
  49375. /**
  49376. * Represents the range of an animation
  49377. */
  49378. var AnimationRange = /** @class */ (function () {
  49379. /**
  49380. * Initializes the range of an animation
  49381. * @param name The name of the animation range
  49382. * @param from The starting frame of the animation
  49383. * @param to The ending frame of the animation
  49384. */
  49385. function AnimationRange(
  49386. /**The name of the animation range**/
  49387. name,
  49388. /**The starting frame of the animation */
  49389. from,
  49390. /**The ending frame of the animation*/
  49391. to) {
  49392. this.name = name;
  49393. this.from = from;
  49394. this.to = to;
  49395. }
  49396. /**
  49397. * Makes a copy of the animation range
  49398. * @returns A copy of the animation range
  49399. */
  49400. AnimationRange.prototype.clone = function () {
  49401. return new AnimationRange(this.name, this.from, this.to);
  49402. };
  49403. return AnimationRange;
  49404. }());
  49405. BABYLON.AnimationRange = AnimationRange;
  49406. /**
  49407. * Composed of a frame, and an action function
  49408. */
  49409. var AnimationEvent = /** @class */ (function () {
  49410. /**
  49411. * Initializes the animation event
  49412. * @param frame The frame for which the event is triggered
  49413. * @param action The event to perform when triggered
  49414. * @param onlyOnce Specifies if the event should be triggered only once
  49415. */
  49416. function AnimationEvent(
  49417. /** The frame for which the event is triggered **/
  49418. frame,
  49419. /** The event to perform when triggered **/
  49420. action,
  49421. /** Specifies if the event should be triggered only once**/
  49422. onlyOnce) {
  49423. this.frame = frame;
  49424. this.action = action;
  49425. this.onlyOnce = onlyOnce;
  49426. /**
  49427. * Specifies if the animation event is done
  49428. */
  49429. this.isDone = false;
  49430. }
  49431. /** @hidden */
  49432. AnimationEvent.prototype._clone = function () {
  49433. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49434. };
  49435. return AnimationEvent;
  49436. }());
  49437. BABYLON.AnimationEvent = AnimationEvent;
  49438. /**
  49439. * A cursor which tracks a point on a path
  49440. */
  49441. var PathCursor = /** @class */ (function () {
  49442. /**
  49443. * Initializes the path cursor
  49444. * @param path The path to track
  49445. */
  49446. function PathCursor(path) {
  49447. this.path = path;
  49448. /**
  49449. * Stores path cursor callbacks for when an onchange event is triggered
  49450. */
  49451. this._onchange = new Array();
  49452. /**
  49453. * The value of the path cursor
  49454. */
  49455. this.value = 0;
  49456. /**
  49457. * The animation array of the path cursor
  49458. */
  49459. this.animations = new Array();
  49460. }
  49461. /**
  49462. * Gets the cursor point on the path
  49463. * @returns A point on the path cursor at the cursor location
  49464. */
  49465. PathCursor.prototype.getPoint = function () {
  49466. var point = this.path.getPointAtLengthPosition(this.value);
  49467. return new BABYLON.Vector3(point.x, 0, point.y);
  49468. };
  49469. /**
  49470. * Moves the cursor ahead by the step amount
  49471. * @param step The amount to move the cursor forward
  49472. * @returns This path cursor
  49473. */
  49474. PathCursor.prototype.moveAhead = function (step) {
  49475. if (step === void 0) { step = 0.002; }
  49476. this.move(step);
  49477. return this;
  49478. };
  49479. /**
  49480. * Moves the cursor behind by the step amount
  49481. * @param step The amount to move the cursor back
  49482. * @returns This path cursor
  49483. */
  49484. PathCursor.prototype.moveBack = function (step) {
  49485. if (step === void 0) { step = 0.002; }
  49486. this.move(-step);
  49487. return this;
  49488. };
  49489. /**
  49490. * Moves the cursor by the step amount
  49491. * If the step amount is greater than one, an exception is thrown
  49492. * @param step The amount to move the cursor
  49493. * @returns This path cursor
  49494. */
  49495. PathCursor.prototype.move = function (step) {
  49496. if (Math.abs(step) > 1) {
  49497. throw "step size should be less than 1.";
  49498. }
  49499. this.value += step;
  49500. this.ensureLimits();
  49501. this.raiseOnChange();
  49502. return this;
  49503. };
  49504. /**
  49505. * Ensures that the value is limited between zero and one
  49506. * @returns This path cursor
  49507. */
  49508. PathCursor.prototype.ensureLimits = function () {
  49509. while (this.value > 1) {
  49510. this.value -= 1;
  49511. }
  49512. while (this.value < 0) {
  49513. this.value += 1;
  49514. }
  49515. return this;
  49516. };
  49517. /**
  49518. * Runs onchange callbacks on change (used by the animation engine)
  49519. * @returns This path cursor
  49520. */
  49521. PathCursor.prototype.raiseOnChange = function () {
  49522. var _this = this;
  49523. this._onchange.forEach(function (f) { return f(_this); });
  49524. return this;
  49525. };
  49526. /**
  49527. * Executes a function on change
  49528. * @param f A path cursor onchange callback
  49529. * @returns This path cursor
  49530. */
  49531. PathCursor.prototype.onchange = function (f) {
  49532. this._onchange.push(f);
  49533. return this;
  49534. };
  49535. return PathCursor;
  49536. }());
  49537. BABYLON.PathCursor = PathCursor;
  49538. /**
  49539. * Enum for the animation key frame interpolation type
  49540. */
  49541. var AnimationKeyInterpolation;
  49542. (function (AnimationKeyInterpolation) {
  49543. /**
  49544. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49545. */
  49546. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49547. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49548. /**
  49549. * Class used to store any kind of animation
  49550. */
  49551. var Animation = /** @class */ (function () {
  49552. /**
  49553. * Initializes the animation
  49554. * @param name Name of the animation
  49555. * @param targetProperty Property to animate
  49556. * @param framePerSecond The frames per second of the animation
  49557. * @param dataType The data type of the animation
  49558. * @param loopMode The loop mode of the animation
  49559. * @param enableBlendings Specifies if blending should be enabled
  49560. */
  49561. function Animation(
  49562. /**Name of the animation */
  49563. name,
  49564. /**Property to animate */
  49565. targetProperty,
  49566. /**The frames per second of the animation */
  49567. framePerSecond,
  49568. /**The data type of the animation */
  49569. dataType,
  49570. /**The loop mode of the animation */
  49571. loopMode,
  49572. /**Specifies if blending should be enabled */
  49573. enableBlending) {
  49574. this.name = name;
  49575. this.targetProperty = targetProperty;
  49576. this.framePerSecond = framePerSecond;
  49577. this.dataType = dataType;
  49578. this.loopMode = loopMode;
  49579. this.enableBlending = enableBlending;
  49580. /**
  49581. * @hidden Internal use only
  49582. */
  49583. this._runtimeAnimations = new Array();
  49584. /**
  49585. * The set of event that will be linked to this animation
  49586. */
  49587. this._events = new Array();
  49588. /**
  49589. * Stores the blending speed of the animation
  49590. */
  49591. this.blendingSpeed = 0.01;
  49592. /**
  49593. * Stores the animation ranges for the animation
  49594. */
  49595. this._ranges = {};
  49596. this.targetPropertyPath = targetProperty.split(".");
  49597. this.dataType = dataType;
  49598. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49599. }
  49600. /**
  49601. * @hidden Internal use
  49602. */
  49603. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49604. var dataType = undefined;
  49605. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49606. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49607. }
  49608. else if (from instanceof BABYLON.Quaternion) {
  49609. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49610. }
  49611. else if (from instanceof BABYLON.Vector3) {
  49612. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49613. }
  49614. else if (from instanceof BABYLON.Vector2) {
  49615. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49616. }
  49617. else if (from instanceof BABYLON.Color3) {
  49618. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49619. }
  49620. else if (from instanceof BABYLON.Size) {
  49621. dataType = Animation.ANIMATIONTYPE_SIZE;
  49622. }
  49623. if (dataType == undefined) {
  49624. return null;
  49625. }
  49626. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49627. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49628. animation.setKeys(keys);
  49629. if (easingFunction !== undefined) {
  49630. animation.setEasingFunction(easingFunction);
  49631. }
  49632. return animation;
  49633. };
  49634. /**
  49635. * Sets up an animation
  49636. * @param property The property to animate
  49637. * @param animationType The animation type to apply
  49638. * @param framePerSecond The frames per second of the animation
  49639. * @param easingFunction The easing function used in the animation
  49640. * @returns The created animation
  49641. */
  49642. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49643. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49644. animation.setEasingFunction(easingFunction);
  49645. return animation;
  49646. };
  49647. /**
  49648. * Create and start an animation on a node
  49649. * @param name defines the name of the global animation that will be run on all nodes
  49650. * @param node defines the root node where the animation will take place
  49651. * @param targetProperty defines property to animate
  49652. * @param framePerSecond defines the number of frame per second yo use
  49653. * @param totalFrame defines the number of frames in total
  49654. * @param from defines the initial value
  49655. * @param to defines the final value
  49656. * @param loopMode defines which loop mode you want to use (off by default)
  49657. * @param easingFunction defines the easing function to use (linear by default)
  49658. * @param onAnimationEnd defines the callback to call when animation end
  49659. * @returns the animatable created for this animation
  49660. */
  49661. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49662. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49663. if (!animation) {
  49664. return null;
  49665. }
  49666. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49667. };
  49668. /**
  49669. * Create and start an animation on a node and its descendants
  49670. * @param name defines the name of the global animation that will be run on all nodes
  49671. * @param node defines the root node where the animation will take place
  49672. * @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
  49673. * @param targetProperty defines property to animate
  49674. * @param framePerSecond defines the number of frame per second to use
  49675. * @param totalFrame defines the number of frames in total
  49676. * @param from defines the initial value
  49677. * @param to defines the final value
  49678. * @param loopMode defines which loop mode you want to use (off by default)
  49679. * @param easingFunction defines the easing function to use (linear by default)
  49680. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49681. * @returns the list of animatables created for all nodes
  49682. * @example https://www.babylonjs-playground.com/#MH0VLI
  49683. */
  49684. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49685. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49686. if (!animation) {
  49687. return null;
  49688. }
  49689. var scene = node.getScene();
  49690. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49691. };
  49692. /**
  49693. * Creates a new animation, merges it with the existing animations and starts it
  49694. * @param name Name of the animation
  49695. * @param node Node which contains the scene that begins the animations
  49696. * @param targetProperty Specifies which property to animate
  49697. * @param framePerSecond The frames per second of the animation
  49698. * @param totalFrame The total number of frames
  49699. * @param from The frame at the beginning of the animation
  49700. * @param to The frame at the end of the animation
  49701. * @param loopMode Specifies the loop mode of the animation
  49702. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49703. * @param onAnimationEnd Callback to run once the animation is complete
  49704. * @returns Nullable animation
  49705. */
  49706. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49707. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49708. if (!animation) {
  49709. return null;
  49710. }
  49711. node.animations.push(animation);
  49712. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49713. };
  49714. /**
  49715. * Transition property of an host to the target Value
  49716. * @param property The property to transition
  49717. * @param targetValue The target Value of the property
  49718. * @param host The object where the property to animate belongs
  49719. * @param scene Scene used to run the animation
  49720. * @param frameRate Framerate (in frame/s) to use
  49721. * @param transition The transition type we want to use
  49722. * @param duration The duration of the animation, in milliseconds
  49723. * @param onAnimationEnd Callback trigger at the end of the animation
  49724. * @returns Nullable animation
  49725. */
  49726. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49727. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49728. if (duration <= 0) {
  49729. host[property] = targetValue;
  49730. if (onAnimationEnd) {
  49731. onAnimationEnd();
  49732. }
  49733. return null;
  49734. }
  49735. var endFrame = frameRate * (duration / 1000);
  49736. transition.setKeys([{
  49737. frame: 0,
  49738. value: host[property].clone ? host[property].clone() : host[property]
  49739. },
  49740. {
  49741. frame: endFrame,
  49742. value: targetValue
  49743. }]);
  49744. if (!host.animations) {
  49745. host.animations = [];
  49746. }
  49747. host.animations.push(transition);
  49748. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49749. animation.onAnimationEnd = onAnimationEnd;
  49750. return animation;
  49751. };
  49752. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49753. /**
  49754. * Return the array of runtime animations currently using this animation
  49755. */
  49756. get: function () {
  49757. return this._runtimeAnimations;
  49758. },
  49759. enumerable: true,
  49760. configurable: true
  49761. });
  49762. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49763. /**
  49764. * Specifies if any of the runtime animations are currently running
  49765. */
  49766. get: function () {
  49767. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49768. var runtimeAnimation = _a[_i];
  49769. if (!runtimeAnimation.isStopped) {
  49770. return true;
  49771. }
  49772. }
  49773. return false;
  49774. },
  49775. enumerable: true,
  49776. configurable: true
  49777. });
  49778. // Methods
  49779. /**
  49780. * Converts the animation to a string
  49781. * @param fullDetails support for multiple levels of logging within scene loading
  49782. * @returns String form of the animation
  49783. */
  49784. Animation.prototype.toString = function (fullDetails) {
  49785. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49786. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49787. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49788. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49789. if (fullDetails) {
  49790. ret += ", Ranges: {";
  49791. var first = true;
  49792. for (var name in this._ranges) {
  49793. if (first) {
  49794. ret += ", ";
  49795. first = false;
  49796. }
  49797. ret += name;
  49798. }
  49799. ret += "}";
  49800. }
  49801. return ret;
  49802. };
  49803. /**
  49804. * Add an event to this animation
  49805. * @param event Event to add
  49806. */
  49807. Animation.prototype.addEvent = function (event) {
  49808. this._events.push(event);
  49809. };
  49810. /**
  49811. * Remove all events found at the given frame
  49812. * @param frame The frame to remove events from
  49813. */
  49814. Animation.prototype.removeEvents = function (frame) {
  49815. for (var index = 0; index < this._events.length; index++) {
  49816. if (this._events[index].frame === frame) {
  49817. this._events.splice(index, 1);
  49818. index--;
  49819. }
  49820. }
  49821. };
  49822. /**
  49823. * Retrieves all the events from the animation
  49824. * @returns Events from the animation
  49825. */
  49826. Animation.prototype.getEvents = function () {
  49827. return this._events;
  49828. };
  49829. /**
  49830. * Creates an animation range
  49831. * @param name Name of the animation range
  49832. * @param from Starting frame of the animation range
  49833. * @param to Ending frame of the animation
  49834. */
  49835. Animation.prototype.createRange = function (name, from, to) {
  49836. // check name not already in use; could happen for bones after serialized
  49837. if (!this._ranges[name]) {
  49838. this._ranges[name] = new AnimationRange(name, from, to);
  49839. }
  49840. };
  49841. /**
  49842. * Deletes an animation range by name
  49843. * @param name Name of the animation range to delete
  49844. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49845. */
  49846. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49847. if (deleteFrames === void 0) { deleteFrames = true; }
  49848. var range = this._ranges[name];
  49849. if (!range) {
  49850. return;
  49851. }
  49852. if (deleteFrames) {
  49853. var from = range.from;
  49854. var to = range.to;
  49855. // this loop MUST go high to low for multiple splices to work
  49856. for (var key = this._keys.length - 1; key >= 0; key--) {
  49857. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49858. this._keys.splice(key, 1);
  49859. }
  49860. }
  49861. }
  49862. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49863. };
  49864. /**
  49865. * Gets the animation range by name, or null if not defined
  49866. * @param name Name of the animation range
  49867. * @returns Nullable animation range
  49868. */
  49869. Animation.prototype.getRange = function (name) {
  49870. return this._ranges[name];
  49871. };
  49872. /**
  49873. * Gets the key frames from the animation
  49874. * @returns The key frames of the animation
  49875. */
  49876. Animation.prototype.getKeys = function () {
  49877. return this._keys;
  49878. };
  49879. /**
  49880. * Gets the highest frame rate of the animation
  49881. * @returns Highest frame rate of the animation
  49882. */
  49883. Animation.prototype.getHighestFrame = function () {
  49884. var ret = 0;
  49885. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49886. if (ret < this._keys[key].frame) {
  49887. ret = this._keys[key].frame;
  49888. }
  49889. }
  49890. return ret;
  49891. };
  49892. /**
  49893. * Gets the easing function of the animation
  49894. * @returns Easing function of the animation
  49895. */
  49896. Animation.prototype.getEasingFunction = function () {
  49897. return this._easingFunction;
  49898. };
  49899. /**
  49900. * Sets the easing function of the animation
  49901. * @param easingFunction A custom mathematical formula for animation
  49902. */
  49903. Animation.prototype.setEasingFunction = function (easingFunction) {
  49904. this._easingFunction = easingFunction;
  49905. };
  49906. /**
  49907. * Interpolates a scalar linearly
  49908. * @param startValue Start value of the animation curve
  49909. * @param endValue End value of the animation curve
  49910. * @param gradient Scalar amount to interpolate
  49911. * @returns Interpolated scalar value
  49912. */
  49913. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49914. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49915. };
  49916. /**
  49917. * Interpolates a scalar cubically
  49918. * @param startValue Start value of the animation curve
  49919. * @param outTangent End tangent of the animation
  49920. * @param endValue End value of the animation curve
  49921. * @param inTangent Start tangent of the animation curve
  49922. * @param gradient Scalar amount to interpolate
  49923. * @returns Interpolated scalar value
  49924. */
  49925. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49926. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49927. };
  49928. /**
  49929. * Interpolates a quaternion using a spherical linear interpolation
  49930. * @param startValue Start value of the animation curve
  49931. * @param endValue End value of the animation curve
  49932. * @param gradient Scalar amount to interpolate
  49933. * @returns Interpolated quaternion value
  49934. */
  49935. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49936. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49937. };
  49938. /**
  49939. * Interpolates a quaternion cubically
  49940. * @param startValue Start value of the animation curve
  49941. * @param outTangent End tangent of the animation curve
  49942. * @param endValue End value of the animation curve
  49943. * @param inTangent Start tangent of the animation curve
  49944. * @param gradient Scalar amount to interpolate
  49945. * @returns Interpolated quaternion value
  49946. */
  49947. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49948. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49949. };
  49950. /**
  49951. * Interpolates a Vector3 linearl
  49952. * @param startValue Start value of the animation curve
  49953. * @param endValue End value of the animation curve
  49954. * @param gradient Scalar amount to interpolate
  49955. * @returns Interpolated scalar value
  49956. */
  49957. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49958. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49959. };
  49960. /**
  49961. * Interpolates a Vector3 cubically
  49962. * @param startValue Start value of the animation curve
  49963. * @param outTangent End tangent of the animation
  49964. * @param endValue End value of the animation curve
  49965. * @param inTangent Start tangent of the animation curve
  49966. * @param gradient Scalar amount to interpolate
  49967. * @returns InterpolatedVector3 value
  49968. */
  49969. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49970. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49971. };
  49972. /**
  49973. * Interpolates a Vector2 linearly
  49974. * @param startValue Start value of the animation curve
  49975. * @param endValue End value of the animation curve
  49976. * @param gradient Scalar amount to interpolate
  49977. * @returns Interpolated Vector2 value
  49978. */
  49979. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49980. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49981. };
  49982. /**
  49983. * Interpolates a Vector2 cubically
  49984. * @param startValue Start value of the animation curve
  49985. * @param outTangent End tangent of the animation
  49986. * @param endValue End value of the animation curve
  49987. * @param inTangent Start tangent of the animation curve
  49988. * @param gradient Scalar amount to interpolate
  49989. * @returns Interpolated Vector2 value
  49990. */
  49991. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49992. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49993. };
  49994. /**
  49995. * Interpolates a size linearly
  49996. * @param startValue Start value of the animation curve
  49997. * @param endValue End value of the animation curve
  49998. * @param gradient Scalar amount to interpolate
  49999. * @returns Interpolated Size value
  50000. */
  50001. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50002. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50003. };
  50004. /**
  50005. * Interpolates a Color3 linearly
  50006. * @param startValue Start value of the animation curve
  50007. * @param endValue End value of the animation curve
  50008. * @param gradient Scalar amount to interpolate
  50009. * @returns Interpolated Color3 value
  50010. */
  50011. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50012. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50013. };
  50014. /**
  50015. * @hidden Internal use only
  50016. */
  50017. Animation.prototype._getKeyValue = function (value) {
  50018. if (typeof value === "function") {
  50019. return value();
  50020. }
  50021. return value;
  50022. };
  50023. /**
  50024. * @hidden Internal use only
  50025. */
  50026. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50027. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50028. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50029. }
  50030. var keys = this.getKeys();
  50031. // Try to get a hash to find the right key
  50032. 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));
  50033. if (keys[startKeyIndex].frame >= currentFrame) {
  50034. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50035. startKeyIndex--;
  50036. }
  50037. }
  50038. for (var key = startKeyIndex; key < keys.length; key++) {
  50039. var endKey = keys[key + 1];
  50040. if (endKey.frame >= currentFrame) {
  50041. var startKey = keys[key];
  50042. var startValue = this._getKeyValue(startKey.value);
  50043. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50044. return startValue;
  50045. }
  50046. var endValue = this._getKeyValue(endKey.value);
  50047. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50048. var frameDelta = endKey.frame - startKey.frame;
  50049. // gradient : percent of currentFrame between the frame inf and the frame sup
  50050. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50051. // check for easingFunction and correction of gradient
  50052. var easingFunction = this.getEasingFunction();
  50053. if (easingFunction != null) {
  50054. gradient = easingFunction.ease(gradient);
  50055. }
  50056. switch (this.dataType) {
  50057. // Float
  50058. case Animation.ANIMATIONTYPE_FLOAT:
  50059. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50060. switch (loopMode) {
  50061. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50062. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50063. return floatValue;
  50064. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50065. return offsetValue * repeatCount + floatValue;
  50066. }
  50067. break;
  50068. // Quaternion
  50069. case Animation.ANIMATIONTYPE_QUATERNION:
  50070. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50071. switch (loopMode) {
  50072. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50073. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50074. return quatValue;
  50075. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50076. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50077. }
  50078. return quatValue;
  50079. // Vector3
  50080. case Animation.ANIMATIONTYPE_VECTOR3:
  50081. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50082. switch (loopMode) {
  50083. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50084. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50085. return vec3Value;
  50086. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50087. return vec3Value.add(offsetValue.scale(repeatCount));
  50088. }
  50089. // Vector2
  50090. case Animation.ANIMATIONTYPE_VECTOR2:
  50091. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50092. switch (loopMode) {
  50093. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50094. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50095. return vec2Value;
  50096. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50097. return vec2Value.add(offsetValue.scale(repeatCount));
  50098. }
  50099. // Size
  50100. case Animation.ANIMATIONTYPE_SIZE:
  50101. switch (loopMode) {
  50102. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50103. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50104. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50105. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50106. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50107. }
  50108. // Color3
  50109. case Animation.ANIMATIONTYPE_COLOR3:
  50110. switch (loopMode) {
  50111. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50112. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50113. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50114. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50115. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50116. }
  50117. // Matrix
  50118. case Animation.ANIMATIONTYPE_MATRIX:
  50119. switch (loopMode) {
  50120. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50121. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50122. if (Animation.AllowMatricesInterpolation) {
  50123. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50124. }
  50125. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50126. return startValue;
  50127. }
  50128. default:
  50129. break;
  50130. }
  50131. break;
  50132. }
  50133. }
  50134. return this._getKeyValue(keys[keys.length - 1].value);
  50135. };
  50136. /**
  50137. * Defines the function to use to interpolate matrices
  50138. * @param startValue defines the start matrix
  50139. * @param endValue defines the end matrix
  50140. * @param gradient defines the gradient between both matrices
  50141. * @param result defines an optional target matrix where to store the interpolation
  50142. * @returns the interpolated matrix
  50143. */
  50144. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50145. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50146. if (result) {
  50147. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50148. return result;
  50149. }
  50150. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50151. }
  50152. if (result) {
  50153. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50154. return result;
  50155. }
  50156. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50157. };
  50158. /**
  50159. * Makes a copy of the animation
  50160. * @returns Cloned animation
  50161. */
  50162. Animation.prototype.clone = function () {
  50163. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50164. clone.enableBlending = this.enableBlending;
  50165. clone.blendingSpeed = this.blendingSpeed;
  50166. if (this._keys) {
  50167. clone.setKeys(this._keys);
  50168. }
  50169. if (this._ranges) {
  50170. clone._ranges = {};
  50171. for (var name in this._ranges) {
  50172. var range = this._ranges[name];
  50173. if (!range) {
  50174. continue;
  50175. }
  50176. clone._ranges[name] = range.clone();
  50177. }
  50178. }
  50179. return clone;
  50180. };
  50181. /**
  50182. * Sets the key frames of the animation
  50183. * @param values The animation key frames to set
  50184. */
  50185. Animation.prototype.setKeys = function (values) {
  50186. this._keys = values.slice(0);
  50187. };
  50188. /**
  50189. * Serializes the animation to an object
  50190. * @returns Serialized object
  50191. */
  50192. Animation.prototype.serialize = function () {
  50193. var serializationObject = {};
  50194. serializationObject.name = this.name;
  50195. serializationObject.property = this.targetProperty;
  50196. serializationObject.framePerSecond = this.framePerSecond;
  50197. serializationObject.dataType = this.dataType;
  50198. serializationObject.loopBehavior = this.loopMode;
  50199. serializationObject.enableBlending = this.enableBlending;
  50200. serializationObject.blendingSpeed = this.blendingSpeed;
  50201. var dataType = this.dataType;
  50202. serializationObject.keys = [];
  50203. var keys = this.getKeys();
  50204. for (var index = 0; index < keys.length; index++) {
  50205. var animationKey = keys[index];
  50206. var key = {};
  50207. key.frame = animationKey.frame;
  50208. switch (dataType) {
  50209. case Animation.ANIMATIONTYPE_FLOAT:
  50210. key.values = [animationKey.value];
  50211. break;
  50212. case Animation.ANIMATIONTYPE_QUATERNION:
  50213. case Animation.ANIMATIONTYPE_MATRIX:
  50214. case Animation.ANIMATIONTYPE_VECTOR3:
  50215. case Animation.ANIMATIONTYPE_COLOR3:
  50216. key.values = animationKey.value.asArray();
  50217. break;
  50218. }
  50219. serializationObject.keys.push(key);
  50220. }
  50221. serializationObject.ranges = [];
  50222. for (var name in this._ranges) {
  50223. var source = this._ranges[name];
  50224. if (!source) {
  50225. continue;
  50226. }
  50227. var range = {};
  50228. range.name = name;
  50229. range.from = source.from;
  50230. range.to = source.to;
  50231. serializationObject.ranges.push(range);
  50232. }
  50233. return serializationObject;
  50234. };
  50235. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50236. /**
  50237. * Get the float animation type
  50238. */
  50239. get: function () {
  50240. return Animation._ANIMATIONTYPE_FLOAT;
  50241. },
  50242. enumerable: true,
  50243. configurable: true
  50244. });
  50245. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50246. /**
  50247. * Get the Vector3 animation type
  50248. */
  50249. get: function () {
  50250. return Animation._ANIMATIONTYPE_VECTOR3;
  50251. },
  50252. enumerable: true,
  50253. configurable: true
  50254. });
  50255. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50256. /**
  50257. * Get the Vectpr2 animation type
  50258. */
  50259. get: function () {
  50260. return Animation._ANIMATIONTYPE_VECTOR2;
  50261. },
  50262. enumerable: true,
  50263. configurable: true
  50264. });
  50265. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50266. /**
  50267. * Get the Size animation type
  50268. */
  50269. get: function () {
  50270. return Animation._ANIMATIONTYPE_SIZE;
  50271. },
  50272. enumerable: true,
  50273. configurable: true
  50274. });
  50275. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50276. /**
  50277. * Get the Quaternion animation type
  50278. */
  50279. get: function () {
  50280. return Animation._ANIMATIONTYPE_QUATERNION;
  50281. },
  50282. enumerable: true,
  50283. configurable: true
  50284. });
  50285. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50286. /**
  50287. * Get the Matrix animation type
  50288. */
  50289. get: function () {
  50290. return Animation._ANIMATIONTYPE_MATRIX;
  50291. },
  50292. enumerable: true,
  50293. configurable: true
  50294. });
  50295. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50296. /**
  50297. * Get the Color3 animation type
  50298. */
  50299. get: function () {
  50300. return Animation._ANIMATIONTYPE_COLOR3;
  50301. },
  50302. enumerable: true,
  50303. configurable: true
  50304. });
  50305. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50306. /**
  50307. * Get the Relative Loop Mode
  50308. */
  50309. get: function () {
  50310. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50311. },
  50312. enumerable: true,
  50313. configurable: true
  50314. });
  50315. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50316. /**
  50317. * Get the Cycle Loop Mode
  50318. */
  50319. get: function () {
  50320. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50321. },
  50322. enumerable: true,
  50323. configurable: true
  50324. });
  50325. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50326. /**
  50327. * Get the Constant Loop Mode
  50328. */
  50329. get: function () {
  50330. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50331. },
  50332. enumerable: true,
  50333. configurable: true
  50334. });
  50335. /** @hidden */
  50336. Animation._UniversalLerp = function (left, right, amount) {
  50337. var constructor = left.constructor;
  50338. if (constructor.Lerp) { // Lerp supported
  50339. return constructor.Lerp(left, right, amount);
  50340. }
  50341. else if (constructor.Slerp) { // Slerp supported
  50342. return constructor.Slerp(left, right, amount);
  50343. }
  50344. else if (left.toFixed) { // Number
  50345. return left * (1.0 - amount) + amount * right;
  50346. }
  50347. else { // Blending not supported
  50348. return right;
  50349. }
  50350. };
  50351. /**
  50352. * Parses an animation object and creates an animation
  50353. * @param parsedAnimation Parsed animation object
  50354. * @returns Animation object
  50355. */
  50356. Animation.Parse = function (parsedAnimation) {
  50357. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50358. var dataType = parsedAnimation.dataType;
  50359. var keys = [];
  50360. var data;
  50361. var index;
  50362. if (parsedAnimation.enableBlending) {
  50363. animation.enableBlending = parsedAnimation.enableBlending;
  50364. }
  50365. if (parsedAnimation.blendingSpeed) {
  50366. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50367. }
  50368. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50369. var key = parsedAnimation.keys[index];
  50370. var inTangent;
  50371. var outTangent;
  50372. switch (dataType) {
  50373. case Animation.ANIMATIONTYPE_FLOAT:
  50374. data = key.values[0];
  50375. if (key.values.length >= 1) {
  50376. inTangent = key.values[1];
  50377. }
  50378. if (key.values.length >= 2) {
  50379. outTangent = key.values[2];
  50380. }
  50381. break;
  50382. case Animation.ANIMATIONTYPE_QUATERNION:
  50383. data = BABYLON.Quaternion.FromArray(key.values);
  50384. if (key.values.length >= 8) {
  50385. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50386. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50387. inTangent = _inTangent;
  50388. }
  50389. }
  50390. if (key.values.length >= 12) {
  50391. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50392. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50393. outTangent = _outTangent;
  50394. }
  50395. }
  50396. break;
  50397. case Animation.ANIMATIONTYPE_MATRIX:
  50398. data = BABYLON.Matrix.FromArray(key.values);
  50399. break;
  50400. case Animation.ANIMATIONTYPE_COLOR3:
  50401. data = BABYLON.Color3.FromArray(key.values);
  50402. break;
  50403. case Animation.ANIMATIONTYPE_VECTOR3:
  50404. default:
  50405. data = BABYLON.Vector3.FromArray(key.values);
  50406. break;
  50407. }
  50408. var keyData = {};
  50409. keyData.frame = key.frame;
  50410. keyData.value = data;
  50411. if (inTangent != undefined) {
  50412. keyData.inTangent = inTangent;
  50413. }
  50414. if (outTangent != undefined) {
  50415. keyData.outTangent = outTangent;
  50416. }
  50417. keys.push(keyData);
  50418. }
  50419. animation.setKeys(keys);
  50420. if (parsedAnimation.ranges) {
  50421. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50422. data = parsedAnimation.ranges[index];
  50423. animation.createRange(data.name, data.from, data.to);
  50424. }
  50425. }
  50426. return animation;
  50427. };
  50428. /**
  50429. * Appends the serialized animations from the source animations
  50430. * @param source Source containing the animations
  50431. * @param destination Target to store the animations
  50432. */
  50433. Animation.AppendSerializedAnimations = function (source, destination) {
  50434. if (source.animations) {
  50435. destination.animations = [];
  50436. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50437. var animation = source.animations[animationIndex];
  50438. destination.animations.push(animation.serialize());
  50439. }
  50440. }
  50441. };
  50442. /**
  50443. * Use matrix interpolation instead of using direct key value when animating matrices
  50444. */
  50445. Animation.AllowMatricesInterpolation = false;
  50446. /**
  50447. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50448. */
  50449. Animation.AllowMatrixDecomposeForInterpolation = true;
  50450. // Statics
  50451. /**
  50452. * Float animation type
  50453. */
  50454. Animation._ANIMATIONTYPE_FLOAT = 0;
  50455. /**
  50456. * Vector3 animation type
  50457. */
  50458. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50459. /**
  50460. * Quaternion animation type
  50461. */
  50462. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50463. /**
  50464. * Matrix animation type
  50465. */
  50466. Animation._ANIMATIONTYPE_MATRIX = 3;
  50467. /**
  50468. * Color3 animation type
  50469. */
  50470. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50471. /**
  50472. * Vector2 animation type
  50473. */
  50474. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50475. /**
  50476. * Size animation type
  50477. */
  50478. Animation._ANIMATIONTYPE_SIZE = 6;
  50479. /**
  50480. * Relative Loop Mode
  50481. */
  50482. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50483. /**
  50484. * Cycle Loop Mode
  50485. */
  50486. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50487. /**
  50488. * Constant Loop Mode
  50489. */
  50490. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50491. return Animation;
  50492. }());
  50493. BABYLON.Animation = Animation;
  50494. })(BABYLON || (BABYLON = {}));
  50495. //# sourceMappingURL=babylon.animation.js.map
  50496. var BABYLON;
  50497. (function (BABYLON) {
  50498. /**
  50499. * This class defines the direct association between an animation and a target
  50500. */
  50501. var TargetedAnimation = /** @class */ (function () {
  50502. function TargetedAnimation() {
  50503. }
  50504. return TargetedAnimation;
  50505. }());
  50506. BABYLON.TargetedAnimation = TargetedAnimation;
  50507. /**
  50508. * Use this class to create coordinated animations on multiple targets
  50509. */
  50510. var AnimationGroup = /** @class */ (function () {
  50511. function AnimationGroup(name, scene) {
  50512. if (scene === void 0) { scene = null; }
  50513. this.name = name;
  50514. this._targetedAnimations = new Array();
  50515. this._animatables = new Array();
  50516. this._from = Number.MAX_VALUE;
  50517. this._to = -Number.MAX_VALUE;
  50518. this._speedRatio = 1;
  50519. this.onAnimationEndObservable = new BABYLON.Observable();
  50520. /**
  50521. * This observable will notify when all animations have ended.
  50522. */
  50523. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50524. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50525. this._scene.animationGroups.push(this);
  50526. }
  50527. Object.defineProperty(AnimationGroup.prototype, "from", {
  50528. /**
  50529. * Gets the first frame
  50530. */
  50531. get: function () {
  50532. return this._from;
  50533. },
  50534. enumerable: true,
  50535. configurable: true
  50536. });
  50537. Object.defineProperty(AnimationGroup.prototype, "to", {
  50538. /**
  50539. * Gets the last frame
  50540. */
  50541. get: function () {
  50542. return this._to;
  50543. },
  50544. enumerable: true,
  50545. configurable: true
  50546. });
  50547. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50548. /**
  50549. * Define if the animations are started
  50550. */
  50551. get: function () {
  50552. return this._isStarted;
  50553. },
  50554. enumerable: true,
  50555. configurable: true
  50556. });
  50557. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50558. /**
  50559. * Gets or sets the speed ratio to use for all animations
  50560. */
  50561. get: function () {
  50562. return this._speedRatio;
  50563. },
  50564. /**
  50565. * Gets or sets the speed ratio to use for all animations
  50566. */
  50567. set: function (value) {
  50568. if (this._speedRatio === value) {
  50569. return;
  50570. }
  50571. this._speedRatio = value;
  50572. for (var index = 0; index < this._animatables.length; index++) {
  50573. var animatable = this._animatables[index];
  50574. animatable.speedRatio = this._speedRatio;
  50575. }
  50576. },
  50577. enumerable: true,
  50578. configurable: true
  50579. });
  50580. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50581. /**
  50582. * Gets the targeted animations for this animation group
  50583. */
  50584. get: function () {
  50585. return this._targetedAnimations;
  50586. },
  50587. enumerable: true,
  50588. configurable: true
  50589. });
  50590. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50591. /**
  50592. * returning the list of animatables controlled by this animation group.
  50593. */
  50594. get: function () {
  50595. return this._animatables;
  50596. },
  50597. enumerable: true,
  50598. configurable: true
  50599. });
  50600. /**
  50601. * Add an animation (with its target) in the group
  50602. * @param animation defines the animation we want to add
  50603. * @param target defines the target of the animation
  50604. * @returns the {BABYLON.TargetedAnimation} object
  50605. */
  50606. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50607. var targetedAnimation = {
  50608. animation: animation,
  50609. target: target
  50610. };
  50611. var keys = animation.getKeys();
  50612. if (this._from > keys[0].frame) {
  50613. this._from = keys[0].frame;
  50614. }
  50615. if (this._to < keys[keys.length - 1].frame) {
  50616. this._to = keys[keys.length - 1].frame;
  50617. }
  50618. this._targetedAnimations.push(targetedAnimation);
  50619. return targetedAnimation;
  50620. };
  50621. /**
  50622. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50623. * It can add constant keys at begin or end
  50624. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50625. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50626. */
  50627. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50628. if (beginFrame === void 0) { beginFrame = null; }
  50629. if (endFrame === void 0) { endFrame = null; }
  50630. if (beginFrame == null)
  50631. beginFrame = this._from;
  50632. if (endFrame == null)
  50633. endFrame = this._to;
  50634. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50635. var targetedAnimation = this._targetedAnimations[index];
  50636. var keys = targetedAnimation.animation.getKeys();
  50637. var startKey = keys[0];
  50638. var endKey = keys[keys.length - 1];
  50639. if (startKey.frame > beginFrame) {
  50640. var newKey = {
  50641. frame: beginFrame,
  50642. value: startKey.value,
  50643. inTangent: startKey.inTangent,
  50644. outTangent: startKey.outTangent,
  50645. interpolation: startKey.interpolation
  50646. };
  50647. keys.splice(0, 0, newKey);
  50648. }
  50649. if (endKey.frame < endFrame) {
  50650. var newKey = {
  50651. frame: endFrame,
  50652. value: endKey.value,
  50653. inTangent: endKey.outTangent,
  50654. outTangent: endKey.outTangent,
  50655. interpolation: endKey.interpolation
  50656. };
  50657. keys.push(newKey);
  50658. }
  50659. }
  50660. this._from = beginFrame;
  50661. this._to = endFrame;
  50662. return this;
  50663. };
  50664. /**
  50665. * Start all animations on given targets
  50666. * @param loop defines if animations must loop
  50667. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50668. * @param from defines the from key (optional)
  50669. * @param to defines the to key (optional)
  50670. * @returns the current animation group
  50671. */
  50672. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50673. var _this = this;
  50674. if (loop === void 0) { loop = false; }
  50675. if (speedRatio === void 0) { speedRatio = 1; }
  50676. if (this._isStarted || this._targetedAnimations.length === 0) {
  50677. return this;
  50678. }
  50679. var _loop_1 = function (targetedAnimation) {
  50680. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50681. animatable.onAnimationEnd = function () {
  50682. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50683. _this._checkAnimationGroupEnded(animatable);
  50684. };
  50685. this_1._animatables.push(animatable);
  50686. };
  50687. var this_1 = this;
  50688. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50689. var targetedAnimation = _a[_i];
  50690. _loop_1(targetedAnimation);
  50691. }
  50692. this._speedRatio = speedRatio;
  50693. this._isStarted = true;
  50694. return this;
  50695. };
  50696. /**
  50697. * Pause all animations
  50698. */
  50699. AnimationGroup.prototype.pause = function () {
  50700. if (!this._isStarted) {
  50701. return this;
  50702. }
  50703. for (var index = 0; index < this._animatables.length; index++) {
  50704. var animatable = this._animatables[index];
  50705. animatable.pause();
  50706. }
  50707. return this;
  50708. };
  50709. /**
  50710. * Play all animations to initial state
  50711. * This function will start() the animations if they were not started or will restart() them if they were paused
  50712. * @param loop defines if animations must loop
  50713. */
  50714. AnimationGroup.prototype.play = function (loop) {
  50715. // only if all animatables are ready and exist
  50716. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50717. if (loop !== undefined) {
  50718. for (var index = 0; index < this._animatables.length; index++) {
  50719. var animatable = this._animatables[index];
  50720. animatable.loopAnimation = loop;
  50721. }
  50722. }
  50723. this.restart();
  50724. }
  50725. else {
  50726. this.stop();
  50727. this.start(loop, this._speedRatio);
  50728. }
  50729. return this;
  50730. };
  50731. /**
  50732. * Reset all animations to initial state
  50733. */
  50734. AnimationGroup.prototype.reset = function () {
  50735. if (!this._isStarted) {
  50736. return this;
  50737. }
  50738. for (var index = 0; index < this._animatables.length; index++) {
  50739. var animatable = this._animatables[index];
  50740. animatable.reset();
  50741. }
  50742. return this;
  50743. };
  50744. /**
  50745. * Restart animations from key 0
  50746. */
  50747. AnimationGroup.prototype.restart = function () {
  50748. if (!this._isStarted) {
  50749. return this;
  50750. }
  50751. for (var index = 0; index < this._animatables.length; index++) {
  50752. var animatable = this._animatables[index];
  50753. animatable.restart();
  50754. }
  50755. return this;
  50756. };
  50757. /**
  50758. * Stop all animations
  50759. */
  50760. AnimationGroup.prototype.stop = function () {
  50761. if (!this._isStarted) {
  50762. return this;
  50763. }
  50764. var list = this._animatables.slice();
  50765. for (var index = 0; index < list.length; index++) {
  50766. list[index].stop();
  50767. }
  50768. this._isStarted = false;
  50769. return this;
  50770. };
  50771. /**
  50772. * Set animation weight for all animatables
  50773. * @param weight defines the weight to use
  50774. * @return the animationGroup
  50775. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50776. */
  50777. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50778. for (var index = 0; index < this._animatables.length; index++) {
  50779. var animatable = this._animatables[index];
  50780. animatable.weight = weight;
  50781. }
  50782. return this;
  50783. };
  50784. /**
  50785. * Synchronize and normalize all animatables with a source animatable
  50786. * @param root defines the root animatable to synchronize with
  50787. * @return the animationGroup
  50788. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50789. */
  50790. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50791. for (var index = 0; index < this._animatables.length; index++) {
  50792. var animatable = this._animatables[index];
  50793. animatable.syncWith(root);
  50794. }
  50795. return this;
  50796. };
  50797. /**
  50798. * Goes to a specific frame in this animation group
  50799. * @param frame the frame number to go to
  50800. * @return the animationGroup
  50801. */
  50802. AnimationGroup.prototype.goToFrame = function (frame) {
  50803. if (!this._isStarted) {
  50804. return this;
  50805. }
  50806. for (var index = 0; index < this._animatables.length; index++) {
  50807. var animatable = this._animatables[index];
  50808. animatable.goToFrame(frame);
  50809. }
  50810. return this;
  50811. };
  50812. /**
  50813. * Dispose all associated resources
  50814. */
  50815. AnimationGroup.prototype.dispose = function () {
  50816. this._targetedAnimations = [];
  50817. this._animatables = [];
  50818. var index = this._scene.animationGroups.indexOf(this);
  50819. if (index > -1) {
  50820. this._scene.animationGroups.splice(index, 1);
  50821. }
  50822. };
  50823. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50824. // animatable should be taken out of the array
  50825. var idx = this._animatables.indexOf(animatable);
  50826. if (idx > -1) {
  50827. this._animatables.splice(idx, 1);
  50828. }
  50829. // all animatables were removed? animation group ended!
  50830. if (this._animatables.length === 0) {
  50831. this._isStarted = false;
  50832. this.onAnimationGroupEndObservable.notifyObservers(this);
  50833. }
  50834. };
  50835. return AnimationGroup;
  50836. }());
  50837. BABYLON.AnimationGroup = AnimationGroup;
  50838. })(BABYLON || (BABYLON = {}));
  50839. //# sourceMappingURL=babylon.animationGroup.js.map
  50840. var BABYLON;
  50841. (function (BABYLON) {
  50842. /**
  50843. * Defines a runtime animation
  50844. */
  50845. var RuntimeAnimation = /** @class */ (function () {
  50846. /**
  50847. * Create a new RuntimeAnimation object
  50848. * @param target defines the target of the animation
  50849. * @param animation defines the source animation object
  50850. * @param scene defines the hosting scene
  50851. * @param host defines the initiating Animatable
  50852. */
  50853. function RuntimeAnimation(target, animation, scene, host) {
  50854. var _this = this;
  50855. this._events = new Array();
  50856. /**
  50857. * The current frame of the runtime animation
  50858. */
  50859. this._currentFrame = 0;
  50860. /**
  50861. * The original value of the runtime animation
  50862. */
  50863. this._originalValue = new Array();
  50864. /**
  50865. * The offsets cache of the runtime animation
  50866. */
  50867. this._offsetsCache = {};
  50868. /**
  50869. * The high limits cache of the runtime animation
  50870. */
  50871. this._highLimitsCache = {};
  50872. /**
  50873. * Specifies if the runtime animation has been stopped
  50874. */
  50875. this._stopped = false;
  50876. /**
  50877. * The blending factor of the runtime animation
  50878. */
  50879. this._blendingFactor = 0;
  50880. /**
  50881. * The target path of the runtime animation
  50882. */
  50883. this._targetPath = "";
  50884. /**
  50885. * The weight of the runtime animation
  50886. */
  50887. this._weight = 1.0;
  50888. /**
  50889. * The ratio offset of the runtime animation
  50890. */
  50891. this._ratioOffset = 0;
  50892. /**
  50893. * The previous delay of the runtime animation
  50894. */
  50895. this._previousDelay = 0;
  50896. /**
  50897. * The previous ratio of the runtime animation
  50898. */
  50899. this._previousRatio = 0;
  50900. this._animation = animation;
  50901. this._target = target;
  50902. this._scene = scene;
  50903. this._host = host;
  50904. animation._runtimeAnimations.push(this);
  50905. // Cloning events locally
  50906. var events = animation.getEvents();
  50907. if (events && events.length > 0) {
  50908. events.forEach(function (e) {
  50909. _this._events.push(e._clone());
  50910. });
  50911. }
  50912. }
  50913. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50914. /**
  50915. * Gets the current frame of the runtime animation
  50916. */
  50917. get: function () {
  50918. return this._currentFrame;
  50919. },
  50920. enumerable: true,
  50921. configurable: true
  50922. });
  50923. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50924. /**
  50925. * Gets the weight of the runtime animation
  50926. */
  50927. get: function () {
  50928. return this._weight;
  50929. },
  50930. enumerable: true,
  50931. configurable: true
  50932. });
  50933. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50934. /**
  50935. * Gets the current value of the runtime animation
  50936. */
  50937. get: function () {
  50938. return this._currentValue;
  50939. },
  50940. enumerable: true,
  50941. configurable: true
  50942. });
  50943. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50944. /**
  50945. * Gets the target path of the runtime animation
  50946. */
  50947. get: function () {
  50948. return this._targetPath;
  50949. },
  50950. enumerable: true,
  50951. configurable: true
  50952. });
  50953. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50954. /**
  50955. * Gets the actual target of the runtime animation
  50956. */
  50957. get: function () {
  50958. return this._activeTarget;
  50959. },
  50960. enumerable: true,
  50961. configurable: true
  50962. });
  50963. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50964. /**
  50965. * Gets the animation from the runtime animation
  50966. */
  50967. get: function () {
  50968. return this._animation;
  50969. },
  50970. enumerable: true,
  50971. configurable: true
  50972. });
  50973. /**
  50974. * Resets the runtime animation to the beginning
  50975. * @param restoreOriginal defines whether to restore the target property to the original value
  50976. */
  50977. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50978. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50979. if (restoreOriginal) {
  50980. if (this._target instanceof Array) {
  50981. var index = 0;
  50982. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50983. var target = _a[_i];
  50984. if (this._originalValue[index] !== undefined) {
  50985. this._setValue(target, this._originalValue[index], -1);
  50986. }
  50987. index++;
  50988. }
  50989. }
  50990. else {
  50991. if (this._originalValue[0] !== undefined) {
  50992. this._setValue(this._target, this._originalValue[0], -1);
  50993. }
  50994. }
  50995. }
  50996. this._offsetsCache = {};
  50997. this._highLimitsCache = {};
  50998. this._currentFrame = 0;
  50999. this._blendingFactor = 0;
  51000. this._originalValue = new Array();
  51001. // Events
  51002. for (var index = 0; index < this._events.length; index++) {
  51003. this._events[index].isDone = false;
  51004. }
  51005. };
  51006. /**
  51007. * Specifies if the runtime animation is stopped
  51008. * @returns Boolean specifying if the runtime animation is stopped
  51009. */
  51010. RuntimeAnimation.prototype.isStopped = function () {
  51011. return this._stopped;
  51012. };
  51013. /**
  51014. * Disposes of the runtime animation
  51015. */
  51016. RuntimeAnimation.prototype.dispose = function () {
  51017. var index = this._animation.runtimeAnimations.indexOf(this);
  51018. if (index > -1) {
  51019. this._animation.runtimeAnimations.splice(index, 1);
  51020. }
  51021. };
  51022. /**
  51023. * Interpolates the animation from the current frame
  51024. * @param currentFrame The frame to interpolate the animation to
  51025. * @param repeatCount The number of times that the animation should loop
  51026. * @param loopMode The type of looping mode to use
  51027. * @param offsetValue Animation offset value
  51028. * @param highLimitValue The high limit value
  51029. * @returns The interpolated value
  51030. */
  51031. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51032. this._currentFrame = currentFrame;
  51033. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51034. this._workValue = BABYLON.Matrix.Zero();
  51035. }
  51036. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51037. };
  51038. /**
  51039. * Apply the interpolated value to the target
  51040. * @param currentValue defines the value computed by the animation
  51041. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51042. */
  51043. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51044. if (weight === void 0) { weight = 1.0; }
  51045. if (this._target instanceof Array) {
  51046. var index = 0;
  51047. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51048. var target = _a[_i];
  51049. this._setValue(target, currentValue, weight, index);
  51050. index++;
  51051. }
  51052. }
  51053. else {
  51054. this._setValue(this._target, currentValue, weight);
  51055. }
  51056. };
  51057. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51058. if (targetIndex === void 0) { targetIndex = 0; }
  51059. // Set value
  51060. var path;
  51061. var destination;
  51062. var targetPropertyPath = this._animation.targetPropertyPath;
  51063. if (targetPropertyPath.length > 1) {
  51064. var property = target[targetPropertyPath[0]];
  51065. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51066. property = property[targetPropertyPath[index]];
  51067. }
  51068. path = targetPropertyPath[targetPropertyPath.length - 1];
  51069. destination = property;
  51070. }
  51071. else {
  51072. path = targetPropertyPath[0];
  51073. destination = target;
  51074. }
  51075. this._targetPath = path;
  51076. this._activeTarget = destination;
  51077. this._weight = weight;
  51078. if (this._originalValue[targetIndex] === undefined) {
  51079. var originalValue = void 0;
  51080. if (destination.getRestPose && path === "_matrix") { // For bones
  51081. originalValue = destination.getRestPose();
  51082. }
  51083. else {
  51084. originalValue = destination[path];
  51085. }
  51086. if (originalValue && originalValue.clone) {
  51087. this._originalValue[targetIndex] = originalValue.clone();
  51088. }
  51089. else {
  51090. this._originalValue[targetIndex] = originalValue;
  51091. }
  51092. }
  51093. // Blending
  51094. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51095. if (enableBlending && this._blendingFactor <= 1.0) {
  51096. if (!this._originalBlendValue) {
  51097. var originalValue = destination[path];
  51098. if (originalValue.clone) {
  51099. this._originalBlendValue = originalValue.clone();
  51100. }
  51101. else {
  51102. this._originalBlendValue = originalValue;
  51103. }
  51104. }
  51105. if (this._originalBlendValue.m) { // Matrix
  51106. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51107. if (this._currentValue) {
  51108. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51109. }
  51110. else {
  51111. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51112. }
  51113. }
  51114. else {
  51115. if (this._currentValue) {
  51116. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51117. }
  51118. else {
  51119. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51120. }
  51121. }
  51122. }
  51123. else {
  51124. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51125. }
  51126. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51127. this._blendingFactor += blendingSpeed;
  51128. }
  51129. else {
  51130. this._currentValue = currentValue;
  51131. }
  51132. if (weight !== -1.0) {
  51133. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51134. }
  51135. else {
  51136. destination[path] = this._currentValue;
  51137. }
  51138. if (target.markAsDirty) {
  51139. target.markAsDirty(this._animation.targetProperty);
  51140. }
  51141. };
  51142. /**
  51143. * Gets the loop pmode of the runtime animation
  51144. * @returns Loop Mode
  51145. */
  51146. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51147. if (this._target && this._target.animationPropertiesOverride) {
  51148. return this._target.animationPropertiesOverride.loopMode;
  51149. }
  51150. return this._animation.loopMode;
  51151. };
  51152. /**
  51153. * Move the current animation to a given frame
  51154. * @param frame defines the frame to move to
  51155. */
  51156. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51157. var keys = this._animation.getKeys();
  51158. if (frame < keys[0].frame) {
  51159. frame = keys[0].frame;
  51160. }
  51161. else if (frame > keys[keys.length - 1].frame) {
  51162. frame = keys[keys.length - 1].frame;
  51163. }
  51164. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51165. this.setValue(currentValue, -1);
  51166. };
  51167. /**
  51168. * @hidden Internal use only
  51169. */
  51170. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51171. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51172. this._ratioOffset = this._previousRatio - newRatio;
  51173. };
  51174. /**
  51175. * Execute the current animation
  51176. * @param delay defines the delay to add to the current frame
  51177. * @param from defines the lower bound of the animation range
  51178. * @param to defines the upper bound of the animation range
  51179. * @param loop defines if the current animation must loop
  51180. * @param speedRatio defines the current speed ratio
  51181. * @param weight defines the weight of the animation (default is -1 so no weight)
  51182. * @returns a boolean indicating if the animation has ended
  51183. */
  51184. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51185. if (weight === void 0) { weight = -1.0; }
  51186. var targetPropertyPath = this._animation.targetPropertyPath;
  51187. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51188. this._stopped = true;
  51189. return false;
  51190. }
  51191. var returnValue = true;
  51192. var keys = this._animation.getKeys();
  51193. // Adding a start key at frame 0 if missing
  51194. if (keys[0].frame !== 0) {
  51195. var newKey = { frame: 0, value: keys[0].value };
  51196. keys.splice(0, 0, newKey);
  51197. }
  51198. // Check limits
  51199. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51200. from = keys[0].frame;
  51201. }
  51202. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51203. to = keys[keys.length - 1].frame;
  51204. }
  51205. //to and from cannot be the same key
  51206. if (from === to) {
  51207. if (from > keys[0].frame) {
  51208. from--;
  51209. }
  51210. else if (to < keys[keys.length - 1].frame) {
  51211. to++;
  51212. }
  51213. }
  51214. // Compute ratio
  51215. var range = to - from;
  51216. var offsetValue;
  51217. // ratio represents the frame delta between from and to
  51218. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51219. var highLimitValue = 0;
  51220. this._previousDelay = delay;
  51221. this._previousRatio = ratio;
  51222. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51223. returnValue = false;
  51224. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51225. }
  51226. else {
  51227. // Get max value if required
  51228. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51229. var keyOffset = to.toString() + from.toString();
  51230. if (!this._offsetsCache[keyOffset]) {
  51231. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51232. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51233. switch (this._animation.dataType) {
  51234. // Float
  51235. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51236. this._offsetsCache[keyOffset] = toValue - fromValue;
  51237. break;
  51238. // Quaternion
  51239. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51240. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51241. break;
  51242. // Vector3
  51243. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51244. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51245. // Vector2
  51246. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51247. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51248. // Size
  51249. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51250. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51251. // Color3
  51252. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51253. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51254. default:
  51255. break;
  51256. }
  51257. this._highLimitsCache[keyOffset] = toValue;
  51258. }
  51259. highLimitValue = this._highLimitsCache[keyOffset];
  51260. offsetValue = this._offsetsCache[keyOffset];
  51261. }
  51262. }
  51263. if (offsetValue === undefined) {
  51264. switch (this._animation.dataType) {
  51265. // Float
  51266. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51267. offsetValue = 0;
  51268. break;
  51269. // Quaternion
  51270. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51271. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51272. break;
  51273. // Vector3
  51274. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51275. offsetValue = BABYLON.Vector3.Zero();
  51276. break;
  51277. // Vector2
  51278. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51279. offsetValue = BABYLON.Vector2.Zero();
  51280. break;
  51281. // Size
  51282. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51283. offsetValue = BABYLON.Size.Zero();
  51284. break;
  51285. // Color3
  51286. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51287. offsetValue = BABYLON.Color3.Black();
  51288. }
  51289. }
  51290. // Compute value
  51291. var repeatCount = (ratio / range) >> 0;
  51292. var currentFrame = returnValue ? from + ratio % range : to;
  51293. // Need to normalize?
  51294. if (this._host && this._host.syncRoot) {
  51295. var syncRoot = this._host.syncRoot;
  51296. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51297. currentFrame = from + (to - from) * hostNormalizedFrame;
  51298. }
  51299. // Reset events if looping
  51300. var events = this._events;
  51301. if (range > 0 && this.currentFrame > currentFrame ||
  51302. range < 0 && this.currentFrame < currentFrame) {
  51303. // Need to reset animation events
  51304. for (var index = 0; index < events.length; index++) {
  51305. if (!events[index].onlyOnce) {
  51306. // reset event, the animation is looping
  51307. events[index].isDone = false;
  51308. }
  51309. }
  51310. }
  51311. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51312. // Set value
  51313. this.setValue(currentValue, weight);
  51314. // Check events
  51315. for (var index = 0; index < events.length; index++) {
  51316. // Make sure current frame has passed event frame and that event frame is within the current range
  51317. // Also, handle both forward and reverse animations
  51318. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51319. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51320. var event = events[index];
  51321. if (!event.isDone) {
  51322. // If event should be done only once, remove it.
  51323. if (event.onlyOnce) {
  51324. events.splice(index, 1);
  51325. index--;
  51326. }
  51327. event.isDone = true;
  51328. event.action();
  51329. } // Don't do anything if the event has already be done.
  51330. }
  51331. }
  51332. if (!returnValue) {
  51333. this._stopped = true;
  51334. }
  51335. return returnValue;
  51336. };
  51337. return RuntimeAnimation;
  51338. }());
  51339. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51340. })(BABYLON || (BABYLON = {}));
  51341. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51342. var BABYLON;
  51343. (function (BABYLON) {
  51344. var Animatable = /** @class */ (function () {
  51345. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51346. if (fromFrame === void 0) { fromFrame = 0; }
  51347. if (toFrame === void 0) { toFrame = 100; }
  51348. if (loopAnimation === void 0) { loopAnimation = false; }
  51349. if (speedRatio === void 0) { speedRatio = 1.0; }
  51350. this.target = target;
  51351. this.fromFrame = fromFrame;
  51352. this.toFrame = toFrame;
  51353. this.loopAnimation = loopAnimation;
  51354. this.onAnimationEnd = onAnimationEnd;
  51355. this._localDelayOffset = null;
  51356. this._pausedDelay = null;
  51357. this._runtimeAnimations = new Array();
  51358. this._paused = false;
  51359. this._speedRatio = 1;
  51360. this._weight = -1.0;
  51361. this.animationStarted = false;
  51362. /**
  51363. * Observer raised when the animation ends
  51364. */
  51365. this.onAnimationEndObservable = new BABYLON.Observable();
  51366. this._scene = scene;
  51367. if (animations) {
  51368. this.appendAnimations(target, animations);
  51369. }
  51370. this._speedRatio = speedRatio;
  51371. scene._activeAnimatables.push(this);
  51372. }
  51373. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51374. /**
  51375. * Gets the root Animatable used to synchronize and normalize animations
  51376. */
  51377. get: function () {
  51378. return this._syncRoot;
  51379. },
  51380. enumerable: true,
  51381. configurable: true
  51382. });
  51383. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51384. /**
  51385. * Gets the current frame of the first RuntimeAnimation
  51386. * Used to synchronize Animatables
  51387. */
  51388. get: function () {
  51389. if (this._runtimeAnimations.length === 0) {
  51390. return 0;
  51391. }
  51392. return this._runtimeAnimations[0].currentFrame;
  51393. },
  51394. enumerable: true,
  51395. configurable: true
  51396. });
  51397. Object.defineProperty(Animatable.prototype, "weight", {
  51398. /**
  51399. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51400. */
  51401. get: function () {
  51402. return this._weight;
  51403. },
  51404. set: function (value) {
  51405. if (value === -1) { // -1 is ok and means no weight
  51406. this._weight = -1;
  51407. return;
  51408. }
  51409. // Else weight must be in [0, 1] range
  51410. this._weight = Math.min(Math.max(value, 0), 1.0);
  51411. },
  51412. enumerable: true,
  51413. configurable: true
  51414. });
  51415. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51416. /**
  51417. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51418. */
  51419. get: function () {
  51420. return this._speedRatio;
  51421. },
  51422. set: function (value) {
  51423. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51424. var animation = this._runtimeAnimations[index];
  51425. animation._prepareForSpeedRatioChange(value);
  51426. }
  51427. this._speedRatio = value;
  51428. },
  51429. enumerable: true,
  51430. configurable: true
  51431. });
  51432. // Methods
  51433. /**
  51434. * Synchronize and normalize current Animatable with a source Animatable
  51435. * This is useful when using animation weights and when animations are not of the same length
  51436. * @param root defines the root Animatable to synchronize with
  51437. * @returns the current Animatable
  51438. */
  51439. Animatable.prototype.syncWith = function (root) {
  51440. this._syncRoot = root;
  51441. if (root) {
  51442. // Make sure this animatable will animate after the root
  51443. var index = this._scene._activeAnimatables.indexOf(this);
  51444. if (index > -1) {
  51445. this._scene._activeAnimatables.splice(index, 1);
  51446. this._scene._activeAnimatables.push(this);
  51447. }
  51448. }
  51449. return this;
  51450. };
  51451. Animatable.prototype.getAnimations = function () {
  51452. return this._runtimeAnimations;
  51453. };
  51454. Animatable.prototype.appendAnimations = function (target, animations) {
  51455. for (var index = 0; index < animations.length; index++) {
  51456. var animation = animations[index];
  51457. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51458. }
  51459. };
  51460. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51461. var runtimeAnimations = this._runtimeAnimations;
  51462. for (var index = 0; index < runtimeAnimations.length; index++) {
  51463. if (runtimeAnimations[index].animation.targetProperty === property) {
  51464. return runtimeAnimations[index].animation;
  51465. }
  51466. }
  51467. return null;
  51468. };
  51469. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51470. var runtimeAnimations = this._runtimeAnimations;
  51471. for (var index = 0; index < runtimeAnimations.length; index++) {
  51472. if (runtimeAnimations[index].animation.targetProperty === property) {
  51473. return runtimeAnimations[index];
  51474. }
  51475. }
  51476. return null;
  51477. };
  51478. Animatable.prototype.reset = function () {
  51479. var runtimeAnimations = this._runtimeAnimations;
  51480. for (var index = 0; index < runtimeAnimations.length; index++) {
  51481. runtimeAnimations[index].reset(true);
  51482. }
  51483. this._localDelayOffset = null;
  51484. this._pausedDelay = null;
  51485. };
  51486. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51487. var runtimeAnimations = this._runtimeAnimations;
  51488. for (var index = 0; index < runtimeAnimations.length; index++) {
  51489. runtimeAnimations[index].animation.enableBlending = true;
  51490. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51491. }
  51492. };
  51493. Animatable.prototype.disableBlending = function () {
  51494. var runtimeAnimations = this._runtimeAnimations;
  51495. for (var index = 0; index < runtimeAnimations.length; index++) {
  51496. runtimeAnimations[index].animation.enableBlending = false;
  51497. }
  51498. };
  51499. Animatable.prototype.goToFrame = function (frame) {
  51500. var runtimeAnimations = this._runtimeAnimations;
  51501. if (runtimeAnimations[0]) {
  51502. var fps = runtimeAnimations[0].animation.framePerSecond;
  51503. var currentFrame = runtimeAnimations[0].currentFrame;
  51504. var adjustTime = frame - currentFrame;
  51505. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51506. if (this._localDelayOffset === null) {
  51507. this._localDelayOffset = 0;
  51508. }
  51509. this._localDelayOffset -= delay;
  51510. }
  51511. for (var index = 0; index < runtimeAnimations.length; index++) {
  51512. runtimeAnimations[index].goToFrame(frame);
  51513. }
  51514. };
  51515. Animatable.prototype.pause = function () {
  51516. if (this._paused) {
  51517. return;
  51518. }
  51519. this._paused = true;
  51520. };
  51521. Animatable.prototype.restart = function () {
  51522. this._paused = false;
  51523. };
  51524. Animatable.prototype._raiseOnAnimationEnd = function () {
  51525. if (this.onAnimationEnd) {
  51526. this.onAnimationEnd();
  51527. }
  51528. this.onAnimationEndObservable.notifyObservers(this);
  51529. };
  51530. Animatable.prototype.stop = function (animationName) {
  51531. if (animationName) {
  51532. var idx = this._scene._activeAnimatables.indexOf(this);
  51533. if (idx > -1) {
  51534. var runtimeAnimations = this._runtimeAnimations;
  51535. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51536. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51537. continue;
  51538. }
  51539. runtimeAnimations[index].dispose();
  51540. runtimeAnimations.splice(index, 1);
  51541. }
  51542. if (runtimeAnimations.length == 0) {
  51543. this._scene._activeAnimatables.splice(idx, 1);
  51544. this._raiseOnAnimationEnd();
  51545. }
  51546. }
  51547. }
  51548. else {
  51549. var index = this._scene._activeAnimatables.indexOf(this);
  51550. if (index > -1) {
  51551. this._scene._activeAnimatables.splice(index, 1);
  51552. var runtimeAnimations = this._runtimeAnimations;
  51553. for (var index = 0; index < runtimeAnimations.length; index++) {
  51554. runtimeAnimations[index].dispose();
  51555. }
  51556. this._raiseOnAnimationEnd();
  51557. }
  51558. }
  51559. };
  51560. /**
  51561. * Wait asynchronously for the animation to end
  51562. * @returns a promise which will be fullfilled when the animation ends
  51563. */
  51564. Animatable.prototype.waitAsync = function () {
  51565. var _this = this;
  51566. return new Promise(function (resolve, reject) {
  51567. _this.onAnimationEndObservable.add(function () {
  51568. resolve(_this);
  51569. }, undefined, undefined, _this, true);
  51570. });
  51571. };
  51572. /** @hidden */
  51573. Animatable.prototype._animate = function (delay) {
  51574. if (this._paused) {
  51575. this.animationStarted = false;
  51576. if (this._pausedDelay === null) {
  51577. this._pausedDelay = delay;
  51578. }
  51579. return true;
  51580. }
  51581. if (this._localDelayOffset === null) {
  51582. this._localDelayOffset = delay;
  51583. this._pausedDelay = null;
  51584. }
  51585. else if (this._pausedDelay !== null) {
  51586. this._localDelayOffset += delay - this._pausedDelay;
  51587. this._pausedDelay = null;
  51588. }
  51589. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51590. return true;
  51591. }
  51592. // Animating
  51593. var running = false;
  51594. var runtimeAnimations = this._runtimeAnimations;
  51595. var index;
  51596. for (index = 0; index < runtimeAnimations.length; index++) {
  51597. var animation = runtimeAnimations[index];
  51598. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51599. running = running || isRunning;
  51600. }
  51601. this.animationStarted = running;
  51602. if (!running) {
  51603. // Remove from active animatables
  51604. index = this._scene._activeAnimatables.indexOf(this);
  51605. this._scene._activeAnimatables.splice(index, 1);
  51606. // Dispose all runtime animations
  51607. for (index = 0; index < runtimeAnimations.length; index++) {
  51608. runtimeAnimations[index].dispose();
  51609. }
  51610. this._raiseOnAnimationEnd();
  51611. this.onAnimationEnd = null;
  51612. this.onAnimationEndObservable.clear();
  51613. }
  51614. return running;
  51615. };
  51616. return Animatable;
  51617. }());
  51618. BABYLON.Animatable = Animatable;
  51619. })(BABYLON || (BABYLON = {}));
  51620. //# sourceMappingURL=babylon.animatable.js.map
  51621. var BABYLON;
  51622. (function (BABYLON) {
  51623. var EasingFunction = /** @class */ (function () {
  51624. function EasingFunction() {
  51625. // Properties
  51626. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51627. }
  51628. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51629. get: function () {
  51630. return EasingFunction._EASINGMODE_EASEIN;
  51631. },
  51632. enumerable: true,
  51633. configurable: true
  51634. });
  51635. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51636. get: function () {
  51637. return EasingFunction._EASINGMODE_EASEOUT;
  51638. },
  51639. enumerable: true,
  51640. configurable: true
  51641. });
  51642. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51643. get: function () {
  51644. return EasingFunction._EASINGMODE_EASEINOUT;
  51645. },
  51646. enumerable: true,
  51647. configurable: true
  51648. });
  51649. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51650. var n = Math.min(Math.max(easingMode, 0), 2);
  51651. this._easingMode = n;
  51652. };
  51653. EasingFunction.prototype.getEasingMode = function () {
  51654. return this._easingMode;
  51655. };
  51656. EasingFunction.prototype.easeInCore = function (gradient) {
  51657. throw new Error('You must implement this method');
  51658. };
  51659. EasingFunction.prototype.ease = function (gradient) {
  51660. switch (this._easingMode) {
  51661. case EasingFunction.EASINGMODE_EASEIN:
  51662. return this.easeInCore(gradient);
  51663. case EasingFunction.EASINGMODE_EASEOUT:
  51664. return (1 - this.easeInCore(1 - gradient));
  51665. }
  51666. if (gradient >= 0.5) {
  51667. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51668. }
  51669. return (this.easeInCore(gradient * 2) * 0.5);
  51670. };
  51671. //Statics
  51672. EasingFunction._EASINGMODE_EASEIN = 0;
  51673. EasingFunction._EASINGMODE_EASEOUT = 1;
  51674. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51675. return EasingFunction;
  51676. }());
  51677. BABYLON.EasingFunction = EasingFunction;
  51678. var CircleEase = /** @class */ (function (_super) {
  51679. __extends(CircleEase, _super);
  51680. function CircleEase() {
  51681. return _super !== null && _super.apply(this, arguments) || this;
  51682. }
  51683. CircleEase.prototype.easeInCore = function (gradient) {
  51684. gradient = Math.max(0, Math.min(1, gradient));
  51685. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51686. };
  51687. return CircleEase;
  51688. }(EasingFunction));
  51689. BABYLON.CircleEase = CircleEase;
  51690. var BackEase = /** @class */ (function (_super) {
  51691. __extends(BackEase, _super);
  51692. function BackEase(amplitude) {
  51693. if (amplitude === void 0) { amplitude = 1; }
  51694. var _this = _super.call(this) || this;
  51695. _this.amplitude = amplitude;
  51696. return _this;
  51697. }
  51698. BackEase.prototype.easeInCore = function (gradient) {
  51699. var num = Math.max(0, this.amplitude);
  51700. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51701. };
  51702. return BackEase;
  51703. }(EasingFunction));
  51704. BABYLON.BackEase = BackEase;
  51705. var BounceEase = /** @class */ (function (_super) {
  51706. __extends(BounceEase, _super);
  51707. function BounceEase(bounces, bounciness) {
  51708. if (bounces === void 0) { bounces = 3; }
  51709. if (bounciness === void 0) { bounciness = 2; }
  51710. var _this = _super.call(this) || this;
  51711. _this.bounces = bounces;
  51712. _this.bounciness = bounciness;
  51713. return _this;
  51714. }
  51715. BounceEase.prototype.easeInCore = function (gradient) {
  51716. var y = Math.max(0.0, this.bounces);
  51717. var bounciness = this.bounciness;
  51718. if (bounciness <= 1.0) {
  51719. bounciness = 1.001;
  51720. }
  51721. var num9 = Math.pow(bounciness, y);
  51722. var num5 = 1.0 - bounciness;
  51723. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51724. var num15 = gradient * num4;
  51725. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51726. var num3 = Math.floor(num65);
  51727. var num13 = num3 + 1.0;
  51728. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51729. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51730. var num7 = (num8 + num12) * 0.5;
  51731. var num6 = gradient - num7;
  51732. var num2 = num7 - num8;
  51733. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51734. };
  51735. return BounceEase;
  51736. }(EasingFunction));
  51737. BABYLON.BounceEase = BounceEase;
  51738. var CubicEase = /** @class */ (function (_super) {
  51739. __extends(CubicEase, _super);
  51740. function CubicEase() {
  51741. return _super !== null && _super.apply(this, arguments) || this;
  51742. }
  51743. CubicEase.prototype.easeInCore = function (gradient) {
  51744. return (gradient * gradient * gradient);
  51745. };
  51746. return CubicEase;
  51747. }(EasingFunction));
  51748. BABYLON.CubicEase = CubicEase;
  51749. var ElasticEase = /** @class */ (function (_super) {
  51750. __extends(ElasticEase, _super);
  51751. function ElasticEase(oscillations, springiness) {
  51752. if (oscillations === void 0) { oscillations = 3; }
  51753. if (springiness === void 0) { springiness = 3; }
  51754. var _this = _super.call(this) || this;
  51755. _this.oscillations = oscillations;
  51756. _this.springiness = springiness;
  51757. return _this;
  51758. }
  51759. ElasticEase.prototype.easeInCore = function (gradient) {
  51760. var num2;
  51761. var num3 = Math.max(0.0, this.oscillations);
  51762. var num = Math.max(0.0, this.springiness);
  51763. if (num == 0) {
  51764. num2 = gradient;
  51765. }
  51766. else {
  51767. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51768. }
  51769. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51770. };
  51771. return ElasticEase;
  51772. }(EasingFunction));
  51773. BABYLON.ElasticEase = ElasticEase;
  51774. var ExponentialEase = /** @class */ (function (_super) {
  51775. __extends(ExponentialEase, _super);
  51776. function ExponentialEase(exponent) {
  51777. if (exponent === void 0) { exponent = 2; }
  51778. var _this = _super.call(this) || this;
  51779. _this.exponent = exponent;
  51780. return _this;
  51781. }
  51782. ExponentialEase.prototype.easeInCore = function (gradient) {
  51783. if (this.exponent <= 0) {
  51784. return gradient;
  51785. }
  51786. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51787. };
  51788. return ExponentialEase;
  51789. }(EasingFunction));
  51790. BABYLON.ExponentialEase = ExponentialEase;
  51791. var PowerEase = /** @class */ (function (_super) {
  51792. __extends(PowerEase, _super);
  51793. function PowerEase(power) {
  51794. if (power === void 0) { power = 2; }
  51795. var _this = _super.call(this) || this;
  51796. _this.power = power;
  51797. return _this;
  51798. }
  51799. PowerEase.prototype.easeInCore = function (gradient) {
  51800. var y = Math.max(0.0, this.power);
  51801. return Math.pow(gradient, y);
  51802. };
  51803. return PowerEase;
  51804. }(EasingFunction));
  51805. BABYLON.PowerEase = PowerEase;
  51806. var QuadraticEase = /** @class */ (function (_super) {
  51807. __extends(QuadraticEase, _super);
  51808. function QuadraticEase() {
  51809. return _super !== null && _super.apply(this, arguments) || this;
  51810. }
  51811. QuadraticEase.prototype.easeInCore = function (gradient) {
  51812. return (gradient * gradient);
  51813. };
  51814. return QuadraticEase;
  51815. }(EasingFunction));
  51816. BABYLON.QuadraticEase = QuadraticEase;
  51817. var QuarticEase = /** @class */ (function (_super) {
  51818. __extends(QuarticEase, _super);
  51819. function QuarticEase() {
  51820. return _super !== null && _super.apply(this, arguments) || this;
  51821. }
  51822. QuarticEase.prototype.easeInCore = function (gradient) {
  51823. return (gradient * gradient * gradient * gradient);
  51824. };
  51825. return QuarticEase;
  51826. }(EasingFunction));
  51827. BABYLON.QuarticEase = QuarticEase;
  51828. var QuinticEase = /** @class */ (function (_super) {
  51829. __extends(QuinticEase, _super);
  51830. function QuinticEase() {
  51831. return _super !== null && _super.apply(this, arguments) || this;
  51832. }
  51833. QuinticEase.prototype.easeInCore = function (gradient) {
  51834. return (gradient * gradient * gradient * gradient * gradient);
  51835. };
  51836. return QuinticEase;
  51837. }(EasingFunction));
  51838. BABYLON.QuinticEase = QuinticEase;
  51839. var SineEase = /** @class */ (function (_super) {
  51840. __extends(SineEase, _super);
  51841. function SineEase() {
  51842. return _super !== null && _super.apply(this, arguments) || this;
  51843. }
  51844. SineEase.prototype.easeInCore = function (gradient) {
  51845. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51846. };
  51847. return SineEase;
  51848. }(EasingFunction));
  51849. BABYLON.SineEase = SineEase;
  51850. var BezierCurveEase = /** @class */ (function (_super) {
  51851. __extends(BezierCurveEase, _super);
  51852. function BezierCurveEase(x1, y1, x2, y2) {
  51853. if (x1 === void 0) { x1 = 0; }
  51854. if (y1 === void 0) { y1 = 0; }
  51855. if (x2 === void 0) { x2 = 1; }
  51856. if (y2 === void 0) { y2 = 1; }
  51857. var _this = _super.call(this) || this;
  51858. _this.x1 = x1;
  51859. _this.y1 = y1;
  51860. _this.x2 = x2;
  51861. _this.y2 = y2;
  51862. return _this;
  51863. }
  51864. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51865. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51866. };
  51867. return BezierCurveEase;
  51868. }(EasingFunction));
  51869. BABYLON.BezierCurveEase = BezierCurveEase;
  51870. })(BABYLON || (BABYLON = {}));
  51871. //# sourceMappingURL=babylon.easing.js.map
  51872. var BABYLON;
  51873. (function (BABYLON) {
  51874. /**
  51875. * A Condition applied to an Action
  51876. */
  51877. var Condition = /** @class */ (function () {
  51878. /**
  51879. * Creates a new Condition
  51880. * @param actionManager the manager of the action the condition is applied to
  51881. */
  51882. function Condition(actionManager) {
  51883. this._actionManager = actionManager;
  51884. }
  51885. /**
  51886. * Check if the current condition is valid
  51887. * @returns a boolean
  51888. */
  51889. Condition.prototype.isValid = function () {
  51890. return true;
  51891. };
  51892. /**
  51893. * Internal only
  51894. * @hidden
  51895. */
  51896. Condition.prototype._getProperty = function (propertyPath) {
  51897. return this._actionManager._getProperty(propertyPath);
  51898. };
  51899. /**
  51900. * Internal only
  51901. * @hidden
  51902. */
  51903. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51904. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51905. };
  51906. /**
  51907. * Serialize placeholder for child classes
  51908. * @returns the serialized object
  51909. */
  51910. Condition.prototype.serialize = function () {
  51911. };
  51912. /**
  51913. * Internal only
  51914. * @hidden
  51915. */
  51916. Condition.prototype._serialize = function (serializedCondition) {
  51917. return {
  51918. type: 2,
  51919. children: [],
  51920. name: serializedCondition.name,
  51921. properties: serializedCondition.properties
  51922. };
  51923. };
  51924. return Condition;
  51925. }());
  51926. BABYLON.Condition = Condition;
  51927. /**
  51928. * Defines specific conditional operators as extensions of Condition
  51929. */
  51930. var ValueCondition = /** @class */ (function (_super) {
  51931. __extends(ValueCondition, _super);
  51932. /**
  51933. * Creates a new ValueCondition
  51934. * @param actionManager manager for the action the condition applies to
  51935. * @param target for the action
  51936. * @param propertyPath path to specify the property of the target the conditional operator uses
  51937. * @param value the value compared by the conditional operator against the current value of the property
  51938. * @param operator the conditional operator, default ValueCondition.IsEqual
  51939. */
  51940. function ValueCondition(actionManager, target,
  51941. /** path to specify the property of the target the conditional operator uses */
  51942. propertyPath,
  51943. /** the value compared by the conditional operator against the current value of the property */
  51944. value,
  51945. /** the conditional operator, default ValueCondition.IsEqual */
  51946. operator) {
  51947. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51948. var _this = _super.call(this, actionManager) || this;
  51949. _this.propertyPath = propertyPath;
  51950. _this.value = value;
  51951. _this.operator = operator;
  51952. _this._target = target;
  51953. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51954. _this._property = _this._getProperty(_this.propertyPath);
  51955. return _this;
  51956. }
  51957. Object.defineProperty(ValueCondition, "IsEqual", {
  51958. /**
  51959. * returns the number for IsEqual
  51960. */
  51961. get: function () {
  51962. return ValueCondition._IsEqual;
  51963. },
  51964. enumerable: true,
  51965. configurable: true
  51966. });
  51967. Object.defineProperty(ValueCondition, "IsDifferent", {
  51968. /**
  51969. * Returns the number for IsDifferent
  51970. */
  51971. get: function () {
  51972. return ValueCondition._IsDifferent;
  51973. },
  51974. enumerable: true,
  51975. configurable: true
  51976. });
  51977. Object.defineProperty(ValueCondition, "IsGreater", {
  51978. /**
  51979. * Returns the number for IsGreater
  51980. */
  51981. get: function () {
  51982. return ValueCondition._IsGreater;
  51983. },
  51984. enumerable: true,
  51985. configurable: true
  51986. });
  51987. Object.defineProperty(ValueCondition, "IsLesser", {
  51988. /**
  51989. * Returns the number for IsLesser
  51990. */
  51991. get: function () {
  51992. return ValueCondition._IsLesser;
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. /**
  51998. * Compares the given value with the property value for the specified conditional operator
  51999. * @returns the result of the comparison
  52000. */
  52001. ValueCondition.prototype.isValid = function () {
  52002. switch (this.operator) {
  52003. case ValueCondition.IsGreater:
  52004. return this._effectiveTarget[this._property] > this.value;
  52005. case ValueCondition.IsLesser:
  52006. return this._effectiveTarget[this._property] < this.value;
  52007. case ValueCondition.IsEqual:
  52008. case ValueCondition.IsDifferent:
  52009. var check;
  52010. if (this.value.equals) {
  52011. check = this.value.equals(this._effectiveTarget[this._property]);
  52012. }
  52013. else {
  52014. check = this.value === this._effectiveTarget[this._property];
  52015. }
  52016. return this.operator === ValueCondition.IsEqual ? check : !check;
  52017. }
  52018. return false;
  52019. };
  52020. /**
  52021. * Serialize the ValueCondition into a JSON compatible object
  52022. * @returns serialization object
  52023. */
  52024. ValueCondition.prototype.serialize = function () {
  52025. return this._serialize({
  52026. name: "ValueCondition",
  52027. properties: [
  52028. BABYLON.Action._GetTargetProperty(this._target),
  52029. { name: "propertyPath", value: this.propertyPath },
  52030. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52031. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52032. ]
  52033. });
  52034. };
  52035. /**
  52036. * Gets the name of the conditional operator for the ValueCondition
  52037. * @param operator the conditional operator
  52038. * @returns the name
  52039. */
  52040. ValueCondition.GetOperatorName = function (operator) {
  52041. switch (operator) {
  52042. case ValueCondition._IsEqual: return "IsEqual";
  52043. case ValueCondition._IsDifferent: return "IsDifferent";
  52044. case ValueCondition._IsGreater: return "IsGreater";
  52045. case ValueCondition._IsLesser: return "IsLesser";
  52046. default: return "";
  52047. }
  52048. };
  52049. /**
  52050. * Internal only
  52051. * @hidden
  52052. */
  52053. ValueCondition._IsEqual = 0;
  52054. /**
  52055. * Internal only
  52056. * @hidden
  52057. */
  52058. ValueCondition._IsDifferent = 1;
  52059. /**
  52060. * Internal only
  52061. * @hidden
  52062. */
  52063. ValueCondition._IsGreater = 2;
  52064. /**
  52065. * Internal only
  52066. * @hidden
  52067. */
  52068. ValueCondition._IsLesser = 3;
  52069. return ValueCondition;
  52070. }(Condition));
  52071. BABYLON.ValueCondition = ValueCondition;
  52072. /**
  52073. * Defines a predicate condition as an extension of Condition
  52074. */
  52075. var PredicateCondition = /** @class */ (function (_super) {
  52076. __extends(PredicateCondition, _super);
  52077. /**
  52078. * Creates a new PredicateCondition
  52079. * @param actionManager manager for the action the condition applies to
  52080. * @param predicate defines the predicate function used to validate the condition
  52081. */
  52082. function PredicateCondition(actionManager,
  52083. /** defines the predicate function used to validate the condition */
  52084. predicate) {
  52085. var _this = _super.call(this, actionManager) || this;
  52086. _this.predicate = predicate;
  52087. return _this;
  52088. }
  52089. /**
  52090. * @returns the validity of the predicate condition
  52091. */
  52092. PredicateCondition.prototype.isValid = function () {
  52093. return this.predicate();
  52094. };
  52095. return PredicateCondition;
  52096. }(Condition));
  52097. BABYLON.PredicateCondition = PredicateCondition;
  52098. /**
  52099. * Defines a state condition as an extension of Condition
  52100. */
  52101. var StateCondition = /** @class */ (function (_super) {
  52102. __extends(StateCondition, _super);
  52103. /**
  52104. * Creates a new StateCondition
  52105. * @param actionManager manager for the action the condition applies to
  52106. * @param target of the condition
  52107. * @param value to compare with target state
  52108. */
  52109. function StateCondition(actionManager, target, value) {
  52110. var _this = _super.call(this, actionManager) || this;
  52111. _this.value = value;
  52112. _this._target = target;
  52113. return _this;
  52114. }
  52115. /**
  52116. * @returns the validity of the state
  52117. */
  52118. StateCondition.prototype.isValid = function () {
  52119. return this._target.state === this.value;
  52120. };
  52121. /**
  52122. * Serialize the StateCondition into a JSON compatible object
  52123. * @returns serialization object
  52124. */
  52125. StateCondition.prototype.serialize = function () {
  52126. return this._serialize({
  52127. name: "StateCondition",
  52128. properties: [
  52129. BABYLON.Action._GetTargetProperty(this._target),
  52130. { name: "value", value: this.value }
  52131. ]
  52132. });
  52133. };
  52134. return StateCondition;
  52135. }(Condition));
  52136. BABYLON.StateCondition = StateCondition;
  52137. })(BABYLON || (BABYLON = {}));
  52138. //# sourceMappingURL=babylon.condition.js.map
  52139. var BABYLON;
  52140. (function (BABYLON) {
  52141. /**
  52142. * The action to be carried out following a trigger
  52143. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52144. */
  52145. var Action = /** @class */ (function () {
  52146. /**
  52147. * Creates a new Action
  52148. * @param triggerOptions the trigger, with or without parameters, for the action
  52149. * @param condition an optional determinant of action
  52150. */
  52151. function Action(
  52152. /** the trigger, with or without parameters, for the action */
  52153. triggerOptions, condition) {
  52154. this.triggerOptions = triggerOptions;
  52155. /**
  52156. * An event triggered prior to action being executed.
  52157. */
  52158. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52159. if (triggerOptions.parameter) {
  52160. this.trigger = triggerOptions.trigger;
  52161. this._triggerParameter = triggerOptions.parameter;
  52162. }
  52163. else {
  52164. this.trigger = triggerOptions;
  52165. }
  52166. this._nextActiveAction = this;
  52167. this._condition = condition;
  52168. }
  52169. /**
  52170. * Internal only
  52171. * @hidden
  52172. */
  52173. Action.prototype._prepare = function () {
  52174. };
  52175. /**
  52176. * Gets the trigger parameters
  52177. * @returns the trigger parameters
  52178. */
  52179. Action.prototype.getTriggerParameter = function () {
  52180. return this._triggerParameter;
  52181. };
  52182. /**
  52183. * Internal only - executes current action event
  52184. * @hidden
  52185. */
  52186. Action.prototype._executeCurrent = function (evt) {
  52187. if (this._nextActiveAction._condition) {
  52188. var condition = this._nextActiveAction._condition;
  52189. var currentRenderId = this._actionManager.getScene().getRenderId();
  52190. // We cache the current evaluation for the current frame
  52191. if (condition._evaluationId === currentRenderId) {
  52192. if (!condition._currentResult) {
  52193. return;
  52194. }
  52195. }
  52196. else {
  52197. condition._evaluationId = currentRenderId;
  52198. if (!condition.isValid()) {
  52199. condition._currentResult = false;
  52200. return;
  52201. }
  52202. condition._currentResult = true;
  52203. }
  52204. }
  52205. this.onBeforeExecuteObservable.notifyObservers(this);
  52206. this._nextActiveAction.execute(evt);
  52207. this.skipToNextActiveAction();
  52208. };
  52209. /**
  52210. * Execute placeholder for child classes
  52211. * @param evt optional action event
  52212. */
  52213. Action.prototype.execute = function (evt) {
  52214. };
  52215. /**
  52216. * Skips to next active action
  52217. */
  52218. Action.prototype.skipToNextActiveAction = function () {
  52219. if (this._nextActiveAction._child) {
  52220. if (!this._nextActiveAction._child._actionManager) {
  52221. this._nextActiveAction._child._actionManager = this._actionManager;
  52222. }
  52223. this._nextActiveAction = this._nextActiveAction._child;
  52224. }
  52225. else {
  52226. this._nextActiveAction = this;
  52227. }
  52228. };
  52229. /**
  52230. * Adds action to chain of actions, may be a DoNothingAction
  52231. * @param action defines the next action to execute
  52232. * @returns The action passed in
  52233. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52234. */
  52235. Action.prototype.then = function (action) {
  52236. this._child = action;
  52237. action._actionManager = this._actionManager;
  52238. action._prepare();
  52239. return action;
  52240. };
  52241. /**
  52242. * Internal only
  52243. * @hidden
  52244. */
  52245. Action.prototype._getProperty = function (propertyPath) {
  52246. return this._actionManager._getProperty(propertyPath);
  52247. };
  52248. /**
  52249. * Internal only
  52250. * @hidden
  52251. */
  52252. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52253. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52254. };
  52255. /**
  52256. * Serialize placeholder for child classes
  52257. * @param parent of child
  52258. * @returns the serialized object
  52259. */
  52260. Action.prototype.serialize = function (parent) {
  52261. };
  52262. /**
  52263. * Internal only called by serialize
  52264. * @hidden
  52265. */
  52266. Action.prototype._serialize = function (serializedAction, parent) {
  52267. var serializationObject = {
  52268. type: 1,
  52269. children: [],
  52270. name: serializedAction.name,
  52271. properties: serializedAction.properties || []
  52272. };
  52273. // Serialize child
  52274. if (this._child) {
  52275. this._child.serialize(serializationObject);
  52276. }
  52277. // Check if "this" has a condition
  52278. if (this._condition) {
  52279. var serializedCondition = this._condition.serialize();
  52280. serializedCondition.children.push(serializationObject);
  52281. if (parent) {
  52282. parent.children.push(serializedCondition);
  52283. }
  52284. return serializedCondition;
  52285. }
  52286. if (parent) {
  52287. parent.children.push(serializationObject);
  52288. }
  52289. return serializationObject;
  52290. };
  52291. /**
  52292. * Internal only
  52293. * @hidden
  52294. */
  52295. Action._SerializeValueAsString = function (value) {
  52296. if (typeof value === "number") {
  52297. return value.toString();
  52298. }
  52299. if (typeof value === "boolean") {
  52300. return value ? "true" : "false";
  52301. }
  52302. if (value instanceof BABYLON.Vector2) {
  52303. return value.x + ", " + value.y;
  52304. }
  52305. if (value instanceof BABYLON.Vector3) {
  52306. return value.x + ", " + value.y + ", " + value.z;
  52307. }
  52308. if (value instanceof BABYLON.Color3) {
  52309. return value.r + ", " + value.g + ", " + value.b;
  52310. }
  52311. if (value instanceof BABYLON.Color4) {
  52312. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52313. }
  52314. return value; // string
  52315. };
  52316. /**
  52317. * Internal only
  52318. * @hidden
  52319. */
  52320. Action._GetTargetProperty = function (target) {
  52321. return {
  52322. name: "target",
  52323. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52324. : target instanceof BABYLON.Light ? "LightProperties"
  52325. : target instanceof BABYLON.Camera ? "CameraProperties"
  52326. : "SceneProperties",
  52327. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52328. };
  52329. };
  52330. return Action;
  52331. }());
  52332. BABYLON.Action = Action;
  52333. })(BABYLON || (BABYLON = {}));
  52334. //# sourceMappingURL=babylon.action.js.map
  52335. var BABYLON;
  52336. (function (BABYLON) {
  52337. /**
  52338. * ActionEvent is the event being sent when an action is triggered.
  52339. */
  52340. var ActionEvent = /** @class */ (function () {
  52341. /**
  52342. * Creates a new ActionEvent
  52343. * @param source The mesh or sprite that triggered the action
  52344. * @param pointerX The X mouse cursor position at the time of the event
  52345. * @param pointerY The Y mouse cursor position at the time of the event
  52346. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52347. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52348. * @param additionalData additional data for the event
  52349. */
  52350. function ActionEvent(
  52351. /** The mesh or sprite that triggered the action */
  52352. source,
  52353. /** The X mouse cursor position at the time of the event */
  52354. pointerX,
  52355. /** The Y mouse cursor position at the time of the event */
  52356. pointerY,
  52357. /** The mesh that is currently pointed at (can be null) */
  52358. meshUnderPointer,
  52359. /** the original (browser) event that triggered the ActionEvent */
  52360. sourceEvent,
  52361. /** additional data for the event */
  52362. additionalData) {
  52363. this.source = source;
  52364. this.pointerX = pointerX;
  52365. this.pointerY = pointerY;
  52366. this.meshUnderPointer = meshUnderPointer;
  52367. this.sourceEvent = sourceEvent;
  52368. this.additionalData = additionalData;
  52369. }
  52370. /**
  52371. * Helper function to auto-create an ActionEvent from a source mesh.
  52372. * @param source The source mesh that triggered the event
  52373. * @param evt The original (browser) event
  52374. * @param additionalData additional data for the event
  52375. * @returns the new ActionEvent
  52376. */
  52377. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52378. var scene = source.getScene();
  52379. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52380. };
  52381. /**
  52382. * Helper function to auto-create an ActionEvent from a source sprite
  52383. * @param source The source sprite that triggered the event
  52384. * @param scene Scene associated with the sprite
  52385. * @param evt The original (browser) event
  52386. * @param additionalData additional data for the event
  52387. * @returns the new ActionEvent
  52388. */
  52389. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52390. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52391. };
  52392. /**
  52393. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52394. * @param scene the scene where the event occurred
  52395. * @param evt The original (browser) event
  52396. * @returns the new ActionEvent
  52397. */
  52398. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52399. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52400. };
  52401. /**
  52402. * Helper function to auto-create an ActionEvent from a primitive
  52403. * @param prim defines the target primitive
  52404. * @param pointerPos defines the pointer position
  52405. * @param evt The original (browser) event
  52406. * @param additionalData additional data for the event
  52407. * @returns the new ActionEvent
  52408. */
  52409. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52410. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52411. };
  52412. return ActionEvent;
  52413. }());
  52414. BABYLON.ActionEvent = ActionEvent;
  52415. /**
  52416. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52417. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52418. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52419. */
  52420. var ActionManager = /** @class */ (function () {
  52421. /**
  52422. * Creates a new action manager
  52423. * @param scene defines the hosting scene
  52424. */
  52425. function ActionManager(scene) {
  52426. // Members
  52427. /** Gets the list of actions */
  52428. this.actions = new Array();
  52429. /** Gets the cursor to use when hovering items */
  52430. this.hoverCursor = '';
  52431. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52432. scene._actionManagers.push(this);
  52433. }
  52434. Object.defineProperty(ActionManager, "NothingTrigger", {
  52435. /**
  52436. * Nothing
  52437. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52438. */
  52439. get: function () {
  52440. return ActionManager._NothingTrigger;
  52441. },
  52442. enumerable: true,
  52443. configurable: true
  52444. });
  52445. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52446. /**
  52447. * On pick
  52448. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52449. */
  52450. get: function () {
  52451. return ActionManager._OnPickTrigger;
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52457. /**
  52458. * On left pick
  52459. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52460. */
  52461. get: function () {
  52462. return ActionManager._OnLeftPickTrigger;
  52463. },
  52464. enumerable: true,
  52465. configurable: true
  52466. });
  52467. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52468. /**
  52469. * On right pick
  52470. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52471. */
  52472. get: function () {
  52473. return ActionManager._OnRightPickTrigger;
  52474. },
  52475. enumerable: true,
  52476. configurable: true
  52477. });
  52478. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52479. /**
  52480. * On center pick
  52481. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52482. */
  52483. get: function () {
  52484. return ActionManager._OnCenterPickTrigger;
  52485. },
  52486. enumerable: true,
  52487. configurable: true
  52488. });
  52489. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52490. /**
  52491. * On pick down
  52492. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52493. */
  52494. get: function () {
  52495. return ActionManager._OnPickDownTrigger;
  52496. },
  52497. enumerable: true,
  52498. configurable: true
  52499. });
  52500. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52501. /**
  52502. * On double pick
  52503. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52504. */
  52505. get: function () {
  52506. return ActionManager._OnDoublePickTrigger;
  52507. },
  52508. enumerable: true,
  52509. configurable: true
  52510. });
  52511. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52512. /**
  52513. * On pick up
  52514. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52515. */
  52516. get: function () {
  52517. return ActionManager._OnPickUpTrigger;
  52518. },
  52519. enumerable: true,
  52520. configurable: true
  52521. });
  52522. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52523. /**
  52524. * On pick out.
  52525. * This trigger will only be raised if you also declared a OnPickDown
  52526. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52527. */
  52528. get: function () {
  52529. return ActionManager._OnPickOutTrigger;
  52530. },
  52531. enumerable: true,
  52532. configurable: true
  52533. });
  52534. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52535. /**
  52536. * On long press
  52537. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52538. */
  52539. get: function () {
  52540. return ActionManager._OnLongPressTrigger;
  52541. },
  52542. enumerable: true,
  52543. configurable: true
  52544. });
  52545. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52546. /**
  52547. * On pointer over
  52548. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52549. */
  52550. get: function () {
  52551. return ActionManager._OnPointerOverTrigger;
  52552. },
  52553. enumerable: true,
  52554. configurable: true
  52555. });
  52556. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52557. /**
  52558. * On pointer out
  52559. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52560. */
  52561. get: function () {
  52562. return ActionManager._OnPointerOutTrigger;
  52563. },
  52564. enumerable: true,
  52565. configurable: true
  52566. });
  52567. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52568. /**
  52569. * On every frame
  52570. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52571. */
  52572. get: function () {
  52573. return ActionManager._OnEveryFrameTrigger;
  52574. },
  52575. enumerable: true,
  52576. configurable: true
  52577. });
  52578. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52579. /**
  52580. * On intersection enter
  52581. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52582. */
  52583. get: function () {
  52584. return ActionManager._OnIntersectionEnterTrigger;
  52585. },
  52586. enumerable: true,
  52587. configurable: true
  52588. });
  52589. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52590. /**
  52591. * On intersection exit
  52592. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52593. */
  52594. get: function () {
  52595. return ActionManager._OnIntersectionExitTrigger;
  52596. },
  52597. enumerable: true,
  52598. configurable: true
  52599. });
  52600. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52601. /**
  52602. * On key down
  52603. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52604. */
  52605. get: function () {
  52606. return ActionManager._OnKeyDownTrigger;
  52607. },
  52608. enumerable: true,
  52609. configurable: true
  52610. });
  52611. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52612. /**
  52613. * On key up
  52614. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52615. */
  52616. get: function () {
  52617. return ActionManager._OnKeyUpTrigger;
  52618. },
  52619. enumerable: true,
  52620. configurable: true
  52621. });
  52622. // Methods
  52623. /**
  52624. * Releases all associated resources
  52625. */
  52626. ActionManager.prototype.dispose = function () {
  52627. var index = this._scene._actionManagers.indexOf(this);
  52628. for (var i = 0; i < this.actions.length; i++) {
  52629. var action = this.actions[i];
  52630. ActionManager.Triggers[action.trigger]--;
  52631. if (ActionManager.Triggers[action.trigger] === 0) {
  52632. delete ActionManager.Triggers[action.trigger];
  52633. }
  52634. }
  52635. if (index > -1) {
  52636. this._scene._actionManagers.splice(index, 1);
  52637. }
  52638. };
  52639. /**
  52640. * Gets hosting scene
  52641. * @returns the hosting scene
  52642. */
  52643. ActionManager.prototype.getScene = function () {
  52644. return this._scene;
  52645. };
  52646. /**
  52647. * Does this action manager handles actions of any of the given triggers
  52648. * @param triggers defines the triggers to be tested
  52649. * @return a boolean indicating whether one (or more) of the triggers is handled
  52650. */
  52651. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52652. for (var index = 0; index < this.actions.length; index++) {
  52653. var action = this.actions[index];
  52654. if (triggers.indexOf(action.trigger) > -1) {
  52655. return true;
  52656. }
  52657. }
  52658. return false;
  52659. };
  52660. /**
  52661. * Does this action manager handles actions of a given trigger
  52662. * @param trigger defines the trigger to be tested
  52663. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52664. * @return whether the trigger is handled
  52665. */
  52666. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52667. for (var index = 0; index < this.actions.length; index++) {
  52668. var action = this.actions[index];
  52669. if (action.trigger === trigger) {
  52670. if (parameterPredicate) {
  52671. if (parameterPredicate(action.getTriggerParameter())) {
  52672. return true;
  52673. }
  52674. }
  52675. else {
  52676. return true;
  52677. }
  52678. }
  52679. }
  52680. return false;
  52681. };
  52682. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52683. /**
  52684. * Does this action manager has pointer triggers
  52685. */
  52686. get: function () {
  52687. for (var index = 0; index < this.actions.length; index++) {
  52688. var action = this.actions[index];
  52689. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52690. return true;
  52691. }
  52692. }
  52693. return false;
  52694. },
  52695. enumerable: true,
  52696. configurable: true
  52697. });
  52698. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52699. /**
  52700. * Does this action manager has pick triggers
  52701. */
  52702. get: function () {
  52703. for (var index = 0; index < this.actions.length; index++) {
  52704. var action = this.actions[index];
  52705. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52706. return true;
  52707. }
  52708. }
  52709. return false;
  52710. },
  52711. enumerable: true,
  52712. configurable: true
  52713. });
  52714. Object.defineProperty(ActionManager, "HasTriggers", {
  52715. /**
  52716. * Does exist one action manager with at least one trigger
  52717. **/
  52718. get: function () {
  52719. for (var t in ActionManager.Triggers) {
  52720. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52721. return true;
  52722. }
  52723. }
  52724. return false;
  52725. },
  52726. enumerable: true,
  52727. configurable: true
  52728. });
  52729. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52730. /**
  52731. * Does exist one action manager with at least one pick trigger
  52732. **/
  52733. get: function () {
  52734. for (var t in ActionManager.Triggers) {
  52735. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52736. var t_int = parseInt(t);
  52737. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52738. return true;
  52739. }
  52740. }
  52741. }
  52742. return false;
  52743. },
  52744. enumerable: true,
  52745. configurable: true
  52746. });
  52747. /**
  52748. * Does exist one action manager that handles actions of a given trigger
  52749. * @param trigger defines the trigger to be tested
  52750. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52751. **/
  52752. ActionManager.HasSpecificTrigger = function (trigger) {
  52753. for (var t in ActionManager.Triggers) {
  52754. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52755. var t_int = parseInt(t);
  52756. if (t_int === trigger) {
  52757. return true;
  52758. }
  52759. }
  52760. }
  52761. return false;
  52762. };
  52763. /**
  52764. * Registers an action to this action manager
  52765. * @param action defines the action to be registered
  52766. * @return the action amended (prepared) after registration
  52767. */
  52768. ActionManager.prototype.registerAction = function (action) {
  52769. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52770. if (this.getScene().actionManager !== this) {
  52771. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52772. return null;
  52773. }
  52774. }
  52775. this.actions.push(action);
  52776. if (ActionManager.Triggers[action.trigger]) {
  52777. ActionManager.Triggers[action.trigger]++;
  52778. }
  52779. else {
  52780. ActionManager.Triggers[action.trigger] = 1;
  52781. }
  52782. action._actionManager = this;
  52783. action._prepare();
  52784. return action;
  52785. };
  52786. /**
  52787. * Unregisters an action to this action manager
  52788. * @param action defines the action to be unregistered
  52789. * @return a boolean indicating whether the action has been unregistered
  52790. */
  52791. ActionManager.prototype.unregisterAction = function (action) {
  52792. var index = this.actions.indexOf(action);
  52793. if (index !== -1) {
  52794. this.actions.splice(index, 1);
  52795. ActionManager.Triggers[action.trigger] -= 1;
  52796. if (ActionManager.Triggers[action.trigger] === 0) {
  52797. delete ActionManager.Triggers[action.trigger];
  52798. }
  52799. delete action._actionManager;
  52800. return true;
  52801. }
  52802. return false;
  52803. };
  52804. /**
  52805. * Process a specific trigger
  52806. * @param trigger defines the trigger to process
  52807. * @param evt defines the event details to be processed
  52808. */
  52809. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52810. for (var index = 0; index < this.actions.length; index++) {
  52811. var action = this.actions[index];
  52812. if (action.trigger === trigger) {
  52813. if (evt) {
  52814. if (trigger === ActionManager.OnKeyUpTrigger
  52815. || trigger === ActionManager.OnKeyDownTrigger) {
  52816. var parameter = action.getTriggerParameter();
  52817. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52818. if (!parameter.toLowerCase) {
  52819. continue;
  52820. }
  52821. var lowerCase = parameter.toLowerCase();
  52822. if (lowerCase !== evt.sourceEvent.key) {
  52823. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52824. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52825. if (actualkey !== lowerCase) {
  52826. continue;
  52827. }
  52828. }
  52829. }
  52830. }
  52831. }
  52832. action._executeCurrent(evt);
  52833. }
  52834. }
  52835. };
  52836. /** @hidden */
  52837. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52838. var properties = propertyPath.split(".");
  52839. for (var index = 0; index < properties.length - 1; index++) {
  52840. target = target[properties[index]];
  52841. }
  52842. return target;
  52843. };
  52844. /** @hidden */
  52845. ActionManager.prototype._getProperty = function (propertyPath) {
  52846. var properties = propertyPath.split(".");
  52847. return properties[properties.length - 1];
  52848. };
  52849. /**
  52850. * Serialize this manager to a JSON object
  52851. * @param name defines the property name to store this manager
  52852. * @returns a JSON representation of this manager
  52853. */
  52854. ActionManager.prototype.serialize = function (name) {
  52855. var root = {
  52856. children: new Array(),
  52857. name: name,
  52858. type: 3,
  52859. properties: new Array() // Empty for root but required
  52860. };
  52861. for (var i = 0; i < this.actions.length; i++) {
  52862. var triggerObject = {
  52863. type: 0,
  52864. children: new Array(),
  52865. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52866. properties: new Array()
  52867. };
  52868. var triggerOptions = this.actions[i].triggerOptions;
  52869. if (triggerOptions && typeof triggerOptions !== "number") {
  52870. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52871. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52872. }
  52873. else {
  52874. var parameter = {};
  52875. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52876. if (triggerOptions.parameter.mesh) {
  52877. parameter._meshId = triggerOptions.parameter.mesh.id;
  52878. }
  52879. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52880. }
  52881. }
  52882. // Serialize child action, recursively
  52883. this.actions[i].serialize(triggerObject);
  52884. // Add serialized trigger
  52885. root.children.push(triggerObject);
  52886. }
  52887. return root;
  52888. };
  52889. /**
  52890. * Creates a new ActionManager from a JSON data
  52891. * @param parsedActions defines the JSON data to read from
  52892. * @param object defines the hosting mesh
  52893. * @param scene defines the hosting scene
  52894. */
  52895. ActionManager.Parse = function (parsedActions, object, scene) {
  52896. var actionManager = new ActionManager(scene);
  52897. if (object === null)
  52898. scene.actionManager = actionManager;
  52899. else
  52900. object.actionManager = actionManager;
  52901. // instanciate a new object
  52902. var instanciate = function (name, params) {
  52903. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52904. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52905. newInstance.constructor.apply(newInstance, params);
  52906. return newInstance;
  52907. };
  52908. var parseParameter = function (name, value, target, propertyPath) {
  52909. if (propertyPath === null) {
  52910. // String, boolean or float
  52911. var floatValue = parseFloat(value);
  52912. if (value === "true" || value === "false")
  52913. return value === "true";
  52914. else
  52915. return isNaN(floatValue) ? value : floatValue;
  52916. }
  52917. var effectiveTarget = propertyPath.split(".");
  52918. var values = value.split(",");
  52919. // Get effective Target
  52920. for (var i = 0; i < effectiveTarget.length; i++) {
  52921. target = target[effectiveTarget[i]];
  52922. }
  52923. // Return appropriate value with its type
  52924. if (typeof (target) === "boolean")
  52925. return values[0] === "true";
  52926. if (typeof (target) === "string")
  52927. return values[0];
  52928. // Parameters with multiple values such as Vector3 etc.
  52929. var split = new Array();
  52930. for (var i = 0; i < values.length; i++)
  52931. split.push(parseFloat(values[i]));
  52932. if (target instanceof BABYLON.Vector3)
  52933. return BABYLON.Vector3.FromArray(split);
  52934. if (target instanceof BABYLON.Vector4)
  52935. return BABYLON.Vector4.FromArray(split);
  52936. if (target instanceof BABYLON.Color3)
  52937. return BABYLON.Color3.FromArray(split);
  52938. if (target instanceof BABYLON.Color4)
  52939. return BABYLON.Color4.FromArray(split);
  52940. return parseFloat(values[0]);
  52941. };
  52942. // traverse graph per trigger
  52943. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52944. if (combineArray === void 0) { combineArray = null; }
  52945. if (parsedAction.detached)
  52946. return;
  52947. var parameters = new Array();
  52948. var target = null;
  52949. var propertyPath = null;
  52950. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52951. // Parameters
  52952. if (parsedAction.type === 2)
  52953. parameters.push(actionManager);
  52954. else
  52955. parameters.push(trigger);
  52956. if (combine) {
  52957. var actions = new Array();
  52958. for (var j = 0; j < parsedAction.combine.length; j++) {
  52959. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52960. }
  52961. parameters.push(actions);
  52962. }
  52963. else {
  52964. for (var i = 0; i < parsedAction.properties.length; i++) {
  52965. var value = parsedAction.properties[i].value;
  52966. var name = parsedAction.properties[i].name;
  52967. var targetType = parsedAction.properties[i].targetType;
  52968. if (name === "target")
  52969. if (targetType !== null && targetType === "SceneProperties")
  52970. value = target = scene;
  52971. else
  52972. value = target = scene.getNodeByName(value);
  52973. else if (name === "parent")
  52974. value = scene.getNodeByName(value);
  52975. else if (name === "sound")
  52976. value = scene.getSoundByName(value);
  52977. else if (name !== "propertyPath") {
  52978. if (parsedAction.type === 2 && name === "operator")
  52979. value = BABYLON.ValueCondition[value];
  52980. else
  52981. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52982. }
  52983. else {
  52984. propertyPath = value;
  52985. }
  52986. parameters.push(value);
  52987. }
  52988. }
  52989. if (combineArray === null) {
  52990. parameters.push(condition);
  52991. }
  52992. else {
  52993. parameters.push(null);
  52994. }
  52995. // If interpolate value action
  52996. if (parsedAction.name === "InterpolateValueAction") {
  52997. var param = parameters[parameters.length - 2];
  52998. parameters[parameters.length - 1] = param;
  52999. parameters[parameters.length - 2] = condition;
  53000. }
  53001. // Action or condition(s) and not CombineAction
  53002. var newAction = instanciate(parsedAction.name, parameters);
  53003. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53004. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53005. if (action)
  53006. action.then(nothing);
  53007. else
  53008. actionManager.registerAction(nothing);
  53009. action = nothing;
  53010. }
  53011. if (combineArray === null) {
  53012. if (newAction instanceof BABYLON.Condition) {
  53013. condition = newAction;
  53014. newAction = action;
  53015. }
  53016. else {
  53017. condition = null;
  53018. if (action)
  53019. action.then(newAction);
  53020. else
  53021. actionManager.registerAction(newAction);
  53022. }
  53023. }
  53024. else {
  53025. combineArray.push(newAction);
  53026. }
  53027. for (var i = 0; i < parsedAction.children.length; i++)
  53028. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53029. };
  53030. // triggers
  53031. for (var i = 0; i < parsedActions.children.length; i++) {
  53032. var triggerParams;
  53033. var trigger = parsedActions.children[i];
  53034. if (trigger.properties.length > 0) {
  53035. var param = trigger.properties[0].value;
  53036. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53037. if (value._meshId) {
  53038. value.mesh = scene.getMeshByID(value._meshId);
  53039. }
  53040. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53041. }
  53042. else
  53043. triggerParams = ActionManager[trigger.name];
  53044. for (var j = 0; j < trigger.children.length; j++) {
  53045. if (!trigger.detached)
  53046. traverse(trigger.children[j], triggerParams, null, null);
  53047. }
  53048. }
  53049. };
  53050. /**
  53051. * Get a trigger name by index
  53052. * @param trigger defines the trigger index
  53053. * @returns a trigger name
  53054. */
  53055. ActionManager.GetTriggerName = function (trigger) {
  53056. switch (trigger) {
  53057. case 0: return "NothingTrigger";
  53058. case 1: return "OnPickTrigger";
  53059. case 2: return "OnLeftPickTrigger";
  53060. case 3: return "OnRightPickTrigger";
  53061. case 4: return "OnCenterPickTrigger";
  53062. case 5: return "OnPickDownTrigger";
  53063. case 6: return "OnPickUpTrigger";
  53064. case 7: return "OnLongPressTrigger";
  53065. case 8: return "OnPointerOverTrigger";
  53066. case 9: return "OnPointerOutTrigger";
  53067. case 10: return "OnEveryFrameTrigger";
  53068. case 11: return "OnIntersectionEnterTrigger";
  53069. case 12: return "OnIntersectionExitTrigger";
  53070. case 13: return "OnKeyDownTrigger";
  53071. case 14: return "OnKeyUpTrigger";
  53072. case 15: return "OnPickOutTrigger";
  53073. default: return "";
  53074. }
  53075. };
  53076. // Statics
  53077. ActionManager._NothingTrigger = 0;
  53078. ActionManager._OnPickTrigger = 1;
  53079. ActionManager._OnLeftPickTrigger = 2;
  53080. ActionManager._OnRightPickTrigger = 3;
  53081. ActionManager._OnCenterPickTrigger = 4;
  53082. ActionManager._OnPickDownTrigger = 5;
  53083. ActionManager._OnDoublePickTrigger = 6;
  53084. ActionManager._OnPickUpTrigger = 7;
  53085. ActionManager._OnLongPressTrigger = 8;
  53086. ActionManager._OnPointerOverTrigger = 9;
  53087. ActionManager._OnPointerOutTrigger = 10;
  53088. ActionManager._OnEveryFrameTrigger = 11;
  53089. ActionManager._OnIntersectionEnterTrigger = 12;
  53090. ActionManager._OnIntersectionExitTrigger = 13;
  53091. ActionManager._OnKeyDownTrigger = 14;
  53092. ActionManager._OnKeyUpTrigger = 15;
  53093. ActionManager._OnPickOutTrigger = 16;
  53094. /** Gets the list of active triggers */
  53095. ActionManager.Triggers = {};
  53096. return ActionManager;
  53097. }());
  53098. BABYLON.ActionManager = ActionManager;
  53099. })(BABYLON || (BABYLON = {}));
  53100. //# sourceMappingURL=babylon.actionManager.js.map
  53101. var BABYLON;
  53102. (function (BABYLON) {
  53103. var InterpolateValueAction = /** @class */ (function (_super) {
  53104. __extends(InterpolateValueAction, _super);
  53105. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53106. if (duration === void 0) { duration = 1000; }
  53107. var _this = _super.call(this, triggerOptions, condition) || this;
  53108. _this.propertyPath = propertyPath;
  53109. _this.value = value;
  53110. _this.duration = duration;
  53111. _this.stopOtherAnimations = stopOtherAnimations;
  53112. _this.onInterpolationDone = onInterpolationDone;
  53113. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53114. _this._target = _this._effectiveTarget = target;
  53115. return _this;
  53116. }
  53117. InterpolateValueAction.prototype._prepare = function () {
  53118. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53119. this._property = this._getProperty(this.propertyPath);
  53120. };
  53121. InterpolateValueAction.prototype.execute = function () {
  53122. var _this = this;
  53123. var scene = this._actionManager.getScene();
  53124. var keys = [
  53125. {
  53126. frame: 0,
  53127. value: this._effectiveTarget[this._property]
  53128. }, {
  53129. frame: 100,
  53130. value: this.value
  53131. }
  53132. ];
  53133. var dataType;
  53134. if (typeof this.value === "number") {
  53135. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53136. }
  53137. else if (this.value instanceof BABYLON.Color3) {
  53138. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53139. }
  53140. else if (this.value instanceof BABYLON.Vector3) {
  53141. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53142. }
  53143. else if (this.value instanceof BABYLON.Matrix) {
  53144. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53145. }
  53146. else if (this.value instanceof BABYLON.Quaternion) {
  53147. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53148. }
  53149. else {
  53150. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53151. return;
  53152. }
  53153. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53154. animation.setKeys(keys);
  53155. if (this.stopOtherAnimations) {
  53156. scene.stopAnimation(this._effectiveTarget);
  53157. }
  53158. var wrapper = function () {
  53159. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53160. if (_this.onInterpolationDone) {
  53161. _this.onInterpolationDone();
  53162. }
  53163. };
  53164. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53165. };
  53166. InterpolateValueAction.prototype.serialize = function (parent) {
  53167. return _super.prototype._serialize.call(this, {
  53168. name: "InterpolateValueAction",
  53169. properties: [
  53170. BABYLON.Action._GetTargetProperty(this._target),
  53171. { name: "propertyPath", value: this.propertyPath },
  53172. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53173. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53174. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53175. ]
  53176. }, parent);
  53177. };
  53178. return InterpolateValueAction;
  53179. }(BABYLON.Action));
  53180. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53181. })(BABYLON || (BABYLON = {}));
  53182. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53183. var BABYLON;
  53184. (function (BABYLON) {
  53185. var SwitchBooleanAction = /** @class */ (function (_super) {
  53186. __extends(SwitchBooleanAction, _super);
  53187. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53188. var _this = _super.call(this, triggerOptions, condition) || this;
  53189. _this.propertyPath = propertyPath;
  53190. _this._target = _this._effectiveTarget = target;
  53191. return _this;
  53192. }
  53193. SwitchBooleanAction.prototype._prepare = function () {
  53194. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53195. this._property = this._getProperty(this.propertyPath);
  53196. };
  53197. SwitchBooleanAction.prototype.execute = function () {
  53198. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53199. };
  53200. SwitchBooleanAction.prototype.serialize = function (parent) {
  53201. return _super.prototype._serialize.call(this, {
  53202. name: "SwitchBooleanAction",
  53203. properties: [
  53204. BABYLON.Action._GetTargetProperty(this._target),
  53205. { name: "propertyPath", value: this.propertyPath }
  53206. ]
  53207. }, parent);
  53208. };
  53209. return SwitchBooleanAction;
  53210. }(BABYLON.Action));
  53211. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53212. var SetStateAction = /** @class */ (function (_super) {
  53213. __extends(SetStateAction, _super);
  53214. function SetStateAction(triggerOptions, target, value, condition) {
  53215. var _this = _super.call(this, triggerOptions, condition) || this;
  53216. _this.value = value;
  53217. _this._target = target;
  53218. return _this;
  53219. }
  53220. SetStateAction.prototype.execute = function () {
  53221. this._target.state = this.value;
  53222. };
  53223. SetStateAction.prototype.serialize = function (parent) {
  53224. return _super.prototype._serialize.call(this, {
  53225. name: "SetStateAction",
  53226. properties: [
  53227. BABYLON.Action._GetTargetProperty(this._target),
  53228. { name: "value", value: this.value }
  53229. ]
  53230. }, parent);
  53231. };
  53232. return SetStateAction;
  53233. }(BABYLON.Action));
  53234. BABYLON.SetStateAction = SetStateAction;
  53235. var SetValueAction = /** @class */ (function (_super) {
  53236. __extends(SetValueAction, _super);
  53237. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53238. var _this = _super.call(this, triggerOptions, condition) || this;
  53239. _this.propertyPath = propertyPath;
  53240. _this.value = value;
  53241. _this._target = _this._effectiveTarget = target;
  53242. return _this;
  53243. }
  53244. SetValueAction.prototype._prepare = function () {
  53245. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53246. this._property = this._getProperty(this.propertyPath);
  53247. };
  53248. SetValueAction.prototype.execute = function () {
  53249. this._effectiveTarget[this._property] = this.value;
  53250. if (this._target.markAsDirty) {
  53251. this._target.markAsDirty(this._property);
  53252. }
  53253. };
  53254. SetValueAction.prototype.serialize = function (parent) {
  53255. return _super.prototype._serialize.call(this, {
  53256. name: "SetValueAction",
  53257. properties: [
  53258. BABYLON.Action._GetTargetProperty(this._target),
  53259. { name: "propertyPath", value: this.propertyPath },
  53260. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53261. ]
  53262. }, parent);
  53263. };
  53264. return SetValueAction;
  53265. }(BABYLON.Action));
  53266. BABYLON.SetValueAction = SetValueAction;
  53267. var IncrementValueAction = /** @class */ (function (_super) {
  53268. __extends(IncrementValueAction, _super);
  53269. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53270. var _this = _super.call(this, triggerOptions, condition) || this;
  53271. _this.propertyPath = propertyPath;
  53272. _this.value = value;
  53273. _this._target = _this._effectiveTarget = target;
  53274. return _this;
  53275. }
  53276. IncrementValueAction.prototype._prepare = function () {
  53277. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53278. this._property = this._getProperty(this.propertyPath);
  53279. if (typeof this._effectiveTarget[this._property] !== "number") {
  53280. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53281. }
  53282. };
  53283. IncrementValueAction.prototype.execute = function () {
  53284. this._effectiveTarget[this._property] += this.value;
  53285. if (this._target.markAsDirty) {
  53286. this._target.markAsDirty(this._property);
  53287. }
  53288. };
  53289. IncrementValueAction.prototype.serialize = function (parent) {
  53290. return _super.prototype._serialize.call(this, {
  53291. name: "IncrementValueAction",
  53292. properties: [
  53293. BABYLON.Action._GetTargetProperty(this._target),
  53294. { name: "propertyPath", value: this.propertyPath },
  53295. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53296. ]
  53297. }, parent);
  53298. };
  53299. return IncrementValueAction;
  53300. }(BABYLON.Action));
  53301. BABYLON.IncrementValueAction = IncrementValueAction;
  53302. var PlayAnimationAction = /** @class */ (function (_super) {
  53303. __extends(PlayAnimationAction, _super);
  53304. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53305. var _this = _super.call(this, triggerOptions, condition) || this;
  53306. _this.from = from;
  53307. _this.to = to;
  53308. _this.loop = loop;
  53309. _this._target = target;
  53310. return _this;
  53311. }
  53312. PlayAnimationAction.prototype._prepare = function () {
  53313. };
  53314. PlayAnimationAction.prototype.execute = function () {
  53315. var scene = this._actionManager.getScene();
  53316. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53317. };
  53318. PlayAnimationAction.prototype.serialize = function (parent) {
  53319. return _super.prototype._serialize.call(this, {
  53320. name: "PlayAnimationAction",
  53321. properties: [
  53322. BABYLON.Action._GetTargetProperty(this._target),
  53323. { name: "from", value: String(this.from) },
  53324. { name: "to", value: String(this.to) },
  53325. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53326. ]
  53327. }, parent);
  53328. };
  53329. return PlayAnimationAction;
  53330. }(BABYLON.Action));
  53331. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53332. var StopAnimationAction = /** @class */ (function (_super) {
  53333. __extends(StopAnimationAction, _super);
  53334. function StopAnimationAction(triggerOptions, target, condition) {
  53335. var _this = _super.call(this, triggerOptions, condition) || this;
  53336. _this._target = target;
  53337. return _this;
  53338. }
  53339. StopAnimationAction.prototype._prepare = function () {
  53340. };
  53341. StopAnimationAction.prototype.execute = function () {
  53342. var scene = this._actionManager.getScene();
  53343. scene.stopAnimation(this._target);
  53344. };
  53345. StopAnimationAction.prototype.serialize = function (parent) {
  53346. return _super.prototype._serialize.call(this, {
  53347. name: "StopAnimationAction",
  53348. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53349. }, parent);
  53350. };
  53351. return StopAnimationAction;
  53352. }(BABYLON.Action));
  53353. BABYLON.StopAnimationAction = StopAnimationAction;
  53354. var DoNothingAction = /** @class */ (function (_super) {
  53355. __extends(DoNothingAction, _super);
  53356. function DoNothingAction(triggerOptions, condition) {
  53357. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53358. return _super.call(this, triggerOptions, condition) || this;
  53359. }
  53360. DoNothingAction.prototype.execute = function () {
  53361. };
  53362. DoNothingAction.prototype.serialize = function (parent) {
  53363. return _super.prototype._serialize.call(this, {
  53364. name: "DoNothingAction",
  53365. properties: []
  53366. }, parent);
  53367. };
  53368. return DoNothingAction;
  53369. }(BABYLON.Action));
  53370. BABYLON.DoNothingAction = DoNothingAction;
  53371. var CombineAction = /** @class */ (function (_super) {
  53372. __extends(CombineAction, _super);
  53373. function CombineAction(triggerOptions, children, condition) {
  53374. var _this = _super.call(this, triggerOptions, condition) || this;
  53375. _this.children = children;
  53376. return _this;
  53377. }
  53378. CombineAction.prototype._prepare = function () {
  53379. for (var index = 0; index < this.children.length; index++) {
  53380. this.children[index]._actionManager = this._actionManager;
  53381. this.children[index]._prepare();
  53382. }
  53383. };
  53384. CombineAction.prototype.execute = function (evt) {
  53385. for (var index = 0; index < this.children.length; index++) {
  53386. this.children[index].execute(evt);
  53387. }
  53388. };
  53389. CombineAction.prototype.serialize = function (parent) {
  53390. var serializationObject = _super.prototype._serialize.call(this, {
  53391. name: "CombineAction",
  53392. properties: [],
  53393. combine: []
  53394. }, parent);
  53395. for (var i = 0; i < this.children.length; i++) {
  53396. serializationObject.combine.push(this.children[i].serialize(null));
  53397. }
  53398. return serializationObject;
  53399. };
  53400. return CombineAction;
  53401. }(BABYLON.Action));
  53402. BABYLON.CombineAction = CombineAction;
  53403. var ExecuteCodeAction = /** @class */ (function (_super) {
  53404. __extends(ExecuteCodeAction, _super);
  53405. function ExecuteCodeAction(triggerOptions, func, condition) {
  53406. var _this = _super.call(this, triggerOptions, condition) || this;
  53407. _this.func = func;
  53408. return _this;
  53409. }
  53410. ExecuteCodeAction.prototype.execute = function (evt) {
  53411. this.func(evt);
  53412. };
  53413. return ExecuteCodeAction;
  53414. }(BABYLON.Action));
  53415. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53416. var SetParentAction = /** @class */ (function (_super) {
  53417. __extends(SetParentAction, _super);
  53418. function SetParentAction(triggerOptions, target, parent, condition) {
  53419. var _this = _super.call(this, triggerOptions, condition) || this;
  53420. _this._target = target;
  53421. _this._parent = parent;
  53422. return _this;
  53423. }
  53424. SetParentAction.prototype._prepare = function () {
  53425. };
  53426. SetParentAction.prototype.execute = function () {
  53427. if (this._target.parent === this._parent) {
  53428. return;
  53429. }
  53430. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53431. invertParentWorldMatrix.invert();
  53432. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53433. this._target.parent = this._parent;
  53434. };
  53435. SetParentAction.prototype.serialize = function (parent) {
  53436. return _super.prototype._serialize.call(this, {
  53437. name: "SetParentAction",
  53438. properties: [
  53439. BABYLON.Action._GetTargetProperty(this._target),
  53440. BABYLON.Action._GetTargetProperty(this._parent),
  53441. ]
  53442. }, parent);
  53443. };
  53444. return SetParentAction;
  53445. }(BABYLON.Action));
  53446. BABYLON.SetParentAction = SetParentAction;
  53447. var PlaySoundAction = /** @class */ (function (_super) {
  53448. __extends(PlaySoundAction, _super);
  53449. function PlaySoundAction(triggerOptions, sound, condition) {
  53450. var _this = _super.call(this, triggerOptions, condition) || this;
  53451. _this._sound = sound;
  53452. return _this;
  53453. }
  53454. PlaySoundAction.prototype._prepare = function () {
  53455. };
  53456. PlaySoundAction.prototype.execute = function () {
  53457. if (this._sound !== undefined)
  53458. this._sound.play();
  53459. };
  53460. PlaySoundAction.prototype.serialize = function (parent) {
  53461. return _super.prototype._serialize.call(this, {
  53462. name: "PlaySoundAction",
  53463. properties: [{ name: "sound", value: this._sound.name }]
  53464. }, parent);
  53465. };
  53466. return PlaySoundAction;
  53467. }(BABYLON.Action));
  53468. BABYLON.PlaySoundAction = PlaySoundAction;
  53469. var StopSoundAction = /** @class */ (function (_super) {
  53470. __extends(StopSoundAction, _super);
  53471. function StopSoundAction(triggerOptions, sound, condition) {
  53472. var _this = _super.call(this, triggerOptions, condition) || this;
  53473. _this._sound = sound;
  53474. return _this;
  53475. }
  53476. StopSoundAction.prototype._prepare = function () {
  53477. };
  53478. StopSoundAction.prototype.execute = function () {
  53479. if (this._sound !== undefined)
  53480. this._sound.stop();
  53481. };
  53482. StopSoundAction.prototype.serialize = function (parent) {
  53483. return _super.prototype._serialize.call(this, {
  53484. name: "StopSoundAction",
  53485. properties: [{ name: "sound", value: this._sound.name }]
  53486. }, parent);
  53487. };
  53488. return StopSoundAction;
  53489. }(BABYLON.Action));
  53490. BABYLON.StopSoundAction = StopSoundAction;
  53491. })(BABYLON || (BABYLON = {}));
  53492. //# sourceMappingURL=babylon.directActions.js.map
  53493. var BABYLON;
  53494. (function (BABYLON) {
  53495. var SpriteManager = /** @class */ (function () {
  53496. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53497. if (epsilon === void 0) { epsilon = 0.01; }
  53498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53499. this.name = name;
  53500. this.sprites = new Array();
  53501. this.renderingGroupId = 0;
  53502. this.layerMask = 0x0FFFFFFF;
  53503. this.fogEnabled = true;
  53504. this.isPickable = false;
  53505. /**
  53506. * An event triggered when the manager is disposed.
  53507. */
  53508. this.onDisposeObservable = new BABYLON.Observable();
  53509. this._vertexBuffers = {};
  53510. this._capacity = capacity;
  53511. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53512. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53513. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53514. if (cellSize.width && cellSize.height) {
  53515. this.cellWidth = cellSize.width;
  53516. this.cellHeight = cellSize.height;
  53517. }
  53518. else if (cellSize !== undefined) {
  53519. this.cellWidth = cellSize;
  53520. this.cellHeight = cellSize;
  53521. }
  53522. else {
  53523. return;
  53524. }
  53525. this._epsilon = epsilon;
  53526. this._scene = scene;
  53527. this._scene.spriteManagers.push(this);
  53528. var indices = [];
  53529. var index = 0;
  53530. for (var count = 0; count < capacity; count++) {
  53531. indices.push(index);
  53532. indices.push(index + 1);
  53533. indices.push(index + 2);
  53534. indices.push(index);
  53535. indices.push(index + 2);
  53536. indices.push(index + 3);
  53537. index += 4;
  53538. }
  53539. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53540. // VBO
  53541. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53542. this._vertexData = new Float32Array(capacity * 16 * 4);
  53543. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53544. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53545. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53546. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53547. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53548. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53549. this._vertexBuffers["options"] = options;
  53550. this._vertexBuffers["cellInfo"] = cellInfo;
  53551. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53552. // Effects
  53553. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53554. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53555. }
  53556. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53557. set: function (callback) {
  53558. if (this._onDisposeObserver) {
  53559. this.onDisposeObservable.remove(this._onDisposeObserver);
  53560. }
  53561. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53562. },
  53563. enumerable: true,
  53564. configurable: true
  53565. });
  53566. Object.defineProperty(SpriteManager.prototype, "texture", {
  53567. get: function () {
  53568. return this._spriteTexture;
  53569. },
  53570. set: function (value) {
  53571. this._spriteTexture = value;
  53572. },
  53573. enumerable: true,
  53574. configurable: true
  53575. });
  53576. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53577. var arrayOffset = index * 16;
  53578. if (offsetX === 0)
  53579. offsetX = this._epsilon;
  53580. else if (offsetX === 1)
  53581. offsetX = 1 - this._epsilon;
  53582. if (offsetY === 0)
  53583. offsetY = this._epsilon;
  53584. else if (offsetY === 1)
  53585. offsetY = 1 - this._epsilon;
  53586. this._vertexData[arrayOffset] = sprite.position.x;
  53587. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53588. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53589. this._vertexData[arrayOffset + 3] = sprite.angle;
  53590. this._vertexData[arrayOffset + 4] = sprite.width;
  53591. this._vertexData[arrayOffset + 5] = sprite.height;
  53592. this._vertexData[arrayOffset + 6] = offsetX;
  53593. this._vertexData[arrayOffset + 7] = offsetY;
  53594. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53595. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53596. var offset = (sprite.cellIndex / rowSize) >> 0;
  53597. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53598. this._vertexData[arrayOffset + 11] = offset;
  53599. // Color
  53600. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53601. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53602. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53603. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53604. };
  53605. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53606. var count = Math.min(this._capacity, this.sprites.length);
  53607. var min = BABYLON.Vector3.Zero();
  53608. var max = BABYLON.Vector3.Zero();
  53609. var distance = Number.MAX_VALUE;
  53610. var currentSprite = null;
  53611. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53612. var cameraView = camera.getViewMatrix();
  53613. for (var index = 0; index < count; index++) {
  53614. var sprite = this.sprites[index];
  53615. if (!sprite) {
  53616. continue;
  53617. }
  53618. if (predicate) {
  53619. if (!predicate(sprite)) {
  53620. continue;
  53621. }
  53622. }
  53623. else if (!sprite.isPickable) {
  53624. continue;
  53625. }
  53626. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53627. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53628. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53629. if (ray.intersectsBoxMinMax(min, max)) {
  53630. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53631. if (distance > currentDistance) {
  53632. distance = currentDistance;
  53633. currentSprite = sprite;
  53634. if (fastCheck) {
  53635. break;
  53636. }
  53637. }
  53638. }
  53639. }
  53640. if (currentSprite) {
  53641. var result = new BABYLON.PickingInfo();
  53642. result.hit = true;
  53643. result.pickedSprite = currentSprite;
  53644. result.distance = distance;
  53645. return result;
  53646. }
  53647. return null;
  53648. };
  53649. SpriteManager.prototype.render = function () {
  53650. // Check
  53651. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53652. return;
  53653. var engine = this._scene.getEngine();
  53654. var baseSize = this._spriteTexture.getBaseSize();
  53655. // Sprites
  53656. var deltaTime = engine.getDeltaTime();
  53657. var max = Math.min(this._capacity, this.sprites.length);
  53658. var rowSize = baseSize.width / this.cellWidth;
  53659. var offset = 0;
  53660. for (var index = 0; index < max; index++) {
  53661. var sprite = this.sprites[index];
  53662. if (!sprite || !sprite.isVisible) {
  53663. continue;
  53664. }
  53665. sprite._animate(deltaTime);
  53666. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53667. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53668. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53669. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53670. }
  53671. this._buffer.update(this._vertexData);
  53672. // Render
  53673. var effect = this._effectBase;
  53674. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53675. effect = this._effectFog;
  53676. }
  53677. engine.enableEffect(effect);
  53678. var viewMatrix = this._scene.getViewMatrix();
  53679. effect.setTexture("diffuseSampler", this._spriteTexture);
  53680. effect.setMatrix("view", viewMatrix);
  53681. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53682. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53683. // Fog
  53684. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53685. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53686. effect.setColor3("vFogColor", this._scene.fogColor);
  53687. }
  53688. // VBOs
  53689. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53690. // Draw order
  53691. engine.setDepthFunctionToLessOrEqual();
  53692. effect.setBool("alphaTest", true);
  53693. engine.setColorWrite(false);
  53694. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53695. engine.setColorWrite(true);
  53696. effect.setBool("alphaTest", false);
  53697. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53698. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53699. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53700. };
  53701. SpriteManager.prototype.dispose = function () {
  53702. if (this._buffer) {
  53703. this._buffer.dispose();
  53704. this._buffer = null;
  53705. }
  53706. if (this._indexBuffer) {
  53707. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53708. this._indexBuffer = null;
  53709. }
  53710. if (this._spriteTexture) {
  53711. this._spriteTexture.dispose();
  53712. this._spriteTexture = null;
  53713. }
  53714. // Remove from scene
  53715. var index = this._scene.spriteManagers.indexOf(this);
  53716. this._scene.spriteManagers.splice(index, 1);
  53717. // Callback
  53718. this.onDisposeObservable.notifyObservers(this);
  53719. this.onDisposeObservable.clear();
  53720. };
  53721. return SpriteManager;
  53722. }());
  53723. BABYLON.SpriteManager = SpriteManager;
  53724. })(BABYLON || (BABYLON = {}));
  53725. //# sourceMappingURL=babylon.spriteManager.js.map
  53726. var BABYLON;
  53727. (function (BABYLON) {
  53728. var Sprite = /** @class */ (function () {
  53729. function Sprite(name, manager) {
  53730. this.name = name;
  53731. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53732. this.width = 1.0;
  53733. this.height = 1.0;
  53734. this.angle = 0;
  53735. this.cellIndex = 0;
  53736. this.invertU = 0;
  53737. this.invertV = 0;
  53738. this.animations = new Array();
  53739. this.isPickable = false;
  53740. this._animationStarted = false;
  53741. this._loopAnimation = false;
  53742. this._fromIndex = 0;
  53743. this._toIndex = 0;
  53744. this._delay = 0;
  53745. this._direction = 1;
  53746. this._time = 0;
  53747. /**
  53748. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53749. */
  53750. this.isVisible = true;
  53751. this._manager = manager;
  53752. this._manager.sprites.push(this);
  53753. this.position = BABYLON.Vector3.Zero();
  53754. }
  53755. Object.defineProperty(Sprite.prototype, "size", {
  53756. get: function () {
  53757. return this.width;
  53758. },
  53759. set: function (value) {
  53760. this.width = value;
  53761. this.height = value;
  53762. },
  53763. enumerable: true,
  53764. configurable: true
  53765. });
  53766. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53767. this._fromIndex = from;
  53768. this._toIndex = to;
  53769. this._loopAnimation = loop;
  53770. this._delay = delay;
  53771. this._animationStarted = true;
  53772. this._direction = from < to ? 1 : -1;
  53773. this.cellIndex = from;
  53774. this._time = 0;
  53775. this._onAnimationEnd = onAnimationEnd;
  53776. };
  53777. Sprite.prototype.stopAnimation = function () {
  53778. this._animationStarted = false;
  53779. };
  53780. Sprite.prototype._animate = function (deltaTime) {
  53781. if (!this._animationStarted)
  53782. return;
  53783. this._time += deltaTime;
  53784. if (this._time > this._delay) {
  53785. this._time = this._time % this._delay;
  53786. this.cellIndex += this._direction;
  53787. if (this.cellIndex > this._toIndex) {
  53788. if (this._loopAnimation) {
  53789. this.cellIndex = this._fromIndex;
  53790. }
  53791. else {
  53792. this.cellIndex = this._toIndex;
  53793. this._animationStarted = false;
  53794. if (this._onAnimationEnd) {
  53795. this._onAnimationEnd();
  53796. }
  53797. if (this.disposeWhenFinishedAnimating) {
  53798. this.dispose();
  53799. }
  53800. }
  53801. }
  53802. }
  53803. };
  53804. Sprite.prototype.dispose = function () {
  53805. for (var i = 0; i < this._manager.sprites.length; i++) {
  53806. if (this._manager.sprites[i] == this) {
  53807. this._manager.sprites.splice(i, 1);
  53808. }
  53809. }
  53810. };
  53811. return Sprite;
  53812. }());
  53813. BABYLON.Sprite = Sprite;
  53814. })(BABYLON || (BABYLON = {}));
  53815. //# sourceMappingURL=babylon.sprite.js.map
  53816. var BABYLON;
  53817. (function (BABYLON) {
  53818. var IntersectionInfo = /** @class */ (function () {
  53819. function IntersectionInfo(bu, bv, distance) {
  53820. this.bu = bu;
  53821. this.bv = bv;
  53822. this.distance = distance;
  53823. this.faceId = 0;
  53824. this.subMeshId = 0;
  53825. }
  53826. return IntersectionInfo;
  53827. }());
  53828. BABYLON.IntersectionInfo = IntersectionInfo;
  53829. /**
  53830. * Information about the result of picking within a scene
  53831. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53832. */
  53833. var PickingInfo = /** @class */ (function () {
  53834. function PickingInfo() {
  53835. /**
  53836. * If the pick collided with an object
  53837. */
  53838. this.hit = false;
  53839. /**
  53840. * Distance away where the pick collided
  53841. */
  53842. this.distance = 0;
  53843. /**
  53844. * The location of pick collision
  53845. */
  53846. this.pickedPoint = null;
  53847. /**
  53848. * The mesh corrisponding the the pick collision
  53849. */
  53850. this.pickedMesh = null;
  53851. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53852. this.bu = 0;
  53853. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53854. this.bv = 0;
  53855. /** The id of the face on the mesh that was picked */
  53856. this.faceId = -1;
  53857. /** Id of the the submesh that was picked */
  53858. this.subMeshId = 0;
  53859. /** If a sprite was picked, this will be the sprite the pick collided with */
  53860. this.pickedSprite = null;
  53861. /**
  53862. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53863. */
  53864. this.originMesh = null;
  53865. /**
  53866. * The ray that was used to perform the picking.
  53867. */
  53868. this.ray = null;
  53869. }
  53870. /**
  53871. * Gets the normal corrispodning to the face the pick collided with
  53872. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53873. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53874. * @returns The normal corrispodning to the face the pick collided with
  53875. */
  53876. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53877. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53878. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53879. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53880. return null;
  53881. }
  53882. var indices = this.pickedMesh.getIndices();
  53883. if (!indices) {
  53884. return null;
  53885. }
  53886. var result;
  53887. if (useVerticesNormals) {
  53888. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53889. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53890. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53891. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53892. normal0 = normal0.scale(this.bu);
  53893. normal1 = normal1.scale(this.bv);
  53894. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53895. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53896. }
  53897. else {
  53898. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53899. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53900. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53901. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53902. var p1p2 = vertex1.subtract(vertex2);
  53903. var p3p2 = vertex3.subtract(vertex2);
  53904. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53905. }
  53906. if (useWorldCoordinates) {
  53907. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53908. }
  53909. return BABYLON.Vector3.Normalize(result);
  53910. };
  53911. /**
  53912. * Gets the texture coordinates of where the pick occured
  53913. * @returns the vector containing the coordnates of the texture
  53914. */
  53915. PickingInfo.prototype.getTextureCoordinates = function () {
  53916. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53917. return null;
  53918. }
  53919. var indices = this.pickedMesh.getIndices();
  53920. if (!indices) {
  53921. return null;
  53922. }
  53923. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53924. if (!uvs) {
  53925. return null;
  53926. }
  53927. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53928. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53929. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53930. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53931. uv1 = uv1.scale(this.bu);
  53932. uv2 = uv2.scale(this.bv);
  53933. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53934. };
  53935. return PickingInfo;
  53936. }());
  53937. BABYLON.PickingInfo = PickingInfo;
  53938. })(BABYLON || (BABYLON = {}));
  53939. //# sourceMappingURL=babylon.pickingInfo.js.map
  53940. var BABYLON;
  53941. (function (BABYLON) {
  53942. var Ray = /** @class */ (function () {
  53943. function Ray(origin, direction, length) {
  53944. if (length === void 0) { length = Number.MAX_VALUE; }
  53945. this.origin = origin;
  53946. this.direction = direction;
  53947. this.length = length;
  53948. }
  53949. // Methods
  53950. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53951. var d = 0.0;
  53952. var maxValue = Number.MAX_VALUE;
  53953. var inv;
  53954. var min;
  53955. var max;
  53956. var temp;
  53957. if (Math.abs(this.direction.x) < 0.0000001) {
  53958. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53959. return false;
  53960. }
  53961. }
  53962. else {
  53963. inv = 1.0 / this.direction.x;
  53964. min = (minimum.x - this.origin.x) * inv;
  53965. max = (maximum.x - this.origin.x) * inv;
  53966. if (max === -Infinity) {
  53967. max = Infinity;
  53968. }
  53969. if (min > max) {
  53970. temp = min;
  53971. min = max;
  53972. max = temp;
  53973. }
  53974. d = Math.max(min, d);
  53975. maxValue = Math.min(max, maxValue);
  53976. if (d > maxValue) {
  53977. return false;
  53978. }
  53979. }
  53980. if (Math.abs(this.direction.y) < 0.0000001) {
  53981. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53982. return false;
  53983. }
  53984. }
  53985. else {
  53986. inv = 1.0 / this.direction.y;
  53987. min = (minimum.y - this.origin.y) * inv;
  53988. max = (maximum.y - this.origin.y) * inv;
  53989. if (max === -Infinity) {
  53990. max = Infinity;
  53991. }
  53992. if (min > max) {
  53993. temp = min;
  53994. min = max;
  53995. max = temp;
  53996. }
  53997. d = Math.max(min, d);
  53998. maxValue = Math.min(max, maxValue);
  53999. if (d > maxValue) {
  54000. return false;
  54001. }
  54002. }
  54003. if (Math.abs(this.direction.z) < 0.0000001) {
  54004. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54005. return false;
  54006. }
  54007. }
  54008. else {
  54009. inv = 1.0 / this.direction.z;
  54010. min = (minimum.z - this.origin.z) * inv;
  54011. max = (maximum.z - this.origin.z) * inv;
  54012. if (max === -Infinity) {
  54013. max = Infinity;
  54014. }
  54015. if (min > max) {
  54016. temp = min;
  54017. min = max;
  54018. max = temp;
  54019. }
  54020. d = Math.max(min, d);
  54021. maxValue = Math.min(max, maxValue);
  54022. if (d > maxValue) {
  54023. return false;
  54024. }
  54025. }
  54026. return true;
  54027. };
  54028. Ray.prototype.intersectsBox = function (box) {
  54029. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54030. };
  54031. Ray.prototype.intersectsSphere = function (sphere) {
  54032. var x = sphere.center.x - this.origin.x;
  54033. var y = sphere.center.y - this.origin.y;
  54034. var z = sphere.center.z - this.origin.z;
  54035. var pyth = (x * x) + (y * y) + (z * z);
  54036. var rr = sphere.radius * sphere.radius;
  54037. if (pyth <= rr) {
  54038. return true;
  54039. }
  54040. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54041. if (dot < 0.0) {
  54042. return false;
  54043. }
  54044. var temp = pyth - (dot * dot);
  54045. return temp <= rr;
  54046. };
  54047. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54048. if (!this._edge1) {
  54049. this._edge1 = BABYLON.Vector3.Zero();
  54050. this._edge2 = BABYLON.Vector3.Zero();
  54051. this._pvec = BABYLON.Vector3.Zero();
  54052. this._tvec = BABYLON.Vector3.Zero();
  54053. this._qvec = BABYLON.Vector3.Zero();
  54054. }
  54055. vertex1.subtractToRef(vertex0, this._edge1);
  54056. vertex2.subtractToRef(vertex0, this._edge2);
  54057. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54058. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54059. if (det === 0) {
  54060. return null;
  54061. }
  54062. var invdet = 1 / det;
  54063. this.origin.subtractToRef(vertex0, this._tvec);
  54064. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54065. if (bu < 0 || bu > 1.0) {
  54066. return null;
  54067. }
  54068. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54069. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54070. if (bv < 0 || bu + bv > 1.0) {
  54071. return null;
  54072. }
  54073. //check if the distance is longer than the predefined length.
  54074. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54075. if (distance > this.length) {
  54076. return null;
  54077. }
  54078. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54079. };
  54080. Ray.prototype.intersectsPlane = function (plane) {
  54081. var distance;
  54082. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54083. if (Math.abs(result1) < 9.99999997475243E-07) {
  54084. return null;
  54085. }
  54086. else {
  54087. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54088. distance = (-plane.d - result2) / result1;
  54089. if (distance < 0.0) {
  54090. if (distance < -9.99999997475243E-07) {
  54091. return null;
  54092. }
  54093. else {
  54094. return 0;
  54095. }
  54096. }
  54097. return distance;
  54098. }
  54099. };
  54100. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54101. var tm = BABYLON.Tmp.Matrix[0];
  54102. mesh.getWorldMatrix().invertToRef(tm);
  54103. if (this._tmpRay) {
  54104. Ray.TransformToRef(this, tm, this._tmpRay);
  54105. }
  54106. else {
  54107. this._tmpRay = Ray.Transform(this, tm);
  54108. }
  54109. return mesh.intersects(this._tmpRay, fastCheck);
  54110. };
  54111. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54112. if (results) {
  54113. results.length = 0;
  54114. }
  54115. else {
  54116. results = [];
  54117. }
  54118. for (var i = 0; i < meshes.length; i++) {
  54119. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54120. if (pickInfo.hit) {
  54121. results.push(pickInfo);
  54122. }
  54123. }
  54124. results.sort(this._comparePickingInfo);
  54125. return results;
  54126. };
  54127. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54128. if (pickingInfoA.distance < pickingInfoB.distance) {
  54129. return -1;
  54130. }
  54131. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54132. return 1;
  54133. }
  54134. else {
  54135. return 0;
  54136. }
  54137. };
  54138. /**
  54139. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54140. * @param sega the first point of the segment to test the intersection against
  54141. * @param segb the second point of the segment to test the intersection against
  54142. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54143. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54144. */
  54145. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54146. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54147. var u = segb.subtract(sega);
  54148. var v = rsegb.subtract(this.origin);
  54149. var w = sega.subtract(this.origin);
  54150. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54151. var b = BABYLON.Vector3.Dot(u, v);
  54152. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54153. var d = BABYLON.Vector3.Dot(u, w);
  54154. var e = BABYLON.Vector3.Dot(v, w);
  54155. var D = a * c - b * b; // always >= 0
  54156. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54157. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54158. // compute the line parameters of the two closest points
  54159. if (D < Ray.smallnum) { // the lines are almost parallel
  54160. sN = 0.0; // force using point P0 on segment S1
  54161. sD = 1.0; // to prevent possible division by 0.0 later
  54162. tN = e;
  54163. tD = c;
  54164. }
  54165. else { // get the closest points on the infinite lines
  54166. sN = (b * e - c * d);
  54167. tN = (a * e - b * d);
  54168. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54169. sN = 0.0;
  54170. tN = e;
  54171. tD = c;
  54172. }
  54173. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54174. sN = sD;
  54175. tN = e + b;
  54176. tD = c;
  54177. }
  54178. }
  54179. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54180. tN = 0.0;
  54181. // recompute sc for this edge
  54182. if (-d < 0.0) {
  54183. sN = 0.0;
  54184. }
  54185. else if (-d > a)
  54186. sN = sD;
  54187. else {
  54188. sN = -d;
  54189. sD = a;
  54190. }
  54191. }
  54192. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54193. tN = tD;
  54194. // recompute sc for this edge
  54195. if ((-d + b) < 0.0) {
  54196. sN = 0;
  54197. }
  54198. else if ((-d + b) > a) {
  54199. sN = sD;
  54200. }
  54201. else {
  54202. sN = (-d + b);
  54203. sD = a;
  54204. }
  54205. }
  54206. // finally do the division to get sc and tc
  54207. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54208. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54209. // get the difference of the two closest points
  54210. var qtc = v.multiplyByFloats(tc, tc, tc);
  54211. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54212. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54213. if (isIntersected) {
  54214. return qtc.length();
  54215. }
  54216. return -1;
  54217. };
  54218. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54219. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54220. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54221. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54222. this.direction.normalize();
  54223. return this;
  54224. };
  54225. // Statics
  54226. Ray.Zero = function () {
  54227. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54228. };
  54229. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54230. var result = Ray.Zero();
  54231. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54232. };
  54233. /**
  54234. * 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
  54235. * transformed to the given world matrix.
  54236. * @param origin The origin point
  54237. * @param end The end point
  54238. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54239. */
  54240. Ray.CreateNewFromTo = function (origin, end, world) {
  54241. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54242. var direction = end.subtract(origin);
  54243. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54244. direction.normalize();
  54245. return Ray.Transform(new Ray(origin, direction, length), world);
  54246. };
  54247. Ray.Transform = function (ray, matrix) {
  54248. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54249. Ray.TransformToRef(ray, matrix, result);
  54250. return result;
  54251. };
  54252. Ray.TransformToRef = function (ray, matrix, result) {
  54253. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54254. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54255. result.length = ray.length;
  54256. var dir = result.direction;
  54257. var len = dir.length();
  54258. if (!(len === 0 || len === 1)) {
  54259. var num = 1.0 / len;
  54260. dir.x *= num;
  54261. dir.y *= num;
  54262. dir.z *= num;
  54263. result.length *= len;
  54264. }
  54265. };
  54266. Ray.smallnum = 0.00000001;
  54267. Ray.rayl = 10e8;
  54268. return Ray;
  54269. }());
  54270. BABYLON.Ray = Ray;
  54271. })(BABYLON || (BABYLON = {}));
  54272. //# sourceMappingURL=babylon.ray.js.map
  54273. var BABYLON;
  54274. (function (BABYLON) {
  54275. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54276. if (boxMin.x > sphereCenter.x + sphereRadius)
  54277. return false;
  54278. if (sphereCenter.x - sphereRadius > boxMax.x)
  54279. return false;
  54280. if (boxMin.y > sphereCenter.y + sphereRadius)
  54281. return false;
  54282. if (sphereCenter.y - sphereRadius > boxMax.y)
  54283. return false;
  54284. if (boxMin.z > sphereCenter.z + sphereRadius)
  54285. return false;
  54286. if (sphereCenter.z - sphereRadius > boxMax.z)
  54287. return false;
  54288. return true;
  54289. };
  54290. var getLowestRoot = (function () {
  54291. var result = { root: 0, found: false };
  54292. return function (a, b, c, maxR) {
  54293. result.root = 0;
  54294. result.found = false;
  54295. var determinant = b * b - 4.0 * a * c;
  54296. if (determinant < 0)
  54297. return result;
  54298. var sqrtD = Math.sqrt(determinant);
  54299. var r1 = (-b - sqrtD) / (2.0 * a);
  54300. var r2 = (-b + sqrtD) / (2.0 * a);
  54301. if (r1 > r2) {
  54302. var temp = r2;
  54303. r2 = r1;
  54304. r1 = temp;
  54305. }
  54306. if (r1 > 0 && r1 < maxR) {
  54307. result.root = r1;
  54308. result.found = true;
  54309. return result;
  54310. }
  54311. if (r2 > 0 && r2 < maxR) {
  54312. result.root = r2;
  54313. result.found = true;
  54314. return result;
  54315. }
  54316. return result;
  54317. };
  54318. })();
  54319. var Collider = /** @class */ (function () {
  54320. function Collider() {
  54321. this._collisionPoint = BABYLON.Vector3.Zero();
  54322. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54323. this._tempVector = BABYLON.Vector3.Zero();
  54324. this._tempVector2 = BABYLON.Vector3.Zero();
  54325. this._tempVector3 = BABYLON.Vector3.Zero();
  54326. this._tempVector4 = BABYLON.Vector3.Zero();
  54327. this._edge = BABYLON.Vector3.Zero();
  54328. this._baseToVertex = BABYLON.Vector3.Zero();
  54329. this._destinationPoint = BABYLON.Vector3.Zero();
  54330. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54331. this._displacementVector = BABYLON.Vector3.Zero();
  54332. this._radius = BABYLON.Vector3.One();
  54333. this._retry = 0;
  54334. this._basePointWorld = BABYLON.Vector3.Zero();
  54335. this._velocityWorld = BABYLON.Vector3.Zero();
  54336. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54337. this._collisionMask = -1;
  54338. }
  54339. Object.defineProperty(Collider.prototype, "collisionMask", {
  54340. get: function () {
  54341. return this._collisionMask;
  54342. },
  54343. set: function (mask) {
  54344. this._collisionMask = !isNaN(mask) ? mask : -1;
  54345. },
  54346. enumerable: true,
  54347. configurable: true
  54348. });
  54349. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54350. /**
  54351. * Gets the plane normal used to compute the sliding response (in local space)
  54352. */
  54353. get: function () {
  54354. return this._slidePlaneNormal;
  54355. },
  54356. enumerable: true,
  54357. configurable: true
  54358. });
  54359. // Methods
  54360. Collider.prototype._initialize = function (source, dir, e) {
  54361. this._velocity = dir;
  54362. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54363. this._basePoint = source;
  54364. source.multiplyToRef(this._radius, this._basePointWorld);
  54365. dir.multiplyToRef(this._radius, this._velocityWorld);
  54366. this._velocityWorldLength = this._velocityWorld.length();
  54367. this._epsilon = e;
  54368. this.collisionFound = false;
  54369. };
  54370. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54371. pa.subtractToRef(point, this._tempVector);
  54372. pb.subtractToRef(point, this._tempVector2);
  54373. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54374. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54375. if (d < 0)
  54376. return false;
  54377. pc.subtractToRef(point, this._tempVector3);
  54378. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54379. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54380. if (d < 0)
  54381. return false;
  54382. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54383. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54384. return d >= 0;
  54385. };
  54386. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54387. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54388. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54389. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54390. return false;
  54391. }
  54392. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54393. return false;
  54394. return true;
  54395. };
  54396. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54397. var t0;
  54398. var embeddedInPlane = false;
  54399. //defensive programming, actually not needed.
  54400. if (!trianglePlaneArray) {
  54401. trianglePlaneArray = [];
  54402. }
  54403. if (!trianglePlaneArray[faceIndex]) {
  54404. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54405. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54406. }
  54407. var trianglePlane = trianglePlaneArray[faceIndex];
  54408. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54409. return;
  54410. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54411. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54412. if (normalDotVelocity == 0) {
  54413. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54414. return;
  54415. embeddedInPlane = true;
  54416. t0 = 0;
  54417. }
  54418. else {
  54419. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54420. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54421. if (t0 > t1) {
  54422. var temp = t1;
  54423. t1 = t0;
  54424. t0 = temp;
  54425. }
  54426. if (t0 > 1.0 || t1 < 0.0)
  54427. return;
  54428. if (t0 < 0)
  54429. t0 = 0;
  54430. if (t0 > 1.0)
  54431. t0 = 1.0;
  54432. }
  54433. this._collisionPoint.copyFromFloats(0, 0, 0);
  54434. var found = false;
  54435. var t = 1.0;
  54436. if (!embeddedInPlane) {
  54437. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54438. this._velocity.scaleToRef(t0, this._tempVector);
  54439. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54440. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54441. found = true;
  54442. t = t0;
  54443. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54444. }
  54445. }
  54446. if (!found) {
  54447. var velocitySquaredLength = this._velocity.lengthSquared();
  54448. var a = velocitySquaredLength;
  54449. this._basePoint.subtractToRef(p1, this._tempVector);
  54450. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54451. var c = this._tempVector.lengthSquared() - 1.0;
  54452. var lowestRoot = getLowestRoot(a, b, c, t);
  54453. if (lowestRoot.found) {
  54454. t = lowestRoot.root;
  54455. found = true;
  54456. this._collisionPoint.copyFrom(p1);
  54457. }
  54458. this._basePoint.subtractToRef(p2, this._tempVector);
  54459. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54460. c = this._tempVector.lengthSquared() - 1.0;
  54461. lowestRoot = getLowestRoot(a, b, c, t);
  54462. if (lowestRoot.found) {
  54463. t = lowestRoot.root;
  54464. found = true;
  54465. this._collisionPoint.copyFrom(p2);
  54466. }
  54467. this._basePoint.subtractToRef(p3, this._tempVector);
  54468. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54469. c = this._tempVector.lengthSquared() - 1.0;
  54470. lowestRoot = getLowestRoot(a, b, c, t);
  54471. if (lowestRoot.found) {
  54472. t = lowestRoot.root;
  54473. found = true;
  54474. this._collisionPoint.copyFrom(p3);
  54475. }
  54476. p2.subtractToRef(p1, this._edge);
  54477. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54478. var edgeSquaredLength = this._edge.lengthSquared();
  54479. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54480. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54481. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54482. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54483. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54484. lowestRoot = getLowestRoot(a, b, c, t);
  54485. if (lowestRoot.found) {
  54486. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54487. if (f >= 0.0 && f <= 1.0) {
  54488. t = lowestRoot.root;
  54489. found = true;
  54490. this._edge.scaleInPlace(f);
  54491. p1.addToRef(this._edge, this._collisionPoint);
  54492. }
  54493. }
  54494. p3.subtractToRef(p2, this._edge);
  54495. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54496. edgeSquaredLength = this._edge.lengthSquared();
  54497. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54498. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54499. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54500. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54501. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54502. lowestRoot = getLowestRoot(a, b, c, t);
  54503. if (lowestRoot.found) {
  54504. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54505. if (f >= 0.0 && f <= 1.0) {
  54506. t = lowestRoot.root;
  54507. found = true;
  54508. this._edge.scaleInPlace(f);
  54509. p2.addToRef(this._edge, this._collisionPoint);
  54510. }
  54511. }
  54512. p1.subtractToRef(p3, this._edge);
  54513. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54514. edgeSquaredLength = this._edge.lengthSquared();
  54515. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54516. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54517. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54518. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54519. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54520. lowestRoot = getLowestRoot(a, b, c, t);
  54521. if (lowestRoot.found) {
  54522. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54523. if (f >= 0.0 && f <= 1.0) {
  54524. t = lowestRoot.root;
  54525. found = true;
  54526. this._edge.scaleInPlace(f);
  54527. p3.addToRef(this._edge, this._collisionPoint);
  54528. }
  54529. }
  54530. }
  54531. if (found) {
  54532. var distToCollision = t * this._velocity.length();
  54533. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54534. if (!this.intersectionPoint) {
  54535. this.intersectionPoint = this._collisionPoint.clone();
  54536. }
  54537. else {
  54538. this.intersectionPoint.copyFrom(this._collisionPoint);
  54539. }
  54540. this._nearestDistance = distToCollision;
  54541. this.collisionFound = true;
  54542. }
  54543. }
  54544. };
  54545. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54546. for (var i = indexStart; i < indexEnd; i += 3) {
  54547. var p1 = pts[indices[i] - decal];
  54548. var p2 = pts[indices[i + 1] - decal];
  54549. var p3 = pts[indices[i + 2] - decal];
  54550. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54551. }
  54552. };
  54553. Collider.prototype._getResponse = function (pos, vel) {
  54554. pos.addToRef(vel, this._destinationPoint);
  54555. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54556. this._basePoint.addToRef(vel, pos);
  54557. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54558. this._slidePlaneNormal.normalize();
  54559. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54560. pos.addInPlace(this._displacementVector);
  54561. this.intersectionPoint.addInPlace(this._displacementVector);
  54562. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54563. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54564. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54565. };
  54566. return Collider;
  54567. }());
  54568. BABYLON.Collider = Collider;
  54569. })(BABYLON || (BABYLON = {}));
  54570. //# sourceMappingURL=babylon.collider.js.map
  54571. var BABYLON;
  54572. (function (BABYLON) {
  54573. //WebWorker code will be inserted to this variable.
  54574. BABYLON.CollisionWorker = "";
  54575. /** Defines supported task for worker process */
  54576. var WorkerTaskType;
  54577. (function (WorkerTaskType) {
  54578. /** Initialization */
  54579. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54580. /** Update of geometry */
  54581. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54582. /** Evaluate collision */
  54583. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54584. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54585. /** Defines kind of replies returned by worker */
  54586. var WorkerReplyType;
  54587. (function (WorkerReplyType) {
  54588. /** Success */
  54589. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54590. /** Unkown error */
  54591. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54592. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54593. var CollisionCoordinatorWorker = /** @class */ (function () {
  54594. function CollisionCoordinatorWorker() {
  54595. var _this = this;
  54596. this._scaledPosition = BABYLON.Vector3.Zero();
  54597. this._scaledVelocity = BABYLON.Vector3.Zero();
  54598. this.onMeshUpdated = function (transformNode) {
  54599. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54600. };
  54601. this.onGeometryUpdated = function (geometry) {
  54602. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54603. };
  54604. this._afterRender = function () {
  54605. if (!_this._init)
  54606. return;
  54607. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54608. return;
  54609. }
  54610. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54611. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54612. if (_this._runningUpdated > 4) {
  54613. return;
  54614. }
  54615. ++_this._runningUpdated;
  54616. var payload = {
  54617. updatedMeshes: _this._addUpdateMeshesList,
  54618. updatedGeometries: _this._addUpdateGeometriesList,
  54619. removedGeometries: _this._toRemoveGeometryArray,
  54620. removedMeshes: _this._toRemoveMeshesArray
  54621. };
  54622. var message = {
  54623. payload: payload,
  54624. taskType: WorkerTaskType.UPDATE
  54625. };
  54626. var serializable = [];
  54627. for (var id in payload.updatedGeometries) {
  54628. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54629. //prepare transferables
  54630. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54631. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54632. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54633. }
  54634. }
  54635. _this._worker.postMessage(message, serializable);
  54636. _this._addUpdateMeshesList = {};
  54637. _this._addUpdateGeometriesList = {};
  54638. _this._toRemoveGeometryArray = [];
  54639. _this._toRemoveMeshesArray = [];
  54640. };
  54641. this._onMessageFromWorker = function (e) {
  54642. var returnData = e.data;
  54643. if (returnData.error != WorkerReplyType.SUCCESS) {
  54644. //TODO what errors can be returned from the worker?
  54645. BABYLON.Tools.Warn("error returned from worker!");
  54646. return;
  54647. }
  54648. switch (returnData.taskType) {
  54649. case WorkerTaskType.INIT:
  54650. _this._init = true;
  54651. //Update the worked with ALL of the scene's current state
  54652. _this._scene.meshes.forEach(function (mesh) {
  54653. _this.onMeshAdded(mesh);
  54654. });
  54655. _this._scene.getGeometries().forEach(function (geometry) {
  54656. _this.onGeometryAdded(geometry);
  54657. });
  54658. break;
  54659. case WorkerTaskType.UPDATE:
  54660. _this._runningUpdated--;
  54661. break;
  54662. case WorkerTaskType.COLLIDE:
  54663. var returnPayload = returnData.payload;
  54664. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54665. return;
  54666. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54667. if (callback) {
  54668. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54669. if (mesh) {
  54670. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54671. }
  54672. }
  54673. //cleanup
  54674. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54675. break;
  54676. }
  54677. };
  54678. this._collisionsCallbackArray = [];
  54679. this._init = false;
  54680. this._runningUpdated = 0;
  54681. this._addUpdateMeshesList = {};
  54682. this._addUpdateGeometriesList = {};
  54683. this._toRemoveGeometryArray = [];
  54684. this._toRemoveMeshesArray = [];
  54685. }
  54686. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54687. if (!this._init)
  54688. return;
  54689. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54690. return;
  54691. position.divideToRef(collider._radius, this._scaledPosition);
  54692. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54693. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54694. var payload = {
  54695. collider: {
  54696. position: this._scaledPosition.asArray(),
  54697. velocity: this._scaledVelocity.asArray(),
  54698. radius: collider._radius.asArray()
  54699. },
  54700. collisionId: collisionIndex,
  54701. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54702. maximumRetry: maximumRetry
  54703. };
  54704. var message = {
  54705. payload: payload,
  54706. taskType: WorkerTaskType.COLLIDE
  54707. };
  54708. this._worker.postMessage(message);
  54709. };
  54710. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54711. this._scene = scene;
  54712. this._scene.registerAfterRender(this._afterRender);
  54713. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54714. this._worker = new Worker(workerUrl);
  54715. this._worker.onmessage = this._onMessageFromWorker;
  54716. var message = {
  54717. payload: {},
  54718. taskType: WorkerTaskType.INIT
  54719. };
  54720. this._worker.postMessage(message);
  54721. };
  54722. CollisionCoordinatorWorker.prototype.destroy = function () {
  54723. this._scene.unregisterAfterRender(this._afterRender);
  54724. this._worker.terminate();
  54725. };
  54726. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54727. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54728. this.onMeshUpdated(mesh);
  54729. };
  54730. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54731. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54732. };
  54733. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54734. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54735. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54736. this.onGeometryUpdated(geometry);
  54737. };
  54738. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54739. this._toRemoveGeometryArray.push(geometry.id);
  54740. };
  54741. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54742. var submeshes = [];
  54743. if (mesh.subMeshes) {
  54744. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54745. var boundingInfo = sm.getBoundingInfo();
  54746. return {
  54747. position: idx,
  54748. verticesStart: sm.verticesStart,
  54749. verticesCount: sm.verticesCount,
  54750. indexStart: sm.indexStart,
  54751. indexCount: sm.indexCount,
  54752. hasMaterial: !!sm.getMaterial(),
  54753. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54754. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54755. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54756. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54757. };
  54758. });
  54759. }
  54760. var geometryId = null;
  54761. if (mesh instanceof BABYLON.Mesh) {
  54762. var geometry = mesh.geometry;
  54763. geometryId = geometry ? geometry.id : null;
  54764. }
  54765. else if (mesh instanceof BABYLON.InstancedMesh) {
  54766. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54767. geometryId = geometry ? geometry.id : null;
  54768. }
  54769. var boundingInfo = mesh.getBoundingInfo();
  54770. return {
  54771. uniqueId: mesh.uniqueId,
  54772. id: mesh.id,
  54773. name: mesh.name,
  54774. geometryId: geometryId,
  54775. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54776. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54777. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54778. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54779. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54780. subMeshes: submeshes,
  54781. checkCollisions: mesh.checkCollisions
  54782. };
  54783. };
  54784. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54785. return {
  54786. id: geometry.id,
  54787. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54788. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54789. indices: new Uint32Array(geometry.getIndices() || []),
  54790. };
  54791. };
  54792. return CollisionCoordinatorWorker;
  54793. }());
  54794. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54795. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54796. function CollisionCoordinatorLegacy() {
  54797. this._scaledPosition = BABYLON.Vector3.Zero();
  54798. this._scaledVelocity = BABYLON.Vector3.Zero();
  54799. this._finalPosition = BABYLON.Vector3.Zero();
  54800. }
  54801. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54802. position.divideToRef(collider._radius, this._scaledPosition);
  54803. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54804. collider.collidedMesh = null;
  54805. collider._retry = 0;
  54806. collider._initialVelocity = this._scaledVelocity;
  54807. collider._initialPosition = this._scaledPosition;
  54808. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54809. this._finalPosition.multiplyInPlace(collider._radius);
  54810. //run the callback
  54811. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54812. };
  54813. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54814. this._scene = scene;
  54815. };
  54816. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54817. //Legacy need no destruction method.
  54818. };
  54819. //No update in legacy mode
  54820. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54821. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54822. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54823. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54824. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54825. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54826. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54827. if (excludedMesh === void 0) { excludedMesh = null; }
  54828. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54829. if (collider._retry >= maximumRetry) {
  54830. finalPosition.copyFrom(position);
  54831. return;
  54832. }
  54833. // Check if this is a mesh else camera or -1
  54834. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54835. collider._initialize(position, velocity, closeDistance);
  54836. // Check all meshes
  54837. for (var index = 0; index < this._scene.meshes.length; index++) {
  54838. var mesh = this._scene.meshes[index];
  54839. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54840. mesh._checkCollision(collider);
  54841. }
  54842. }
  54843. if (!collider.collisionFound) {
  54844. position.addToRef(velocity, finalPosition);
  54845. return;
  54846. }
  54847. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54848. collider._getResponse(position, velocity);
  54849. }
  54850. if (velocity.length() <= closeDistance) {
  54851. finalPosition.copyFrom(position);
  54852. return;
  54853. }
  54854. collider._retry++;
  54855. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54856. };
  54857. return CollisionCoordinatorLegacy;
  54858. }());
  54859. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54860. })(BABYLON || (BABYLON = {}));
  54861. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54862. var BABYLON;
  54863. (function (BABYLON) {
  54864. /**
  54865. * A particle represents one of the element emitted by a particle system.
  54866. * This is mainly define by its coordinates, direction, velocity and age.
  54867. */
  54868. var Particle = /** @class */ (function () {
  54869. /**
  54870. * Creates a new instance Particle
  54871. * @param particleSystem the particle system the particle belongs to
  54872. */
  54873. function Particle(
  54874. /**
  54875. * particleSystem the particle system the particle belongs to.
  54876. */
  54877. particleSystem) {
  54878. this.particleSystem = particleSystem;
  54879. /**
  54880. * The world position of the particle in the scene.
  54881. */
  54882. this.position = BABYLON.Vector3.Zero();
  54883. /**
  54884. * The world direction of the particle in the scene.
  54885. */
  54886. this.direction = BABYLON.Vector3.Zero();
  54887. /**
  54888. * The color of the particle.
  54889. */
  54890. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54891. /**
  54892. * The color change of the particle per step.
  54893. */
  54894. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54895. /**
  54896. * Defines how long will the life of the particle be.
  54897. */
  54898. this.lifeTime = 1.0;
  54899. /**
  54900. * The current age of the particle.
  54901. */
  54902. this.age = 0;
  54903. /**
  54904. * The current size of the particle.
  54905. */
  54906. this.size = 0;
  54907. /**
  54908. * The current scale of the particle.
  54909. */
  54910. this.scale = new BABYLON.Vector2(1, 1);
  54911. /**
  54912. * The current angle of the particle.
  54913. */
  54914. this.angle = 0;
  54915. /**
  54916. * Defines how fast is the angle changing.
  54917. */
  54918. this.angularSpeed = 0;
  54919. /**
  54920. * Defines the cell index used by the particle to be rendered from a sprite.
  54921. */
  54922. this.cellIndex = 0;
  54923. this._currentFrameCounter = 0;
  54924. if (!this.particleSystem.isAnimationSheetEnabled) {
  54925. return;
  54926. }
  54927. this.updateCellInfoFromSystem();
  54928. }
  54929. Particle.prototype.updateCellInfoFromSystem = function () {
  54930. this.cellIndex = this.particleSystem.startSpriteCellID;
  54931. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54932. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54933. }
  54934. else {
  54935. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54936. }
  54937. };
  54938. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54939. // (ageOffset / scaledUpdateSpeed) / available cells
  54940. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54941. this._currentFrameCounter += scaledUpdateSpeed;
  54942. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54943. this._currentFrameCounter = 0;
  54944. this.cellIndex++;
  54945. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54946. this.cellIndex = this.particleSystem.endSpriteCellID;
  54947. }
  54948. }
  54949. };
  54950. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54951. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54952. this.cellIndex++;
  54953. this._currentFrameCounter = 0;
  54954. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54955. if (this.particleSystem.spriteCellLoop) {
  54956. this.cellIndex = this.particleSystem.startSpriteCellID;
  54957. }
  54958. else {
  54959. this.cellIndex = this.particleSystem.endSpriteCellID;
  54960. }
  54961. }
  54962. }
  54963. else {
  54964. this._currentFrameCounter++;
  54965. }
  54966. };
  54967. /**
  54968. * Copy the properties of particle to another one.
  54969. * @param other the particle to copy the information to.
  54970. */
  54971. Particle.prototype.copyTo = function (other) {
  54972. other.position.copyFrom(this.position);
  54973. if (this._initialDirection) {
  54974. if (other._initialDirection) {
  54975. other._initialDirection.copyFrom(this._initialDirection);
  54976. }
  54977. else {
  54978. other._initialDirection = this._initialDirection.clone();
  54979. }
  54980. }
  54981. else {
  54982. other._initialDirection = null;
  54983. }
  54984. other.direction.copyFrom(this.direction);
  54985. other.color.copyFrom(this.color);
  54986. other.colorStep.copyFrom(this.colorStep);
  54987. other.lifeTime = this.lifeTime;
  54988. other.age = this.age;
  54989. other.size = this.size;
  54990. other.scale.copyFrom(this.scale);
  54991. other.angle = this.angle;
  54992. other.angularSpeed = this.angularSpeed;
  54993. other.particleSystem = this.particleSystem;
  54994. other.cellIndex = this.cellIndex;
  54995. };
  54996. return Particle;
  54997. }());
  54998. BABYLON.Particle = Particle;
  54999. })(BABYLON || (BABYLON = {}));
  55000. //# sourceMappingURL=babylon.particle.js.map
  55001. var BABYLON;
  55002. (function (BABYLON) {
  55003. /**
  55004. * This represents a particle system in Babylon.
  55005. * 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.
  55006. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55007. * @example https://doc.babylonjs.com/babylon101/particles
  55008. */
  55009. var ParticleSystem = /** @class */ (function () {
  55010. /**
  55011. * Instantiates a particle system.
  55012. * 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.
  55013. * @param name The name of the particle system
  55014. * @param capacity The max number of particles alive at the same time
  55015. * @param scene The scene the particle system belongs to
  55016. * @param customEffect a custom effect used to change the way particles are rendered by default
  55017. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55018. * @param epsilon Offset used to render the particles
  55019. */
  55020. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55021. if (customEffect === void 0) { customEffect = null; }
  55022. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55023. if (epsilon === void 0) { epsilon = 0.01; }
  55024. var _this = this;
  55025. /**
  55026. * List of animations used by the particle system.
  55027. */
  55028. this.animations = [];
  55029. /**
  55030. * The rendering group used by the Particle system to chose when to render.
  55031. */
  55032. this.renderingGroupId = 0;
  55033. /**
  55034. * The emitter represents the Mesh or position we are attaching the particle system to.
  55035. */
  55036. this.emitter = null;
  55037. /**
  55038. * The maximum number of particles to emit per frame
  55039. */
  55040. this.emitRate = 10;
  55041. /**
  55042. * If you want to launch only a few particles at once, that can be done, as well.
  55043. */
  55044. this.manualEmitCount = -1;
  55045. /**
  55046. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55047. */
  55048. this.updateSpeed = 0.01;
  55049. /**
  55050. * The amount of time the particle system is running (depends of the overall update speed).
  55051. */
  55052. this.targetStopDuration = 0;
  55053. /**
  55054. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55055. */
  55056. this.disposeOnStop = false;
  55057. /**
  55058. * Minimum power of emitting particles.
  55059. */
  55060. this.minEmitPower = 1;
  55061. /**
  55062. * Maximum power of emitting particles.
  55063. */
  55064. this.maxEmitPower = 1;
  55065. /**
  55066. * Minimum life time of emitting particles.
  55067. */
  55068. this.minLifeTime = 1;
  55069. /**
  55070. * Maximum life time of emitting particles.
  55071. */
  55072. this.maxLifeTime = 1;
  55073. /**
  55074. * Minimum Size of emitting particles.
  55075. */
  55076. this.minSize = 1;
  55077. /**
  55078. * Maximum Size of emitting particles.
  55079. */
  55080. this.maxSize = 1;
  55081. /**
  55082. * Minimum scale of emitting particles on X axis.
  55083. */
  55084. this.minScaleX = 1;
  55085. /**
  55086. * Maximum scale of emitting particles on X axis.
  55087. */
  55088. this.maxScaleX = 1;
  55089. /**
  55090. * Minimum scale of emitting particles on Y axis.
  55091. */
  55092. this.minScaleY = 1;
  55093. /**
  55094. * Maximum scale of emitting particles on Y axis.
  55095. */
  55096. this.maxScaleY = 1;
  55097. /**
  55098. * Gets or sets the minimal initial rotation in radians.
  55099. */
  55100. this.minInitialRotation = 0;
  55101. /**
  55102. * Gets or sets the maximal initial rotation in radians.
  55103. */
  55104. this.maxInitialRotation = 0;
  55105. /**
  55106. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55107. */
  55108. this.minAngularSpeed = 0;
  55109. /**
  55110. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55111. */
  55112. this.maxAngularSpeed = 0;
  55113. /**
  55114. * The layer mask we are rendering the particles through.
  55115. */
  55116. this.layerMask = 0x0FFFFFFF;
  55117. /**
  55118. * This can help using your own shader to render the particle system.
  55119. * The according effect will be created
  55120. */
  55121. this.customShader = null;
  55122. /**
  55123. * By default particle system starts as soon as they are created. This prevents the
  55124. * automatic start to happen and let you decide when to start emitting particles.
  55125. */
  55126. this.preventAutoStart = false;
  55127. /**
  55128. * Callback triggered when the particle animation is ending.
  55129. */
  55130. this.onAnimationEnd = null;
  55131. /**
  55132. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55133. */
  55134. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55135. /**
  55136. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55137. * to override the particles.
  55138. */
  55139. this.forceDepthWrite = false;
  55140. /**
  55141. * You can use gravity if you want to give an orientation to your particles.
  55142. */
  55143. this.gravity = BABYLON.Vector3.Zero();
  55144. this._colorGradients = null;
  55145. this._sizeGradients = null;
  55146. /**
  55147. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55148. */
  55149. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55150. /**
  55151. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55152. */
  55153. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55154. /**
  55155. * Color the particle will have at the end of its lifetime
  55156. */
  55157. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55158. /**
  55159. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55160. */
  55161. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55162. /**
  55163. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  55164. */
  55165. this.spriteCellLoop = true;
  55166. /**
  55167. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  55168. */
  55169. this.spriteCellChangeSpeed = 0;
  55170. /**
  55171. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  55172. */
  55173. this.startSpriteCellID = 0;
  55174. /**
  55175. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  55176. */
  55177. this.endSpriteCellID = 0;
  55178. /**
  55179. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55180. */
  55181. this.spriteCellWidth = 0;
  55182. /**
  55183. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55184. */
  55185. this.spriteCellHeight = 0;
  55186. /** 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 */
  55187. this.preWarmCycles = 0;
  55188. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55189. this.preWarmStepOffset = 1;
  55190. /**
  55191. * An event triggered when the system is disposed
  55192. */
  55193. this.onDisposeObservable = new BABYLON.Observable();
  55194. this._particles = new Array();
  55195. this._stockParticles = new Array();
  55196. this._newPartsExcess = 0;
  55197. this._vertexBuffers = {};
  55198. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55199. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55200. this._scaledDirection = BABYLON.Vector3.Zero();
  55201. this._scaledGravity = BABYLON.Vector3.Zero();
  55202. this._currentRenderId = -1;
  55203. this._useInstancing = false;
  55204. this._started = false;
  55205. this._stopped = false;
  55206. this._actualFrame = 0;
  55207. this._isBillboardBased = true;
  55208. // start of sub system methods
  55209. /**
  55210. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55211. * Its lifetime will start back at 0.
  55212. */
  55213. this.recycleParticle = function (particle) {
  55214. var lastParticle = _this._particles.pop();
  55215. if (lastParticle !== particle) {
  55216. lastParticle.copyTo(particle);
  55217. }
  55218. _this._stockParticles.push(lastParticle);
  55219. };
  55220. this._createParticle = function () {
  55221. var particle;
  55222. if (_this._stockParticles.length !== 0) {
  55223. particle = _this._stockParticles.pop();
  55224. particle.age = 0;
  55225. particle.cellIndex = _this.startSpriteCellID;
  55226. }
  55227. else {
  55228. particle = new BABYLON.Particle(_this);
  55229. }
  55230. return particle;
  55231. };
  55232. this._emitFromParticle = function (particle) {
  55233. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55234. return;
  55235. }
  55236. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55237. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55238. subSystem._rootParticleSystem = _this;
  55239. _this.activeSubSystems.push(subSystem);
  55240. subSystem.start();
  55241. };
  55242. this.id = name;
  55243. this.name = name;
  55244. this._capacity = capacity;
  55245. this._epsilon = epsilon;
  55246. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55247. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55248. this._customEffect = customEffect;
  55249. scene.particleSystems.push(this);
  55250. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55251. this._createIndexBuffer();
  55252. this._createVertexBuffers();
  55253. // Default emitter type
  55254. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55255. this.updateFunction = function (particles) {
  55256. for (var index = 0; index < particles.length; index++) {
  55257. var particle = particles[index];
  55258. particle.age += _this._scaledUpdateSpeed;
  55259. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55260. _this._emitFromParticle(particle);
  55261. _this.recycleParticle(particle);
  55262. index--;
  55263. continue;
  55264. }
  55265. else {
  55266. var ratio = particle.age / particle.lifeTime;
  55267. // Color
  55268. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55269. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55270. BABYLON.Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, particle.color);
  55271. });
  55272. }
  55273. else {
  55274. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55275. particle.color.addInPlace(_this._scaledColorStep);
  55276. if (particle.color.a < 0) {
  55277. particle.color.a = 0;
  55278. }
  55279. }
  55280. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55281. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55282. particle.position.addInPlace(_this._scaledDirection);
  55283. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55284. particle.direction.addInPlace(_this._scaledGravity);
  55285. // Gradient
  55286. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55287. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55288. particle.size = particle._initialSize * BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  55289. });
  55290. }
  55291. if (_this._isAnimationSheetEnabled) {
  55292. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55293. }
  55294. }
  55295. }
  55296. };
  55297. }
  55298. /**
  55299. * Gets the current list of color gradients.
  55300. * You must use addColorGradient and removeColorGradient to udpate this list
  55301. * @returns the list of color gradients
  55302. */
  55303. ParticleSystem.prototype.getColorGradients = function () {
  55304. return this._colorGradients;
  55305. };
  55306. /**
  55307. * Gets the current list of size gradients.
  55308. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55309. * @returns the list of size gradients
  55310. */
  55311. ParticleSystem.prototype.getSizeGradients = function () {
  55312. return this._sizeGradients;
  55313. };
  55314. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55315. /**
  55316. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55317. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55318. */
  55319. get: function () {
  55320. if (this.particleEmitterType.direction1) {
  55321. return this.particleEmitterType.direction1;
  55322. }
  55323. return BABYLON.Vector3.Zero();
  55324. },
  55325. set: function (value) {
  55326. if (this.particleEmitterType.direction1) {
  55327. this.particleEmitterType.direction1 = value;
  55328. }
  55329. },
  55330. enumerable: true,
  55331. configurable: true
  55332. });
  55333. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55334. /**
  55335. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55336. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55337. */
  55338. get: function () {
  55339. if (this.particleEmitterType.direction2) {
  55340. return this.particleEmitterType.direction2;
  55341. }
  55342. return BABYLON.Vector3.Zero();
  55343. },
  55344. set: function (value) {
  55345. if (this.particleEmitterType.direction2) {
  55346. this.particleEmitterType.direction2 = value;
  55347. }
  55348. },
  55349. enumerable: true,
  55350. configurable: true
  55351. });
  55352. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55353. /**
  55354. * 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.
  55355. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55356. */
  55357. get: function () {
  55358. if (this.particleEmitterType.minEmitBox) {
  55359. return this.particleEmitterType.minEmitBox;
  55360. }
  55361. return BABYLON.Vector3.Zero();
  55362. },
  55363. set: function (value) {
  55364. if (this.particleEmitterType.minEmitBox) {
  55365. this.particleEmitterType.minEmitBox = value;
  55366. }
  55367. },
  55368. enumerable: true,
  55369. configurable: true
  55370. });
  55371. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55372. /**
  55373. * 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.
  55374. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55375. */
  55376. get: function () {
  55377. if (this.particleEmitterType.maxEmitBox) {
  55378. return this.particleEmitterType.maxEmitBox;
  55379. }
  55380. return BABYLON.Vector3.Zero();
  55381. },
  55382. set: function (value) {
  55383. if (this.particleEmitterType.maxEmitBox) {
  55384. this.particleEmitterType.maxEmitBox = value;
  55385. }
  55386. },
  55387. enumerable: true,
  55388. configurable: true
  55389. });
  55390. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55391. /**
  55392. * Sets a callback that will be triggered when the system is disposed
  55393. */
  55394. set: function (callback) {
  55395. if (this._onDisposeObserver) {
  55396. this.onDisposeObservable.remove(this._onDisposeObserver);
  55397. }
  55398. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55399. },
  55400. enumerable: true,
  55401. configurable: true
  55402. });
  55403. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55404. /**
  55405. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55406. */
  55407. get: function () {
  55408. return this._isAnimationSheetEnabled;
  55409. },
  55410. enumerable: true,
  55411. configurable: true
  55412. });
  55413. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55414. /**
  55415. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55416. */
  55417. get: function () {
  55418. return this._isBillboardBased;
  55419. },
  55420. set: function (value) {
  55421. if (this._isBillboardBased === value) {
  55422. return;
  55423. }
  55424. this._isBillboardBased = value;
  55425. this._resetEffect();
  55426. },
  55427. enumerable: true,
  55428. configurable: true
  55429. });
  55430. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55431. //end of Sub-emitter
  55432. /**
  55433. * Gets the current list of active particles
  55434. */
  55435. get: function () {
  55436. return this._particles;
  55437. },
  55438. enumerable: true,
  55439. configurable: true
  55440. });
  55441. /**
  55442. * Returns the string "ParticleSystem"
  55443. * @returns a string containing the class name
  55444. */
  55445. ParticleSystem.prototype.getClassName = function () {
  55446. return "ParticleSystem";
  55447. };
  55448. /**
  55449. * Adds a new size gradient
  55450. * @param gradient defines the gradient to use (between 0 and 1)
  55451. * @param factor defines the size factor to affect to the specified gradient
  55452. */
  55453. ParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  55454. if (!this._sizeGradients) {
  55455. this._sizeGradients = [];
  55456. }
  55457. var sizeGradient = new BABYLON.FactorGradient();
  55458. sizeGradient.gradient = gradient;
  55459. sizeGradient.factor = factor;
  55460. this._sizeGradients.push(sizeGradient);
  55461. this._sizeGradients.sort(function (a, b) {
  55462. if (a.gradient < b.gradient) {
  55463. return -1;
  55464. }
  55465. else if (a.gradient > b.gradient) {
  55466. return 1;
  55467. }
  55468. return 0;
  55469. });
  55470. return this;
  55471. };
  55472. /**
  55473. * Remove a specific size gradient
  55474. * @param gradient defines the gradient to remove
  55475. */
  55476. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55477. if (!this._sizeGradients) {
  55478. return this;
  55479. }
  55480. var index = 0;
  55481. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  55482. var sizeGradient = _a[_i];
  55483. if (sizeGradient.gradient === gradient) {
  55484. this._sizeGradients.splice(index, 1);
  55485. break;
  55486. }
  55487. index++;
  55488. }
  55489. return this;
  55490. };
  55491. /**
  55492. * Adds a new color gradient
  55493. * @param gradient defines the gradient to use (between 0 and 1)
  55494. * @param color defines the color to affect to the specified gradient
  55495. */
  55496. ParticleSystem.prototype.addColorGradient = function (gradient, color) {
  55497. if (!this._colorGradients) {
  55498. this._colorGradients = [];
  55499. }
  55500. var colorGradient = new BABYLON.ColorGradient();
  55501. colorGradient.gradient = gradient;
  55502. colorGradient.color = color;
  55503. this._colorGradients.push(colorGradient);
  55504. this._colorGradients.sort(function (a, b) {
  55505. if (a.gradient < b.gradient) {
  55506. return -1;
  55507. }
  55508. else if (a.gradient > b.gradient) {
  55509. return 1;
  55510. }
  55511. return 0;
  55512. });
  55513. return this;
  55514. };
  55515. /**
  55516. * Remove a specific color gradient
  55517. * @param gradient defines the gradient to remove
  55518. */
  55519. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55520. if (!this._colorGradients) {
  55521. return this;
  55522. }
  55523. var index = 0;
  55524. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55525. var colorGradient = _a[_i];
  55526. if (colorGradient.gradient === gradient) {
  55527. this._colorGradients.splice(index, 1);
  55528. break;
  55529. }
  55530. index++;
  55531. }
  55532. return this;
  55533. };
  55534. ParticleSystem.prototype._resetEffect = function () {
  55535. if (this._vertexBuffer) {
  55536. this._vertexBuffer.dispose();
  55537. this._vertexBuffer = null;
  55538. }
  55539. if (this._spriteBuffer) {
  55540. this._spriteBuffer.dispose();
  55541. this._spriteBuffer = null;
  55542. }
  55543. this._createVertexBuffers();
  55544. };
  55545. ParticleSystem.prototype._createVertexBuffers = function () {
  55546. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55547. if (this._isAnimationSheetEnabled) {
  55548. this._vertexBufferSize += 1;
  55549. }
  55550. if (!this._isBillboardBased) {
  55551. this._vertexBufferSize += 3;
  55552. }
  55553. var engine = this._scene.getEngine();
  55554. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55555. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55556. var dataOffset = 0;
  55557. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55559. dataOffset += 3;
  55560. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55561. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55562. dataOffset += 4;
  55563. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55564. this._vertexBuffers["angle"] = options;
  55565. dataOffset += 1;
  55566. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55567. this._vertexBuffers["size"] = size;
  55568. dataOffset += 2;
  55569. if (this._isAnimationSheetEnabled) {
  55570. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55571. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55572. dataOffset += 1;
  55573. }
  55574. if (!this._isBillboardBased) {
  55575. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55576. this._vertexBuffers["direction"] = directionBuffer;
  55577. dataOffset += 3;
  55578. }
  55579. var offsets;
  55580. if (this._useInstancing) {
  55581. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55582. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55583. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55584. }
  55585. else {
  55586. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55587. dataOffset += 2;
  55588. }
  55589. this._vertexBuffers["offset"] = offsets;
  55590. };
  55591. ParticleSystem.prototype._createIndexBuffer = function () {
  55592. if (this._useInstancing) {
  55593. return;
  55594. }
  55595. var indices = [];
  55596. var index = 0;
  55597. for (var count = 0; count < this._capacity; count++) {
  55598. indices.push(index);
  55599. indices.push(index + 1);
  55600. indices.push(index + 2);
  55601. indices.push(index);
  55602. indices.push(index + 2);
  55603. indices.push(index + 3);
  55604. index += 4;
  55605. }
  55606. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55607. };
  55608. /**
  55609. * Gets the maximum number of particles active at the same time.
  55610. * @returns The max number of active particles.
  55611. */
  55612. ParticleSystem.prototype.getCapacity = function () {
  55613. return this._capacity;
  55614. };
  55615. /**
  55616. * Gets Wether there are still active particles in the system.
  55617. * @returns True if it is alive, otherwise false.
  55618. */
  55619. ParticleSystem.prototype.isAlive = function () {
  55620. return this._alive;
  55621. };
  55622. /**
  55623. * Gets Wether the system has been started.
  55624. * @returns True if it has been started, otherwise false.
  55625. */
  55626. ParticleSystem.prototype.isStarted = function () {
  55627. return this._started;
  55628. };
  55629. /**
  55630. * Starts the particle system and begins to emit.
  55631. */
  55632. ParticleSystem.prototype.start = function () {
  55633. this._started = true;
  55634. this._stopped = false;
  55635. this._actualFrame = 0;
  55636. if (this.subEmitters && this.subEmitters.length != 0) {
  55637. this.activeSubSystems = new Array();
  55638. }
  55639. if (this.preWarmCycles) {
  55640. for (var index = 0; index < this.preWarmCycles; index++) {
  55641. this.animate(true);
  55642. }
  55643. }
  55644. };
  55645. /**
  55646. * Stops the particle system.
  55647. * @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.
  55648. */
  55649. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55650. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55651. this._stopped = true;
  55652. if (stopSubEmitters) {
  55653. this._stopSubEmitters();
  55654. }
  55655. };
  55656. // animation sheet
  55657. /**
  55658. * Remove all active particles
  55659. */
  55660. ParticleSystem.prototype.reset = function () {
  55661. this._stockParticles = [];
  55662. this._particles = [];
  55663. };
  55664. /**
  55665. * @hidden (for internal use only)
  55666. */
  55667. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55668. var offset = index * this._vertexBufferSize;
  55669. this._vertexData[offset++] = particle.position.x;
  55670. this._vertexData[offset++] = particle.position.y;
  55671. this._vertexData[offset++] = particle.position.z;
  55672. this._vertexData[offset++] = particle.color.r;
  55673. this._vertexData[offset++] = particle.color.g;
  55674. this._vertexData[offset++] = particle.color.b;
  55675. this._vertexData[offset++] = particle.color.a;
  55676. this._vertexData[offset++] = particle.angle;
  55677. this._vertexData[offset++] = particle.scale.x * particle.size;
  55678. this._vertexData[offset++] = particle.scale.y * particle.size;
  55679. if (this._isAnimationSheetEnabled) {
  55680. this._vertexData[offset++] = particle.cellIndex;
  55681. }
  55682. if (!this._isBillboardBased) {
  55683. if (particle._initialDirection) {
  55684. this._vertexData[offset++] = particle._initialDirection.x;
  55685. this._vertexData[offset++] = particle._initialDirection.y;
  55686. this._vertexData[offset++] = particle._initialDirection.z;
  55687. }
  55688. else {
  55689. this._vertexData[offset++] = particle.direction.x;
  55690. this._vertexData[offset++] = particle.direction.y;
  55691. this._vertexData[offset++] = particle.direction.z;
  55692. }
  55693. }
  55694. if (!this._useInstancing) {
  55695. if (this._isAnimationSheetEnabled) {
  55696. if (offsetX === 0)
  55697. offsetX = this._epsilon;
  55698. else if (offsetX === 1)
  55699. offsetX = 1 - this._epsilon;
  55700. if (offsetY === 0)
  55701. offsetY = this._epsilon;
  55702. else if (offsetY === 1)
  55703. offsetY = 1 - this._epsilon;
  55704. }
  55705. this._vertexData[offset++] = offsetX;
  55706. this._vertexData[offset++] = offsetY;
  55707. }
  55708. };
  55709. ParticleSystem.prototype._stopSubEmitters = function () {
  55710. if (!this.activeSubSystems) {
  55711. return;
  55712. }
  55713. this.activeSubSystems.forEach(function (subSystem) {
  55714. subSystem.stop(true);
  55715. });
  55716. this.activeSubSystems = new Array();
  55717. };
  55718. ParticleSystem.prototype._removeFromRoot = function () {
  55719. if (!this._rootParticleSystem) {
  55720. return;
  55721. }
  55722. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55723. if (index !== -1) {
  55724. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55725. }
  55726. };
  55727. // end of sub system methods
  55728. ParticleSystem.prototype._update = function (newParticles) {
  55729. // Update current
  55730. this._alive = this._particles.length > 0;
  55731. this.updateFunction(this._particles);
  55732. // Add new ones
  55733. var worldMatrix;
  55734. if (this.emitter.position) {
  55735. var emitterMesh = this.emitter;
  55736. worldMatrix = emitterMesh.getWorldMatrix();
  55737. }
  55738. else {
  55739. var emitterPosition = this.emitter;
  55740. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55741. }
  55742. var particle;
  55743. for (var index = 0; index < newParticles; index++) {
  55744. if (this._particles.length === this._capacity) {
  55745. break;
  55746. }
  55747. particle = this._createParticle();
  55748. this._particles.push(particle);
  55749. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55750. if (this.startPositionFunction) {
  55751. this.startPositionFunction(worldMatrix, particle.position, particle);
  55752. }
  55753. else {
  55754. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55755. }
  55756. if (this.startDirectionFunction) {
  55757. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  55758. }
  55759. else {
  55760. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55761. }
  55762. if (emitPower === 0) {
  55763. if (!particle._initialDirection) {
  55764. particle._initialDirection = particle.direction.clone();
  55765. }
  55766. else {
  55767. particle._initialDirection.copyFrom(particle.direction);
  55768. }
  55769. }
  55770. else {
  55771. particle._initialDirection = null;
  55772. }
  55773. particle.direction.scaleInPlace(emitPower);
  55774. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55775. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55776. particle._initialSize = particle.size;
  55777. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55778. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55779. particle.angle = BABYLON.Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  55780. if (!this._colorGradients || this._colorGradients.length === 0) {
  55781. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55782. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55783. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55784. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55785. }
  55786. else {
  55787. particle.color.copyFrom(this._colorGradients[0].color);
  55788. }
  55789. }
  55790. };
  55791. /** @hidden */
  55792. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55793. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55794. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55795. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55796. if (isAnimationSheetEnabled) {
  55797. attributeNamesOrOptions.push("cellIndex");
  55798. }
  55799. if (!isBillboardBased) {
  55800. attributeNamesOrOptions.push("direction");
  55801. }
  55802. return attributeNamesOrOptions;
  55803. };
  55804. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55805. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55806. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55807. if (isAnimationSheetEnabled) {
  55808. effectCreationOption.push("particlesInfos");
  55809. }
  55810. return effectCreationOption;
  55811. };
  55812. ParticleSystem.prototype._getEffect = function () {
  55813. if (this._customEffect) {
  55814. return this._customEffect;
  55815. }
  55816. ;
  55817. var defines = [];
  55818. if (this._scene.clipPlane) {
  55819. defines.push("#define CLIPPLANE");
  55820. }
  55821. if (this._isAnimationSheetEnabled) {
  55822. defines.push("#define ANIMATESHEET");
  55823. }
  55824. if (this._isBillboardBased) {
  55825. defines.push("#define BILLBOARD");
  55826. }
  55827. // Effect
  55828. var join = defines.join("\n");
  55829. if (this._cachedDefines !== join) {
  55830. this._cachedDefines = join;
  55831. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55832. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55833. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55834. }
  55835. return this._effect;
  55836. };
  55837. /**
  55838. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55839. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55840. */
  55841. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55842. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55843. if (!this._started)
  55844. return;
  55845. if (!preWarmOnly) {
  55846. var effect = this._getEffect();
  55847. // Check
  55848. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55849. return;
  55850. if (this._currentRenderId === this._scene.getRenderId()) {
  55851. return;
  55852. }
  55853. this._currentRenderId = this._scene.getRenderId();
  55854. }
  55855. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55856. // determine the number of particles we need to create
  55857. var newParticles;
  55858. if (this.manualEmitCount > -1) {
  55859. newParticles = this.manualEmitCount;
  55860. this._newPartsExcess = 0;
  55861. this.manualEmitCount = 0;
  55862. }
  55863. else {
  55864. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55865. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55866. }
  55867. if (this._newPartsExcess > 1.0) {
  55868. newParticles += this._newPartsExcess >> 0;
  55869. this._newPartsExcess -= this._newPartsExcess >> 0;
  55870. }
  55871. this._alive = false;
  55872. if (!this._stopped) {
  55873. this._actualFrame += this._scaledUpdateSpeed;
  55874. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55875. this.stop();
  55876. }
  55877. else {
  55878. newParticles = 0;
  55879. }
  55880. this._update(newParticles);
  55881. // Stopped?
  55882. if (this._stopped) {
  55883. if (!this._alive) {
  55884. this._started = false;
  55885. if (this.onAnimationEnd) {
  55886. this.onAnimationEnd();
  55887. }
  55888. if (this.disposeOnStop) {
  55889. this._scene._toBeDisposed.push(this);
  55890. }
  55891. }
  55892. }
  55893. if (!preWarmOnly) {
  55894. // Update VBO
  55895. var offset = 0;
  55896. for (var index = 0; index < this._particles.length; index++) {
  55897. var particle = this._particles[index];
  55898. this._appendParticleVertices(offset, particle);
  55899. offset += this._useInstancing ? 1 : 4;
  55900. }
  55901. if (this._vertexBuffer) {
  55902. this._vertexBuffer.update(this._vertexData);
  55903. }
  55904. }
  55905. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55906. this.stop();
  55907. }
  55908. };
  55909. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55910. this._appendParticleVertex(offset++, particle, 0, 0);
  55911. if (!this._useInstancing) {
  55912. this._appendParticleVertex(offset++, particle, 1, 0);
  55913. this._appendParticleVertex(offset++, particle, 1, 1);
  55914. this._appendParticleVertex(offset++, particle, 0, 1);
  55915. }
  55916. };
  55917. /**
  55918. * Rebuilds the particle system.
  55919. */
  55920. ParticleSystem.prototype.rebuild = function () {
  55921. this._createIndexBuffer();
  55922. if (this._vertexBuffer) {
  55923. this._vertexBuffer._rebuild();
  55924. }
  55925. };
  55926. /**
  55927. * Is this system ready to be used/rendered
  55928. * @return true if the system is ready
  55929. */
  55930. ParticleSystem.prototype.isReady = function () {
  55931. var effect = this._getEffect();
  55932. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55933. return false;
  55934. }
  55935. return true;
  55936. };
  55937. /**
  55938. * Renders the particle system in its current state.
  55939. * @returns the current number of particles
  55940. */
  55941. ParticleSystem.prototype.render = function () {
  55942. var effect = this._getEffect();
  55943. // Check
  55944. if (!this.isReady() || !this._particles.length) {
  55945. return 0;
  55946. }
  55947. var engine = this._scene.getEngine();
  55948. // Render
  55949. engine.enableEffect(effect);
  55950. engine.setState(false);
  55951. var viewMatrix = this._scene.getViewMatrix();
  55952. effect.setTexture("diffuseSampler", this.particleTexture);
  55953. effect.setMatrix("view", viewMatrix);
  55954. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55955. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55956. var baseSize = this.particleTexture.getBaseSize();
  55957. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55958. }
  55959. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55960. if (this._scene.clipPlane) {
  55961. var clipPlane = this._scene.clipPlane;
  55962. var invView = viewMatrix.clone();
  55963. invView.invert();
  55964. effect.setMatrix("invView", invView);
  55965. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55966. }
  55967. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55968. // Draw order
  55969. switch (this.blendMode) {
  55970. case ParticleSystem.BLENDMODE_ADD:
  55971. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55972. break;
  55973. case ParticleSystem.BLENDMODE_ONEONE:
  55974. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55975. break;
  55976. case ParticleSystem.BLENDMODE_STANDARD:
  55977. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55978. break;
  55979. }
  55980. if (this.forceDepthWrite) {
  55981. engine.setDepthWrite(true);
  55982. }
  55983. if (this._useInstancing) {
  55984. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55985. engine.unbindInstanceAttributes();
  55986. }
  55987. else {
  55988. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55989. }
  55990. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55991. return this._particles.length;
  55992. };
  55993. /**
  55994. * Disposes the particle system and free the associated resources
  55995. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55996. */
  55997. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55998. if (disposeTexture === void 0) { disposeTexture = true; }
  55999. if (this._vertexBuffer) {
  56000. this._vertexBuffer.dispose();
  56001. this._vertexBuffer = null;
  56002. }
  56003. if (this._spriteBuffer) {
  56004. this._spriteBuffer.dispose();
  56005. this._spriteBuffer = null;
  56006. }
  56007. if (this._indexBuffer) {
  56008. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56009. this._indexBuffer = null;
  56010. }
  56011. if (disposeTexture && this.particleTexture) {
  56012. this.particleTexture.dispose();
  56013. this.particleTexture = null;
  56014. }
  56015. this._removeFromRoot();
  56016. // Remove from scene
  56017. var index = this._scene.particleSystems.indexOf(this);
  56018. if (index > -1) {
  56019. this._scene.particleSystems.splice(index, 1);
  56020. }
  56021. // Callback
  56022. this.onDisposeObservable.notifyObservers(this);
  56023. this.onDisposeObservable.clear();
  56024. };
  56025. /**
  56026. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56027. * @param radius The radius of the sphere to emit from
  56028. * @returns the emitter
  56029. */
  56030. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56031. if (radius === void 0) { radius = 1; }
  56032. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56033. this.particleEmitterType = particleEmitter;
  56034. return particleEmitter;
  56035. };
  56036. /**
  56037. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56038. * @param radius The radius of the sphere to emit from
  56039. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56040. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56041. * @returns the emitter
  56042. */
  56043. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56044. if (radius === void 0) { radius = 1; }
  56045. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56046. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56047. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56048. this.particleEmitterType = particleEmitter;
  56049. return particleEmitter;
  56050. };
  56051. /**
  56052. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56053. * @param radius The radius of the cone to emit from
  56054. * @param angle The base angle of the cone
  56055. * @returns the emitter
  56056. */
  56057. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56058. if (radius === void 0) { radius = 1; }
  56059. if (angle === void 0) { angle = Math.PI / 4; }
  56060. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56061. this.particleEmitterType = particleEmitter;
  56062. return particleEmitter;
  56063. };
  56064. // 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.
  56065. /**
  56066. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56067. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56068. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56069. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56070. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56071. * @returns the emitter
  56072. */
  56073. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56074. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56075. this.particleEmitterType = particleEmitter;
  56076. this.direction1 = direction1;
  56077. this.direction2 = direction2;
  56078. this.minEmitBox = minEmitBox;
  56079. this.maxEmitBox = maxEmitBox;
  56080. return particleEmitter;
  56081. };
  56082. // Clone
  56083. /**
  56084. * Clones the particle system.
  56085. * @param name The name of the cloned object
  56086. * @param newEmitter The new emitter to use
  56087. * @returns the cloned particle system
  56088. */
  56089. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56090. var custom = null;
  56091. var program = null;
  56092. if (this.customShader != null) {
  56093. program = this.customShader;
  56094. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56095. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56096. }
  56097. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56098. result.customShader = program;
  56099. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56100. if (newEmitter === undefined) {
  56101. newEmitter = this.emitter;
  56102. }
  56103. result.emitter = newEmitter;
  56104. if (this.particleTexture) {
  56105. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56106. }
  56107. if (!this.preventAutoStart) {
  56108. result.start();
  56109. }
  56110. return result;
  56111. };
  56112. /**
  56113. * Serializes the particle system to a JSON object.
  56114. * @returns the JSON object
  56115. */
  56116. ParticleSystem.prototype.serialize = function () {
  56117. var serializationObject = {};
  56118. ParticleSystem._Serialize(serializationObject, this);
  56119. serializationObject.textureMask = this.textureMask.asArray();
  56120. serializationObject.customShader = this.customShader;
  56121. serializationObject.preventAutoStart = this.preventAutoStart;
  56122. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56123. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56124. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56125. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56126. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56127. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56128. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56129. return serializationObject;
  56130. };
  56131. /** @hidden */
  56132. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56133. serializationObject.name = particleSystem.name;
  56134. serializationObject.id = particleSystem.id;
  56135. serializationObject.capacity = particleSystem.getCapacity();
  56136. // Emitter
  56137. if (particleSystem.emitter.position) {
  56138. var emitterMesh = particleSystem.emitter;
  56139. serializationObject.emitterId = emitterMesh.id;
  56140. }
  56141. else {
  56142. var emitterPosition = particleSystem.emitter;
  56143. serializationObject.emitter = emitterPosition.asArray();
  56144. }
  56145. // Emitter
  56146. if (particleSystem.particleEmitterType) {
  56147. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56148. }
  56149. if (particleSystem.particleTexture) {
  56150. serializationObject.textureName = particleSystem.particleTexture.name;
  56151. }
  56152. // Animations
  56153. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56154. // Particle system
  56155. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56156. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56157. serializationObject.minSize = particleSystem.minSize;
  56158. serializationObject.maxSize = particleSystem.maxSize;
  56159. serializationObject.minScaleX = particleSystem.minScaleX;
  56160. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56161. serializationObject.minScaleY = particleSystem.minScaleY;
  56162. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56163. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56164. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56165. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56166. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56167. serializationObject.emitRate = particleSystem.emitRate;
  56168. serializationObject.gravity = particleSystem.gravity.asArray();
  56169. serializationObject.color1 = particleSystem.color1.asArray();
  56170. serializationObject.color2 = particleSystem.color2.asArray();
  56171. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56172. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56173. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56174. serializationObject.blendMode = particleSystem.blendMode;
  56175. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56176. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56177. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56178. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56179. var colorGradients = particleSystem.getColorGradients();
  56180. if (colorGradients) {
  56181. serializationObject.colorGradients = [];
  56182. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56183. var colorGradient = colorGradients_1[_i];
  56184. serializationObject.colorGradients.push({
  56185. gradient: colorGradient.gradient,
  56186. color: colorGradient.color.asArray()
  56187. });
  56188. }
  56189. }
  56190. var sizeGradients = particleSystem.getSizeGradients();
  56191. if (sizeGradients) {
  56192. serializationObject.sizeGradients = [];
  56193. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56194. var sizeGradient = sizeGradients_1[_a];
  56195. serializationObject.sizeGradients.push({
  56196. gradient: sizeGradient.gradient,
  56197. factor: sizeGradient.factor
  56198. });
  56199. }
  56200. }
  56201. };
  56202. /** @hidden */
  56203. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56204. // Texture
  56205. if (parsedParticleSystem.textureName) {
  56206. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56207. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56208. }
  56209. // Emitter
  56210. if (parsedParticleSystem.emitterId) {
  56211. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56212. }
  56213. else {
  56214. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56215. }
  56216. // Animations
  56217. if (parsedParticleSystem.animations) {
  56218. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56219. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56220. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56221. }
  56222. }
  56223. if (parsedParticleSystem.autoAnimate) {
  56224. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56225. }
  56226. // Particle system
  56227. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56228. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56229. particleSystem.minSize = parsedParticleSystem.minSize;
  56230. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56231. if (parsedParticleSystem.minScaleX) {
  56232. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56233. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56234. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56235. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56236. }
  56237. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56238. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56239. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56240. }
  56241. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56242. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56243. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56244. }
  56245. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56246. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56247. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56248. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56249. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56250. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56251. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56252. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56253. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56254. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56255. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56256. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56257. if (parsedParticleSystem.colorGradients) {
  56258. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56259. var colorGradient = _a[_i];
  56260. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color));
  56261. }
  56262. }
  56263. if (parsedParticleSystem.sizeGradients) {
  56264. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56265. var sizeGradient = _c[_b];
  56266. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor);
  56267. }
  56268. }
  56269. // Emitter
  56270. if (parsedParticleSystem.particleEmitterType) {
  56271. var emitterType = void 0;
  56272. switch (parsedParticleSystem.particleEmitterType.type) {
  56273. case "SphereEmitter":
  56274. emitterType = new BABYLON.SphereParticleEmitter();
  56275. break;
  56276. case "SphereDirectedParticleEmitter":
  56277. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56278. break;
  56279. case "ConeEmitter":
  56280. emitterType = new BABYLON.ConeParticleEmitter();
  56281. break;
  56282. case "BoxEmitter":
  56283. default:
  56284. emitterType = new BABYLON.BoxParticleEmitter();
  56285. break;
  56286. }
  56287. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56288. particleSystem.particleEmitterType = emitterType;
  56289. }
  56290. };
  56291. /**
  56292. * Parses a JSON object to create a particle system.
  56293. * @param parsedParticleSystem The JSON object to parse
  56294. * @param scene The scene to create the particle system in
  56295. * @param rootUrl The root url to use to load external dependencies like texture
  56296. * @returns the Parsed particle system
  56297. */
  56298. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56299. var name = parsedParticleSystem.name;
  56300. var custom = null;
  56301. var program = null;
  56302. if (parsedParticleSystem.customShader) {
  56303. program = parsedParticleSystem.customShader;
  56304. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56305. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56306. }
  56307. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56308. particleSystem.customShader = program;
  56309. if (parsedParticleSystem.id) {
  56310. particleSystem.id = parsedParticleSystem.id;
  56311. }
  56312. // Auto start
  56313. if (parsedParticleSystem.preventAutoStart) {
  56314. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56315. }
  56316. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56317. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56318. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56319. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56320. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56321. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56322. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56323. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56324. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56325. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56326. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56327. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56328. if (!particleSystem.preventAutoStart) {
  56329. particleSystem.start();
  56330. }
  56331. return particleSystem;
  56332. };
  56333. /**
  56334. * Source color is added to the destination color without alpha affecting the result.
  56335. */
  56336. ParticleSystem.BLENDMODE_ONEONE = 0;
  56337. /**
  56338. * Blend current color and particle color using particle’s alpha.
  56339. */
  56340. ParticleSystem.BLENDMODE_STANDARD = 1;
  56341. /**
  56342. * Add current color and particle color multiplied by particle’s alpha.
  56343. */
  56344. ParticleSystem.BLENDMODE_ADD = 2;
  56345. return ParticleSystem;
  56346. }());
  56347. BABYLON.ParticleSystem = ParticleSystem;
  56348. })(BABYLON || (BABYLON = {}));
  56349. //# sourceMappingURL=babylon.particleSystem.js.map
  56350. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56351. var BABYLON;
  56352. (function (BABYLON) {
  56353. /**
  56354. * Particle emitter emitting particles from the inside of a box.
  56355. * It emits the particles randomly between 2 given directions.
  56356. */
  56357. var BoxParticleEmitter = /** @class */ (function () {
  56358. /**
  56359. * Creates a new instance BoxParticleEmitter
  56360. */
  56361. function BoxParticleEmitter() {
  56362. /**
  56363. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56364. */
  56365. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56366. /**
  56367. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56368. */
  56369. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56370. /**
  56371. * 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.
  56372. */
  56373. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56374. /**
  56375. * 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.
  56376. */
  56377. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56378. }
  56379. /**
  56380. * Called by the particle System when the direction is computed for the created particle.
  56381. * @param worldMatrix is the world matrix of the particle system
  56382. * @param directionToUpdate is the direction vector to update with the result
  56383. * @param particle is the particle we are computed the direction for
  56384. */
  56385. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56386. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56387. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56388. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56389. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56390. };
  56391. /**
  56392. * Called by the particle System when the position is computed for the created particle.
  56393. * @param worldMatrix is the world matrix of the particle system
  56394. * @param positionToUpdate is the position vector to update with the result
  56395. * @param particle is the particle we are computed the position for
  56396. */
  56397. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56398. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56399. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56400. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56401. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56402. };
  56403. /**
  56404. * Clones the current emitter and returns a copy of it
  56405. * @returns the new emitter
  56406. */
  56407. BoxParticleEmitter.prototype.clone = function () {
  56408. var newOne = new BoxParticleEmitter();
  56409. BABYLON.Tools.DeepCopy(this, newOne);
  56410. return newOne;
  56411. };
  56412. /**
  56413. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56414. * @param effect defines the update shader
  56415. */
  56416. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56417. effect.setVector3("direction1", this.direction1);
  56418. effect.setVector3("direction2", this.direction2);
  56419. effect.setVector3("minEmitBox", this.minEmitBox);
  56420. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56421. };
  56422. /**
  56423. * Returns a string to use to update the GPU particles update shader
  56424. * @returns a string containng the defines string
  56425. */
  56426. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56427. return "#define BOXEMITTER";
  56428. };
  56429. /**
  56430. * Returns the string "BoxEmitter"
  56431. * @returns a string containing the class name
  56432. */
  56433. BoxParticleEmitter.prototype.getClassName = function () {
  56434. return "BoxEmitter";
  56435. };
  56436. /**
  56437. * Serializes the particle system to a JSON object.
  56438. * @returns the JSON object
  56439. */
  56440. BoxParticleEmitter.prototype.serialize = function () {
  56441. var serializationObject = {};
  56442. serializationObject.type = this.getClassName();
  56443. serializationObject.direction1 = this.direction1.asArray();
  56444. serializationObject.direction2 = this.direction2.asArray();
  56445. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56446. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56447. return serializationObject;
  56448. };
  56449. /**
  56450. * Parse properties from a JSON object
  56451. * @param serializationObject defines the JSON object
  56452. */
  56453. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56454. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56455. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56456. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56457. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56458. };
  56459. return BoxParticleEmitter;
  56460. }());
  56461. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56462. })(BABYLON || (BABYLON = {}));
  56463. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56464. var BABYLON;
  56465. (function (BABYLON) {
  56466. /**
  56467. * Particle emitter emitting particles from the inside of a cone.
  56468. * It emits the particles alongside the cone volume from the base to the particle.
  56469. * The emission direction might be randomized.
  56470. */
  56471. var ConeParticleEmitter = /** @class */ (function () {
  56472. /**
  56473. * Creates a new instance ConeParticleEmitter
  56474. * @param radius the radius of the emission cone (1 by default)
  56475. * @param angles the cone base angle (PI by default)
  56476. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56477. */
  56478. function ConeParticleEmitter(radius, angle,
  56479. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56480. directionRandomizer) {
  56481. if (radius === void 0) { radius = 1; }
  56482. if (angle === void 0) { angle = Math.PI; }
  56483. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56484. this.directionRandomizer = directionRandomizer;
  56485. this.angle = angle;
  56486. this.radius = radius;
  56487. }
  56488. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56489. /**
  56490. * Gets or sets the radius of the emission cone
  56491. */
  56492. get: function () {
  56493. return this._radius;
  56494. },
  56495. set: function (value) {
  56496. this._radius = value;
  56497. this._buildHeight();
  56498. },
  56499. enumerable: true,
  56500. configurable: true
  56501. });
  56502. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56503. /**
  56504. * Gets or sets the angle of the emission cone
  56505. */
  56506. get: function () {
  56507. return this._angle;
  56508. },
  56509. set: function (value) {
  56510. this._angle = value;
  56511. this._buildHeight();
  56512. },
  56513. enumerable: true,
  56514. configurable: true
  56515. });
  56516. ConeParticleEmitter.prototype._buildHeight = function () {
  56517. if (this._angle !== 0) {
  56518. this._height = this._radius / Math.tan(this._angle / 2);
  56519. }
  56520. else {
  56521. this._height = 1;
  56522. }
  56523. };
  56524. /**
  56525. * Called by the particle System when the direction is computed for the created particle.
  56526. * @param worldMatrix is the world matrix of the particle system
  56527. * @param directionToUpdate is the direction vector to update with the result
  56528. * @param particle is the particle we are computed the direction for
  56529. */
  56530. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56531. if (this._angle === 0) {
  56532. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56533. }
  56534. else {
  56535. // measure the direction Vector from the emitter to the particle.
  56536. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56537. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56538. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56539. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56540. direction.x += randX;
  56541. direction.y += randY;
  56542. direction.z += randZ;
  56543. direction.normalize();
  56544. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56545. }
  56546. };
  56547. /**
  56548. * Called by the particle System when the position is computed for the created particle.
  56549. * @param worldMatrix is the world matrix of the particle system
  56550. * @param positionToUpdate is the position vector to update with the result
  56551. * @param particle is the particle we are computed the position for
  56552. */
  56553. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56554. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56555. var h = BABYLON.Scalar.RandomRange(0, 1);
  56556. // Better distribution in a cone at normal angles.
  56557. h = 1 - h * h;
  56558. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56559. radius = radius * h;
  56560. var randX = radius * Math.sin(s);
  56561. var randZ = radius * Math.cos(s);
  56562. var randY = h * this._height;
  56563. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56564. };
  56565. /**
  56566. * Clones the current emitter and returns a copy of it
  56567. * @returns the new emitter
  56568. */
  56569. ConeParticleEmitter.prototype.clone = function () {
  56570. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56571. BABYLON.Tools.DeepCopy(this, newOne);
  56572. return newOne;
  56573. };
  56574. /**
  56575. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56576. * @param effect defines the update shader
  56577. */
  56578. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56579. effect.setFloat("radius", this._radius);
  56580. effect.setFloat("coneAngle", this._angle);
  56581. effect.setFloat("height", this._height);
  56582. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56583. };
  56584. /**
  56585. * Returns a string to use to update the GPU particles update shader
  56586. * @returns a string containng the defines string
  56587. */
  56588. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56589. return "#define CONEEMITTER";
  56590. };
  56591. /**
  56592. * Returns the string "BoxEmitter"
  56593. * @returns a string containing the class name
  56594. */
  56595. ConeParticleEmitter.prototype.getClassName = function () {
  56596. return "ConeEmitter";
  56597. };
  56598. /**
  56599. * Serializes the particle system to a JSON object.
  56600. * @returns the JSON object
  56601. */
  56602. ConeParticleEmitter.prototype.serialize = function () {
  56603. var serializationObject = {};
  56604. serializationObject.type = this.getClassName();
  56605. serializationObject.radius = this._radius;
  56606. serializationObject.angle = this._angle;
  56607. serializationObject.directionRandomizer = this.directionRandomizer;
  56608. return serializationObject;
  56609. };
  56610. /**
  56611. * Parse properties from a JSON object
  56612. * @param serializationObject defines the JSON object
  56613. */
  56614. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56615. this.radius = serializationObject.radius;
  56616. this.angle = serializationObject.angle;
  56617. this.directionRandomizer = serializationObject.directionRandomizer;
  56618. };
  56619. return ConeParticleEmitter;
  56620. }());
  56621. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56622. })(BABYLON || (BABYLON = {}));
  56623. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56624. var BABYLON;
  56625. (function (BABYLON) {
  56626. /**
  56627. * Particle emitter emitting particles from the inside of a sphere.
  56628. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56629. */
  56630. var SphereParticleEmitter = /** @class */ (function () {
  56631. /**
  56632. * Creates a new instance SphereParticleEmitter
  56633. * @param radius the radius of the emission sphere (1 by default)
  56634. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56635. */
  56636. function SphereParticleEmitter(
  56637. /**
  56638. * The radius of the emission sphere.
  56639. */
  56640. radius,
  56641. /**
  56642. * How much to randomize the particle direction [0-1].
  56643. */
  56644. directionRandomizer) {
  56645. if (radius === void 0) { radius = 1; }
  56646. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56647. this.radius = radius;
  56648. this.directionRandomizer = directionRandomizer;
  56649. /**
  56650. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56651. */
  56652. this.radiusRange = 1;
  56653. }
  56654. /**
  56655. * Called by the particle System when the direction is computed for the created particle.
  56656. * @param worldMatrix is the world matrix of the particle system
  56657. * @param directionToUpdate is the direction vector to update with the result
  56658. * @param particle is the particle we are computed the direction for
  56659. */
  56660. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56661. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56662. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56663. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56664. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56665. direction.x += randX;
  56666. direction.y += randY;
  56667. direction.z += randZ;
  56668. direction.normalize();
  56669. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56670. };
  56671. /**
  56672. * Called by the particle System when the position is computed for the created particle.
  56673. * @param worldMatrix is the world matrix of the particle system
  56674. * @param positionToUpdate is the position vector to update with the result
  56675. * @param particle is the particle we are computed the position for
  56676. */
  56677. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56678. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56679. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56680. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56681. var theta = Math.acos(2 * v - 1);
  56682. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56683. var randY = randRadius * Math.cos(theta);
  56684. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56685. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56686. };
  56687. /**
  56688. * Clones the current emitter and returns a copy of it
  56689. * @returns the new emitter
  56690. */
  56691. SphereParticleEmitter.prototype.clone = function () {
  56692. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56693. BABYLON.Tools.DeepCopy(this, newOne);
  56694. return newOne;
  56695. };
  56696. /**
  56697. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56698. * @param effect defines the update shader
  56699. */
  56700. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56701. effect.setFloat("radius", this.radius);
  56702. effect.setFloat("radiusRange", this.radiusRange);
  56703. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56704. };
  56705. /**
  56706. * Returns a string to use to update the GPU particles update shader
  56707. * @returns a string containng the defines string
  56708. */
  56709. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56710. return "#define SPHEREEMITTER";
  56711. };
  56712. /**
  56713. * Returns the string "SphereParticleEmitter"
  56714. * @returns a string containing the class name
  56715. */
  56716. SphereParticleEmitter.prototype.getClassName = function () {
  56717. return "SphereParticleEmitter";
  56718. };
  56719. /**
  56720. * Serializes the particle system to a JSON object.
  56721. * @returns the JSON object
  56722. */
  56723. SphereParticleEmitter.prototype.serialize = function () {
  56724. var serializationObject = {};
  56725. serializationObject.type = this.getClassName();
  56726. serializationObject.radius = this.radius;
  56727. serializationObject.directionRandomizer = this.directionRandomizer;
  56728. return serializationObject;
  56729. };
  56730. /**
  56731. * Parse properties from a JSON object
  56732. * @param serializationObject defines the JSON object
  56733. */
  56734. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56735. this.radius = serializationObject.radius;
  56736. this.directionRandomizer = serializationObject.directionRandomizer;
  56737. };
  56738. return SphereParticleEmitter;
  56739. }());
  56740. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56741. /**
  56742. * Particle emitter emitting particles from the inside of a sphere.
  56743. * It emits the particles randomly between two vectors.
  56744. */
  56745. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56746. __extends(SphereDirectedParticleEmitter, _super);
  56747. /**
  56748. * Creates a new instance SphereDirectedParticleEmitter
  56749. * @param radius the radius of the emission sphere (1 by default)
  56750. * @param direction1 the min limit of the emission direction (up vector by default)
  56751. * @param direction2 the max limit of the emission direction (up vector by default)
  56752. */
  56753. function SphereDirectedParticleEmitter(radius,
  56754. /**
  56755. * The min limit of the emission direction.
  56756. */
  56757. direction1,
  56758. /**
  56759. * The max limit of the emission direction.
  56760. */
  56761. direction2) {
  56762. if (radius === void 0) { radius = 1; }
  56763. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56764. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56765. var _this = _super.call(this, radius) || this;
  56766. _this.direction1 = direction1;
  56767. _this.direction2 = direction2;
  56768. return _this;
  56769. }
  56770. /**
  56771. * Called by the particle System when the direction is computed for the created particle.
  56772. * @param worldMatrix is the world matrix of the particle system
  56773. * @param directionToUpdate is the direction vector to update with the result
  56774. * @param particle is the particle we are computed the direction for
  56775. */
  56776. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56777. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56778. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56779. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56780. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56781. };
  56782. /**
  56783. * Clones the current emitter and returns a copy of it
  56784. * @returns the new emitter
  56785. */
  56786. SphereDirectedParticleEmitter.prototype.clone = function () {
  56787. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56788. BABYLON.Tools.DeepCopy(this, newOne);
  56789. return newOne;
  56790. };
  56791. /**
  56792. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56793. * @param effect defines the update shader
  56794. */
  56795. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56796. effect.setFloat("radius", this.radius);
  56797. effect.setFloat("radiusRange", this.radiusRange);
  56798. effect.setVector3("direction1", this.direction1);
  56799. effect.setVector3("direction2", this.direction2);
  56800. };
  56801. /**
  56802. * Returns a string to use to update the GPU particles update shader
  56803. * @returns a string containng the defines string
  56804. */
  56805. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56806. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56807. };
  56808. /**
  56809. * Returns the string "SphereDirectedParticleEmitter"
  56810. * @returns a string containing the class name
  56811. */
  56812. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56813. return "SphereDirectedParticleEmitter";
  56814. };
  56815. /**
  56816. * Serializes the particle system to a JSON object.
  56817. * @returns the JSON object
  56818. */
  56819. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56820. var serializationObject = _super.prototype.serialize.call(this);
  56821. serializationObject.direction1 = this.direction1.asArray();
  56822. serializationObject.direction2 = this.direction2.asArray();
  56823. return serializationObject;
  56824. };
  56825. /**
  56826. * Parse properties from a JSON object
  56827. * @param serializationObject defines the JSON object
  56828. */
  56829. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56830. _super.prototype.parse.call(this, serializationObject);
  56831. this.direction1.copyFrom(serializationObject.direction1);
  56832. this.direction2.copyFrom(serializationObject.direction2);
  56833. };
  56834. return SphereDirectedParticleEmitter;
  56835. }(SphereParticleEmitter));
  56836. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56837. })(BABYLON || (BABYLON = {}));
  56838. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56839. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56840. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56841. s = arguments[i];
  56842. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56843. t[p] = s[p];
  56844. }
  56845. return t;
  56846. };
  56847. var BABYLON;
  56848. (function (BABYLON) {
  56849. /**
  56850. * This represents a GPU particle system in Babylon
  56851. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56852. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56853. */
  56854. var GPUParticleSystem = /** @class */ (function () {
  56855. /**
  56856. * Instantiates a GPU particle system.
  56857. * 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.
  56858. * @param name The name of the particle system
  56859. * @param capacity The max number of particles alive at the same time
  56860. * @param scene The scene the particle system belongs to
  56861. */
  56862. function GPUParticleSystem(name, options, scene) {
  56863. /**
  56864. * The emitter represents the Mesh or position we are attaching the particle system to.
  56865. */
  56866. this.emitter = null;
  56867. /**
  56868. * The rendering group used by the Particle system to chose when to render.
  56869. */
  56870. this.renderingGroupId = 0;
  56871. /**
  56872. * The layer mask we are rendering the particles through.
  56873. */
  56874. this.layerMask = 0x0FFFFFFF;
  56875. this._accumulatedCount = 0;
  56876. this._targetIndex = 0;
  56877. this._currentRenderId = -1;
  56878. this._started = false;
  56879. this._stopped = false;
  56880. this._timeDelta = 0;
  56881. this._attributesStrideSize = 21;
  56882. this._actualFrame = 0;
  56883. /**
  56884. * List of animations used by the particle system.
  56885. */
  56886. this.animations = [];
  56887. /**
  56888. * An event triggered when the system is disposed.
  56889. */
  56890. this.onDisposeObservable = new BABYLON.Observable();
  56891. /**
  56892. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56893. */
  56894. this.updateSpeed = 0.01;
  56895. /**
  56896. * The amount of time the particle system is running (depends of the overall update speed).
  56897. */
  56898. this.targetStopDuration = 0;
  56899. /**
  56900. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56901. */
  56902. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56903. /**
  56904. * Minimum life time of emitting particles.
  56905. */
  56906. this.minLifeTime = 1;
  56907. /**
  56908. * Maximum life time of emitting particles.
  56909. */
  56910. this.maxLifeTime = 1;
  56911. /**
  56912. * Minimum Size of emitting particles.
  56913. */
  56914. this.minSize = 1;
  56915. /**
  56916. * Maximum Size of emitting particles.
  56917. */
  56918. this.maxSize = 1;
  56919. /**
  56920. * Minimum scale of emitting particles on X axis.
  56921. */
  56922. this.minScaleX = 1;
  56923. /**
  56924. * Maximum scale of emitting particles on X axis.
  56925. */
  56926. this.maxScaleX = 1;
  56927. /**
  56928. * Minimum scale of emitting particles on Y axis.
  56929. */
  56930. this.minScaleY = 1;
  56931. /**
  56932. * Maximum scale of emitting particles on Y axis.
  56933. */
  56934. this.maxScaleY = 1;
  56935. /**
  56936. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56937. */
  56938. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56939. /**
  56940. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56941. */
  56942. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56943. /**
  56944. * Color the particle will have at the end of its lifetime.
  56945. */
  56946. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56947. /**
  56948. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56949. */
  56950. this.emitRate = 100;
  56951. /**
  56952. * You can use gravity if you want to give an orientation to your particles.
  56953. */
  56954. this.gravity = BABYLON.Vector3.Zero();
  56955. /**
  56956. * Minimum power of emitting particles.
  56957. */
  56958. this.minEmitPower = 1;
  56959. /**
  56960. * Maximum power of emitting particles.
  56961. */
  56962. this.maxEmitPower = 1;
  56963. /**
  56964. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56965. */
  56966. this.minAngularSpeed = 0;
  56967. /**
  56968. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56969. */
  56970. this.maxAngularSpeed = 0;
  56971. /**
  56972. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56973. * to override the particles.
  56974. */
  56975. this.forceDepthWrite = false;
  56976. this._preWarmDone = false;
  56977. /** 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 */
  56978. this.preWarmCycles = 0;
  56979. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56980. this.preWarmStepOffset = 1;
  56981. /**
  56982. * Gets or sets the minimal initial rotation in radians.
  56983. */
  56984. this.minInitialRotation = 0;
  56985. /**
  56986. * Gets or sets the maximal initial rotation in radians.
  56987. */
  56988. this.maxInitialRotation = 0;
  56989. this._isBillboardBased = true;
  56990. this._colorGradients = null;
  56991. this._sizeGradients = null;
  56992. this.id = name;
  56993. this.name = name;
  56994. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56995. this._engine = this._scene.getEngine();
  56996. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56997. var optionsAsNumber = options;
  56998. if (isFinite(optionsAsNumber)) {
  56999. fullOptions.capacity = optionsAsNumber;
  57000. }
  57001. this._capacity = fullOptions.capacity;
  57002. this._activeCount = fullOptions.capacity;
  57003. this._currentActiveCount = 0;
  57004. this._scene.particleSystems.push(this);
  57005. this._updateEffectOptions = {
  57006. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "initialSize"],
  57007. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57008. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57009. "angleRange", "radiusRange"],
  57010. uniformBuffersNames: [],
  57011. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  57012. defines: "",
  57013. fallbacks: null,
  57014. onCompiled: null,
  57015. onError: null,
  57016. indexParameters: null,
  57017. maxSimultaneousLights: 0,
  57018. transformFeedbackVaryings: []
  57019. };
  57020. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57021. // Random data
  57022. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57023. var d = [];
  57024. for (var i = 0; i < maxTextureSize; ++i) {
  57025. d.push(Math.random());
  57026. d.push(Math.random());
  57027. d.push(Math.random());
  57028. d.push(Math.random());
  57029. }
  57030. 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);
  57031. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57032. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57033. d = [];
  57034. for (var i = 0; i < maxTextureSize; ++i) {
  57035. d.push(Math.random());
  57036. d.push(Math.random());
  57037. d.push(Math.random());
  57038. d.push(Math.random());
  57039. }
  57040. 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);
  57041. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57042. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57043. this._randomTextureSize = maxTextureSize;
  57044. }
  57045. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57046. /**
  57047. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57048. */
  57049. get: function () {
  57050. if (!BABYLON.Engine.LastCreatedEngine) {
  57051. return false;
  57052. }
  57053. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57054. },
  57055. enumerable: true,
  57056. configurable: true
  57057. });
  57058. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57059. /**
  57060. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57061. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57062. */
  57063. get: function () {
  57064. if (this.particleEmitterType.direction1) {
  57065. return this.particleEmitterType.direction1;
  57066. }
  57067. return BABYLON.Vector3.Zero();
  57068. },
  57069. set: function (value) {
  57070. if (this.particleEmitterType.direction1) {
  57071. this.particleEmitterType.direction1 = value;
  57072. }
  57073. },
  57074. enumerable: true,
  57075. configurable: true
  57076. });
  57077. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57078. /**
  57079. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57080. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57081. */
  57082. get: function () {
  57083. if (this.particleEmitterType.direction2) {
  57084. return this.particleEmitterType.direction2;
  57085. }
  57086. return BABYLON.Vector3.Zero();
  57087. },
  57088. set: function (value) {
  57089. if (this.particleEmitterType.direction2) {
  57090. this.particleEmitterType.direction2 = value;
  57091. }
  57092. },
  57093. enumerable: true,
  57094. configurable: true
  57095. });
  57096. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57097. /**
  57098. * 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.
  57099. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57100. */
  57101. get: function () {
  57102. if (this.particleEmitterType.minEmitBox) {
  57103. return this.particleEmitterType.minEmitBox;
  57104. }
  57105. return BABYLON.Vector3.Zero();
  57106. },
  57107. set: function (value) {
  57108. if (this.particleEmitterType.minEmitBox) {
  57109. this.particleEmitterType.minEmitBox = value;
  57110. }
  57111. },
  57112. enumerable: true,
  57113. configurable: true
  57114. });
  57115. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57116. /**
  57117. * 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.
  57118. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57119. */
  57120. get: function () {
  57121. if (this.particleEmitterType.maxEmitBox) {
  57122. return this.particleEmitterType.maxEmitBox;
  57123. }
  57124. return BABYLON.Vector3.Zero();
  57125. },
  57126. set: function (value) {
  57127. if (this.particleEmitterType.maxEmitBox) {
  57128. this.particleEmitterType.maxEmitBox = value;
  57129. }
  57130. },
  57131. enumerable: true,
  57132. configurable: true
  57133. });
  57134. /**
  57135. * Gets the maximum number of particles active at the same time.
  57136. * @returns The max number of active particles.
  57137. */
  57138. GPUParticleSystem.prototype.getCapacity = function () {
  57139. return this._capacity;
  57140. };
  57141. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57142. /**
  57143. * Gets or set the number of active particles
  57144. */
  57145. get: function () {
  57146. return this._activeCount;
  57147. },
  57148. set: function (value) {
  57149. this._activeCount = Math.min(value, this._capacity);
  57150. },
  57151. enumerable: true,
  57152. configurable: true
  57153. });
  57154. /**
  57155. * Is this system ready to be used/rendered
  57156. * @return true if the system is ready
  57157. */
  57158. GPUParticleSystem.prototype.isReady = function () {
  57159. if (!this._updateEffect) {
  57160. this._recreateUpdateEffect();
  57161. this._recreateRenderEffect();
  57162. return false;
  57163. }
  57164. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57165. return false;
  57166. }
  57167. return true;
  57168. };
  57169. /**
  57170. * Gets Wether the system has been started.
  57171. * @returns True if it has been started, otherwise false.
  57172. */
  57173. GPUParticleSystem.prototype.isStarted = function () {
  57174. return this._started;
  57175. };
  57176. /**
  57177. * Starts the particle system and begins to emit.
  57178. */
  57179. GPUParticleSystem.prototype.start = function () {
  57180. this._started = true;
  57181. this._stopped = false;
  57182. this._preWarmDone = false;
  57183. };
  57184. /**
  57185. * Stops the particle system.
  57186. */
  57187. GPUParticleSystem.prototype.stop = function () {
  57188. this._stopped = true;
  57189. };
  57190. /**
  57191. * Remove all active particles
  57192. */
  57193. GPUParticleSystem.prototype.reset = function () {
  57194. this._releaseBuffers();
  57195. this._releaseVAOs();
  57196. this._currentActiveCount = 0;
  57197. this._targetIndex = 0;
  57198. };
  57199. /**
  57200. * Returns the string "GPUParticleSystem"
  57201. * @returns a string containing the class name
  57202. */
  57203. GPUParticleSystem.prototype.getClassName = function () {
  57204. return "GPUParticleSystem";
  57205. };
  57206. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57207. /**
  57208. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57209. */
  57210. get: function () {
  57211. return this._isBillboardBased;
  57212. },
  57213. set: function (value) {
  57214. if (this._isBillboardBased === value) {
  57215. return;
  57216. }
  57217. this._isBillboardBased = value;
  57218. this._releaseBuffers();
  57219. },
  57220. enumerable: true,
  57221. configurable: true
  57222. });
  57223. /**
  57224. * Gets the current list of color gradients.
  57225. * You must use addColorGradient and removeColorGradient to udpate this list
  57226. * @returns the list of color gradients
  57227. */
  57228. GPUParticleSystem.prototype.getColorGradients = function () {
  57229. return this._colorGradients;
  57230. };
  57231. /**
  57232. * Gets the current list of size gradients.
  57233. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57234. * @returns the list of size gradients
  57235. */
  57236. GPUParticleSystem.prototype.getSizeGradients = function () {
  57237. return this._sizeGradients;
  57238. };
  57239. /**
  57240. * Adds a new color gradient
  57241. * @param gradient defines the gradient to use (between 0 and 1)
  57242. * @param color defines the color to affect to the specified gradient
  57243. */
  57244. GPUParticleSystem.prototype.addColorGradient = function (gradient, color) {
  57245. if (!this._colorGradients) {
  57246. this._colorGradients = [];
  57247. }
  57248. var colorGradient = new BABYLON.ColorGradient();
  57249. colorGradient.gradient = gradient;
  57250. colorGradient.color = color;
  57251. this._colorGradients.push(colorGradient);
  57252. this._colorGradients.sort(function (a, b) {
  57253. if (a.gradient < b.gradient) {
  57254. return -1;
  57255. }
  57256. else if (a.gradient > b.gradient) {
  57257. return 1;
  57258. }
  57259. return 0;
  57260. });
  57261. if (this._colorGradientsTexture) {
  57262. this._colorGradientsTexture.dispose();
  57263. this._colorGradientsTexture = null;
  57264. }
  57265. this._releaseBuffers();
  57266. return this;
  57267. };
  57268. /**
  57269. * Remove a specific color gradient
  57270. * @param gradient defines the gradient to remove
  57271. */
  57272. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57273. if (!this._colorGradients) {
  57274. return this;
  57275. }
  57276. var index = 0;
  57277. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57278. var colorGradient = _a[_i];
  57279. if (colorGradient.gradient === gradient) {
  57280. this._colorGradients.splice(index, 1);
  57281. break;
  57282. }
  57283. index++;
  57284. }
  57285. if (this._colorGradientsTexture) {
  57286. this._colorGradientsTexture.dispose();
  57287. this._colorGradientsTexture = null;
  57288. }
  57289. this._releaseBuffers();
  57290. return this;
  57291. };
  57292. /**
  57293. * Adds a new size gradient
  57294. * @param gradient defines the gradient to use (between 0 and 1)
  57295. * @param factor defines the size factor to affect to the specified gradient
  57296. */
  57297. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57298. if (!this._sizeGradients) {
  57299. this._sizeGradients = [];
  57300. }
  57301. var sizeGradient = new BABYLON.FactorGradient();
  57302. sizeGradient.gradient = gradient;
  57303. sizeGradient.factor = factor;
  57304. this._sizeGradients.push(sizeGradient);
  57305. this._sizeGradients.sort(function (a, b) {
  57306. if (a.gradient < b.gradient) {
  57307. return -1;
  57308. }
  57309. else if (a.gradient > b.gradient) {
  57310. return 1;
  57311. }
  57312. return 0;
  57313. });
  57314. if (this._sizeGradientsTexture) {
  57315. this._sizeGradientsTexture.dispose();
  57316. this._sizeGradientsTexture = null;
  57317. }
  57318. this._releaseBuffers();
  57319. return this;
  57320. };
  57321. /**
  57322. * Remove a specific size gradient
  57323. * @param gradient defines the gradient to remove
  57324. */
  57325. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57326. if (!this._sizeGradients) {
  57327. return this;
  57328. }
  57329. var index = 0;
  57330. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57331. var sizeGradient = _a[_i];
  57332. if (sizeGradient.gradient === gradient) {
  57333. this._sizeGradients.splice(index, 1);
  57334. break;
  57335. }
  57336. index++;
  57337. }
  57338. if (this._sizeGradientsTexture) {
  57339. this._sizeGradientsTexture.dispose();
  57340. this._sizeGradientsTexture = null;
  57341. }
  57342. this._releaseBuffers();
  57343. return this;
  57344. };
  57345. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57346. var updateVertexBuffers = {};
  57347. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57348. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57349. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57350. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57351. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57352. var offset = 12;
  57353. if (this._sizeGradientsTexture) {
  57354. updateVertexBuffers["initialSize"] = source.createVertexBuffer("initialSize", offset, 3);
  57355. offset += 3;
  57356. }
  57357. if (!this._colorGradientsTexture) {
  57358. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57359. offset += 4;
  57360. }
  57361. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57362. offset += 3;
  57363. if (!this._isBillboardBased) {
  57364. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57365. offset += 3;
  57366. }
  57367. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57368. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57369. this._engine.bindArrayBuffer(null);
  57370. return vao;
  57371. };
  57372. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57373. var renderVertexBuffers = {};
  57374. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57375. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57376. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57377. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57378. var offset = 12;
  57379. if (this._sizeGradientsTexture) {
  57380. offset += 3;
  57381. }
  57382. if (!this._colorGradientsTexture) {
  57383. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57384. offset += 4;
  57385. }
  57386. offset += 3; // Direction
  57387. if (!this._isBillboardBased) {
  57388. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57389. offset += 3;
  57390. }
  57391. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57392. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57393. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57394. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57395. this._engine.bindArrayBuffer(null);
  57396. return vao;
  57397. };
  57398. GPUParticleSystem.prototype._initialize = function (force) {
  57399. if (force === void 0) { force = false; }
  57400. if (this._buffer0 && !force) {
  57401. return;
  57402. }
  57403. var engine = this._scene.getEngine();
  57404. var data = new Array();
  57405. if (!this.isBillboardBased) {
  57406. this._attributesStrideSize += 3;
  57407. }
  57408. if (this._colorGradientsTexture) {
  57409. this._attributesStrideSize -= 4;
  57410. }
  57411. if (this._sizeGradientsTexture) {
  57412. this._attributesStrideSize += 3;
  57413. }
  57414. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57415. // position
  57416. data.push(0.0);
  57417. data.push(0.0);
  57418. data.push(0.0);
  57419. // Age and life
  57420. data.push(0.0); // create the particle as a dead one to create a new one at start
  57421. data.push(0.0);
  57422. // Seed
  57423. data.push(Math.random());
  57424. data.push(Math.random());
  57425. data.push(Math.random());
  57426. data.push(Math.random());
  57427. // Size
  57428. data.push(0.0);
  57429. data.push(0.0);
  57430. data.push(0.0);
  57431. if (this._sizeGradientsTexture) {
  57432. data.push(0.0);
  57433. data.push(0.0);
  57434. data.push(0.0);
  57435. }
  57436. if (!this._colorGradientsTexture) {
  57437. // color
  57438. data.push(0.0);
  57439. data.push(0.0);
  57440. data.push(0.0);
  57441. data.push(0.0);
  57442. }
  57443. // direction
  57444. data.push(0.0);
  57445. data.push(0.0);
  57446. data.push(0.0);
  57447. if (!this.isBillboardBased) {
  57448. // initialDirection
  57449. data.push(0.0);
  57450. data.push(0.0);
  57451. data.push(0.0);
  57452. }
  57453. // angle
  57454. data.push(0.0);
  57455. data.push(0.0);
  57456. }
  57457. // Sprite data
  57458. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57459. -0.5, 0.5, 0, 1,
  57460. -0.5, -0.5, 0, 0,
  57461. 0.5, -0.5, 1, 0]);
  57462. // Buffers
  57463. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57464. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57465. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57466. // Update VAO
  57467. this._updateVAO = [];
  57468. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57469. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57470. // Render VAO
  57471. this._renderVAO = [];
  57472. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57473. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57474. // Links
  57475. this._sourceBuffer = this._buffer0;
  57476. this._targetBuffer = this._buffer1;
  57477. };
  57478. /** @hidden */
  57479. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57480. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57481. if (this._isBillboardBased) {
  57482. defines += "\n#define BILLBOARD";
  57483. }
  57484. if (this._colorGradientsTexture) {
  57485. defines += "\n#define COLORGRADIENTS";
  57486. }
  57487. if (this._sizeGradientsTexture) {
  57488. defines += "\n#define SIZEGRADIENTS";
  57489. }
  57490. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57491. return;
  57492. }
  57493. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57494. if (this._sizeGradientsTexture) {
  57495. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialSize");
  57496. }
  57497. if (!this._colorGradientsTexture) {
  57498. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57499. }
  57500. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57501. if (!this._isBillboardBased) {
  57502. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57503. }
  57504. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57505. this._updateEffectOptions.defines = defines;
  57506. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57507. };
  57508. /** @hidden */
  57509. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57510. var defines = "";
  57511. if (this._scene.clipPlane) {
  57512. defines = "\n#define CLIPPLANE";
  57513. }
  57514. if (this._isBillboardBased) {
  57515. defines += "\n#define BILLBOARD";
  57516. }
  57517. if (this._colorGradientsTexture) {
  57518. defines += "\n#define COLORGRADIENTS";
  57519. }
  57520. if (this._renderEffect && this._renderEffect.defines === defines) {
  57521. return;
  57522. }
  57523. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57524. };
  57525. /**
  57526. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57527. * @param preWarm defines if we are in the pre-warmimg phase
  57528. */
  57529. GPUParticleSystem.prototype.animate = function (preWarm) {
  57530. if (preWarm === void 0) { preWarm = false; }
  57531. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57532. this._actualFrame += this._timeDelta;
  57533. if (!this._stopped) {
  57534. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57535. this.stop();
  57536. }
  57537. }
  57538. };
  57539. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57540. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57541. return;
  57542. }
  57543. var textureWidth = 256;
  57544. var data = new Float32Array(textureWidth);
  57545. for (var x = 0; x < textureWidth; x++) {
  57546. var ratio = x / textureWidth;
  57547. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57548. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  57549. });
  57550. }
  57551. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57552. };
  57553. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57554. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57555. return;
  57556. }
  57557. var textureWidth = 256;
  57558. var data = new Uint8Array(textureWidth * 4);
  57559. var tmpColor = BABYLON.Tmp.Color4[0];
  57560. for (var x = 0; x < textureWidth; x++) {
  57561. var ratio = x / textureWidth;
  57562. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57563. BABYLON.Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57564. data[x * 4] = tmpColor.r * 255;
  57565. data[x * 4 + 1] = tmpColor.g * 255;
  57566. data[x * 4 + 2] = tmpColor.b * 255;
  57567. data[x * 4 + 3] = tmpColor.a * 255;
  57568. });
  57569. }
  57570. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57571. };
  57572. /**
  57573. * Renders the particle system in its current state
  57574. * @param preWarm defines if the system should only update the particles but not render them
  57575. * @returns the current number of particles
  57576. */
  57577. GPUParticleSystem.prototype.render = function (preWarm) {
  57578. if (preWarm === void 0) { preWarm = false; }
  57579. if (!this._started) {
  57580. return 0;
  57581. }
  57582. this._createColorGradientTexture();
  57583. this._createSizeGradientTexture();
  57584. this._recreateUpdateEffect();
  57585. this._recreateRenderEffect();
  57586. if (!this.isReady()) {
  57587. return 0;
  57588. }
  57589. if (!preWarm) {
  57590. if (!this._preWarmDone && this.preWarmCycles) {
  57591. for (var index = 0; index < this.preWarmCycles; index++) {
  57592. this.animate(true);
  57593. this.render(true);
  57594. }
  57595. this._preWarmDone = true;
  57596. }
  57597. if (this._currentRenderId === this._scene.getRenderId()) {
  57598. return 0;
  57599. }
  57600. this._currentRenderId = this._scene.getRenderId();
  57601. }
  57602. // Get everything ready to render
  57603. this._initialize();
  57604. this._accumulatedCount += this.emitRate * this._timeDelta;
  57605. if (this._accumulatedCount > 1) {
  57606. var intPart = this._accumulatedCount | 0;
  57607. this._accumulatedCount -= intPart;
  57608. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57609. }
  57610. if (!this._currentActiveCount) {
  57611. return 0;
  57612. }
  57613. // Enable update effect
  57614. this._engine.enableEffect(this._updateEffect);
  57615. this._engine.setState(false);
  57616. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57617. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57618. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57619. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57620. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57621. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57622. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57623. if (!this._colorGradientsTexture) {
  57624. this._updateEffect.setDirectColor4("color1", this.color1);
  57625. this._updateEffect.setDirectColor4("color2", this.color2);
  57626. }
  57627. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57628. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57629. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57630. this._updateEffect.setVector3("gravity", this.gravity);
  57631. if (this._sizeGradientsTexture) {
  57632. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57633. }
  57634. if (this.particleEmitterType) {
  57635. this.particleEmitterType.applyToShader(this._updateEffect);
  57636. }
  57637. var emitterWM;
  57638. if (this.emitter.position) {
  57639. var emitterMesh = this.emitter;
  57640. emitterWM = emitterMesh.getWorldMatrix();
  57641. }
  57642. else {
  57643. var emitterPosition = this.emitter;
  57644. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57645. }
  57646. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57647. // Bind source VAO
  57648. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57649. // Update
  57650. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57651. this._engine.setRasterizerState(false);
  57652. this._engine.beginTransformFeedback();
  57653. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57654. this._engine.endTransformFeedback();
  57655. this._engine.setRasterizerState(true);
  57656. this._engine.bindTransformFeedbackBuffer(null);
  57657. if (!preWarm) {
  57658. // Enable render effect
  57659. this._engine.enableEffect(this._renderEffect);
  57660. var viewMatrix = this._scene.getViewMatrix();
  57661. this._renderEffect.setMatrix("view", viewMatrix);
  57662. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57663. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57664. if (this._colorGradientsTexture) {
  57665. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57666. }
  57667. else {
  57668. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57669. }
  57670. if (this._scene.clipPlane) {
  57671. var clipPlane = this._scene.clipPlane;
  57672. var invView = viewMatrix.clone();
  57673. invView.invert();
  57674. this._renderEffect.setMatrix("invView", invView);
  57675. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57676. }
  57677. // Draw order
  57678. switch (this.blendMode) {
  57679. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57680. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57681. break;
  57682. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57683. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57684. break;
  57685. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57686. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57687. break;
  57688. }
  57689. if (this.forceDepthWrite) {
  57690. this._engine.setDepthWrite(true);
  57691. }
  57692. // Bind source VAO
  57693. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57694. // Render
  57695. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57696. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57697. }
  57698. // Switch VAOs
  57699. this._targetIndex++;
  57700. if (this._targetIndex === 2) {
  57701. this._targetIndex = 0;
  57702. }
  57703. // Switch buffers
  57704. var tmpBuffer = this._sourceBuffer;
  57705. this._sourceBuffer = this._targetBuffer;
  57706. this._targetBuffer = tmpBuffer;
  57707. return this._currentActiveCount;
  57708. };
  57709. /**
  57710. * Rebuilds the particle system
  57711. */
  57712. GPUParticleSystem.prototype.rebuild = function () {
  57713. this._initialize(true);
  57714. };
  57715. GPUParticleSystem.prototype._releaseBuffers = function () {
  57716. if (this._buffer0) {
  57717. this._buffer0.dispose();
  57718. this._buffer0 = null;
  57719. }
  57720. if (this._buffer1) {
  57721. this._buffer1.dispose();
  57722. this._buffer1 = null;
  57723. }
  57724. if (this._spriteBuffer) {
  57725. this._spriteBuffer.dispose();
  57726. this._spriteBuffer = null;
  57727. }
  57728. };
  57729. GPUParticleSystem.prototype._releaseVAOs = function () {
  57730. if (!this._updateVAO) {
  57731. return;
  57732. }
  57733. for (var index = 0; index < this._updateVAO.length; index++) {
  57734. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57735. }
  57736. this._updateVAO = [];
  57737. for (var index = 0; index < this._renderVAO.length; index++) {
  57738. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57739. }
  57740. this._renderVAO = [];
  57741. };
  57742. /**
  57743. * Disposes the particle system and free the associated resources
  57744. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57745. */
  57746. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57747. if (disposeTexture === void 0) { disposeTexture = true; }
  57748. var index = this._scene.particleSystems.indexOf(this);
  57749. if (index > -1) {
  57750. this._scene.particleSystems.splice(index, 1);
  57751. }
  57752. this._releaseBuffers();
  57753. this._releaseVAOs();
  57754. if (this._colorGradientsTexture) {
  57755. this._colorGradientsTexture.dispose();
  57756. this._colorGradientsTexture = null;
  57757. }
  57758. if (this._sizeGradientsTexture) {
  57759. this._sizeGradientsTexture.dispose();
  57760. this._sizeGradientsTexture = null;
  57761. }
  57762. if (this._randomTexture) {
  57763. this._randomTexture.dispose();
  57764. this._randomTexture = null;
  57765. }
  57766. if (this._randomTexture2) {
  57767. this._randomTexture2.dispose();
  57768. this._randomTexture2 = null;
  57769. }
  57770. if (disposeTexture && this.particleTexture) {
  57771. this.particleTexture.dispose();
  57772. this.particleTexture = null;
  57773. }
  57774. // Callback
  57775. this.onDisposeObservable.notifyObservers(this);
  57776. this.onDisposeObservable.clear();
  57777. };
  57778. /**
  57779. * Clones the particle system.
  57780. * @param name The name of the cloned object
  57781. * @param newEmitter The new emitter to use
  57782. * @returns the cloned particle system
  57783. */
  57784. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57785. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57786. BABYLON.Tools.DeepCopy(this, result);
  57787. if (newEmitter === undefined) {
  57788. newEmitter = this.emitter;
  57789. }
  57790. result.emitter = newEmitter;
  57791. if (this.particleTexture) {
  57792. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57793. }
  57794. return result;
  57795. };
  57796. /**
  57797. * Serializes the particle system to a JSON object.
  57798. * @returns the JSON object
  57799. */
  57800. GPUParticleSystem.prototype.serialize = function () {
  57801. var serializationObject = {};
  57802. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57803. return serializationObject;
  57804. };
  57805. /**
  57806. * Parses a JSON object to create a GPU particle system.
  57807. * @param parsedParticleSystem The JSON object to parse
  57808. * @param scene The scene to create the particle system in
  57809. * @param rootUrl The root url to use to load external dependencies like texture
  57810. * @returns the parsed GPU particle system
  57811. */
  57812. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57813. var name = parsedParticleSystem.name;
  57814. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57815. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57816. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57817. return particleSystem;
  57818. };
  57819. return GPUParticleSystem;
  57820. }());
  57821. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57822. })(BABYLON || (BABYLON = {}));
  57823. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57824. var BABYLON;
  57825. (function (BABYLON) {
  57826. /**
  57827. * Represents one particle of a solid particle system.
  57828. */
  57829. var SolidParticle = /** @class */ (function () {
  57830. /**
  57831. * Creates a Solid Particle object.
  57832. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57833. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57834. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57835. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57836. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57837. * @param shapeId (integer) is the model shape identifier in the SPS.
  57838. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57839. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57840. */
  57841. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57842. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57843. /**
  57844. * particle global index
  57845. */
  57846. this.idx = 0;
  57847. /**
  57848. * The color of the particle
  57849. */
  57850. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57851. /**
  57852. * The world space position of the particle.
  57853. */
  57854. this.position = BABYLON.Vector3.Zero();
  57855. /**
  57856. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57857. */
  57858. this.rotation = BABYLON.Vector3.Zero();
  57859. /**
  57860. * The scaling of the particle.
  57861. */
  57862. this.scaling = BABYLON.Vector3.One();
  57863. /**
  57864. * The uvs of the particle.
  57865. */
  57866. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57867. /**
  57868. * The current speed of the particle.
  57869. */
  57870. this.velocity = BABYLON.Vector3.Zero();
  57871. /**
  57872. * The pivot point in the particle local space.
  57873. */
  57874. this.pivot = BABYLON.Vector3.Zero();
  57875. /**
  57876. * Must the particle be translated from its pivot point in its local space ?
  57877. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57878. * Default : false
  57879. */
  57880. this.translateFromPivot = false;
  57881. /**
  57882. * Is the particle active or not ?
  57883. */
  57884. this.alive = true;
  57885. /**
  57886. * Is the particle visible or not ?
  57887. */
  57888. this.isVisible = true;
  57889. /**
  57890. * Index of this particle in the global "positions" array (Internal use)
  57891. */
  57892. this._pos = 0;
  57893. /**
  57894. * Index of this particle in the global "indices" array (Internal use)
  57895. */
  57896. this._ind = 0;
  57897. /**
  57898. * ModelShape id of this particle
  57899. */
  57900. this.shapeId = 0;
  57901. /**
  57902. * Index of the particle in its shape id (Internal use)
  57903. */
  57904. this.idxInShape = 0;
  57905. /**
  57906. * Still set as invisible in order to skip useless computations (Internal use)
  57907. */
  57908. this._stillInvisible = false;
  57909. /**
  57910. * Last computed particle rotation matrix
  57911. */
  57912. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57913. /**
  57914. * Parent particle Id, if any.
  57915. * Default null.
  57916. */
  57917. this.parentId = null;
  57918. /**
  57919. * Internal global position in the SPS.
  57920. */
  57921. this._globalPosition = BABYLON.Vector3.Zero();
  57922. this.idx = particleIndex;
  57923. this._pos = positionIndex;
  57924. this._ind = indiceIndex;
  57925. this._model = model;
  57926. this.shapeId = shapeId;
  57927. this.idxInShape = idxInShape;
  57928. this._sps = sps;
  57929. if (modelBoundingInfo) {
  57930. this._modelBoundingInfo = modelBoundingInfo;
  57931. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57932. }
  57933. }
  57934. Object.defineProperty(SolidParticle.prototype, "scale", {
  57935. /**
  57936. * Legacy support, changed scale to scaling
  57937. */
  57938. get: function () {
  57939. return this.scaling;
  57940. },
  57941. /**
  57942. * Legacy support, changed scale to scaling
  57943. */
  57944. set: function (scale) {
  57945. this.scaling = scale;
  57946. },
  57947. enumerable: true,
  57948. configurable: true
  57949. });
  57950. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57951. /**
  57952. * Legacy support, changed quaternion to rotationQuaternion
  57953. */
  57954. get: function () {
  57955. return this.rotationQuaternion;
  57956. },
  57957. /**
  57958. * Legacy support, changed quaternion to rotationQuaternion
  57959. */
  57960. set: function (q) {
  57961. this.rotationQuaternion = q;
  57962. },
  57963. enumerable: true,
  57964. configurable: true
  57965. });
  57966. /**
  57967. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57968. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57969. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57970. * @returns true if it intersects
  57971. */
  57972. SolidParticle.prototype.intersectsMesh = function (target) {
  57973. if (!this._boundingInfo || !target._boundingInfo) {
  57974. return false;
  57975. }
  57976. if (this._sps._bSphereOnly) {
  57977. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57978. }
  57979. return this._boundingInfo.intersects(target._boundingInfo, false);
  57980. };
  57981. return SolidParticle;
  57982. }());
  57983. BABYLON.SolidParticle = SolidParticle;
  57984. /**
  57985. * Represents the shape of the model used by one particle of a solid particle system.
  57986. * SPS internal tool, don't use it manually.
  57987. */
  57988. var ModelShape = /** @class */ (function () {
  57989. /**
  57990. * 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.
  57991. * SPS internal tool, don't use it manually.
  57992. * @hidden
  57993. */
  57994. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57995. /**
  57996. * length of the shape in the model indices array (internal use)
  57997. */
  57998. this._indicesLength = 0;
  57999. this.shapeID = id;
  58000. this._shape = shape;
  58001. this._indicesLength = indicesLength;
  58002. this._shapeUV = shapeUV;
  58003. this._positionFunction = posFunction;
  58004. this._vertexFunction = vtxFunction;
  58005. }
  58006. return ModelShape;
  58007. }());
  58008. BABYLON.ModelShape = ModelShape;
  58009. /**
  58010. * Represents a Depth Sorted Particle in the solid particle system.
  58011. */
  58012. var DepthSortedParticle = /** @class */ (function () {
  58013. function DepthSortedParticle() {
  58014. /**
  58015. * Index of the particle in the "indices" array
  58016. */
  58017. this.ind = 0;
  58018. /**
  58019. * Length of the particle shape in the "indices" array
  58020. */
  58021. this.indicesLength = 0;
  58022. /**
  58023. * Squared distance from the particle to the camera
  58024. */
  58025. this.sqDistance = 0.0;
  58026. }
  58027. return DepthSortedParticle;
  58028. }());
  58029. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58030. })(BABYLON || (BABYLON = {}));
  58031. //# sourceMappingURL=babylon.solidParticle.js.map
  58032. var BABYLON;
  58033. (function (BABYLON) {
  58034. /**
  58035. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58036. *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.
  58037. * The SPS is also a particle system. It provides some methods to manage the particles.
  58038. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58039. *
  58040. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58041. */
  58042. var SolidParticleSystem = /** @class */ (function () {
  58043. /**
  58044. * Creates a SPS (Solid Particle System) object.
  58045. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58046. * @param scene (Scene) is the scene in which the SPS is added.
  58047. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58048. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58049. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58050. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58051. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58052. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58053. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58054. */
  58055. function SolidParticleSystem(name, scene, options) {
  58056. /**
  58057. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58058. * Example : var p = SPS.particles[i];
  58059. */
  58060. this.particles = new Array();
  58061. /**
  58062. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58063. */
  58064. this.nbParticles = 0;
  58065. /**
  58066. * If the particles must ever face the camera (default false). Useful for planar particles.
  58067. */
  58068. this.billboard = false;
  58069. /**
  58070. * Recompute normals when adding a shape
  58071. */
  58072. this.recomputeNormals = true;
  58073. /**
  58074. * This a counter ofr your own usage. It's not set by any SPS functions.
  58075. */
  58076. this.counter = 0;
  58077. /**
  58078. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58079. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58080. */
  58081. this.vars = {};
  58082. /**
  58083. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58084. */
  58085. this._bSphereOnly = false;
  58086. /**
  58087. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58088. */
  58089. this._bSphereRadiusFactor = 1.0;
  58090. this._positions = new Array();
  58091. this._indices = new Array();
  58092. this._normals = new Array();
  58093. this._colors = new Array();
  58094. this._uvs = new Array();
  58095. this._index = 0; // indices index
  58096. this._updatable = true;
  58097. this._pickable = false;
  58098. this._isVisibilityBoxLocked = false;
  58099. this._alwaysVisible = false;
  58100. this._depthSort = false;
  58101. this._shapeCounter = 0;
  58102. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58103. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58104. this._computeParticleColor = true;
  58105. this._computeParticleTexture = true;
  58106. this._computeParticleRotation = true;
  58107. this._computeParticleVertex = false;
  58108. this._computeBoundingBox = false;
  58109. this._depthSortParticles = true;
  58110. this._cam_axisZ = BABYLON.Vector3.Zero();
  58111. this._cam_axisY = BABYLON.Vector3.Zero();
  58112. this._cam_axisX = BABYLON.Vector3.Zero();
  58113. this._axisZ = BABYLON.Axis.Z;
  58114. this._camDir = BABYLON.Vector3.Zero();
  58115. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58116. this._rotMatrix = new BABYLON.Matrix();
  58117. this._invertMatrix = new BABYLON.Matrix();
  58118. this._rotated = BABYLON.Vector3.Zero();
  58119. this._quaternion = new BABYLON.Quaternion();
  58120. this._vertex = BABYLON.Vector3.Zero();
  58121. this._normal = BABYLON.Vector3.Zero();
  58122. this._yaw = 0.0;
  58123. this._pitch = 0.0;
  58124. this._roll = 0.0;
  58125. this._halfroll = 0.0;
  58126. this._halfpitch = 0.0;
  58127. this._halfyaw = 0.0;
  58128. this._sinRoll = 0.0;
  58129. this._cosRoll = 0.0;
  58130. this._sinPitch = 0.0;
  58131. this._cosPitch = 0.0;
  58132. this._sinYaw = 0.0;
  58133. this._cosYaw = 0.0;
  58134. this._mustUnrotateFixedNormals = false;
  58135. this._minimum = BABYLON.Vector3.Zero();
  58136. this._maximum = BABYLON.Vector3.Zero();
  58137. this._minBbox = BABYLON.Vector3.Zero();
  58138. this._maxBbox = BABYLON.Vector3.Zero();
  58139. this._particlesIntersect = false;
  58140. this._depthSortFunction = function (p1, p2) {
  58141. return (p2.sqDistance - p1.sqDistance);
  58142. };
  58143. this._needs32Bits = false;
  58144. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58145. this._scaledPivot = BABYLON.Vector3.Zero();
  58146. this._particleHasParent = false;
  58147. this.name = name;
  58148. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58149. this._camera = scene.activeCamera;
  58150. this._pickable = options ? options.isPickable : false;
  58151. this._depthSort = options ? options.enableDepthSort : false;
  58152. this._particlesIntersect = options ? options.particleIntersection : false;
  58153. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58154. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58155. if (options && options.updatable !== undefined) {
  58156. this._updatable = options.updatable;
  58157. }
  58158. else {
  58159. this._updatable = true;
  58160. }
  58161. if (this._pickable) {
  58162. this.pickedParticles = [];
  58163. }
  58164. if (this._depthSort) {
  58165. this.depthSortedParticles = [];
  58166. }
  58167. }
  58168. /**
  58169. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58170. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58171. * @returns the created mesh
  58172. */
  58173. SolidParticleSystem.prototype.buildMesh = function () {
  58174. if (this.nbParticles === 0) {
  58175. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58176. this.addShape(triangle, 1);
  58177. triangle.dispose();
  58178. }
  58179. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58180. this._positions32 = new Float32Array(this._positions);
  58181. this._uvs32 = new Float32Array(this._uvs);
  58182. this._colors32 = new Float32Array(this._colors);
  58183. if (this.recomputeNormals) {
  58184. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58185. }
  58186. this._normals32 = new Float32Array(this._normals);
  58187. this._fixedNormal32 = new Float32Array(this._normals);
  58188. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58189. this._unrotateFixedNormals();
  58190. }
  58191. var vertexData = new BABYLON.VertexData();
  58192. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58193. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58194. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58195. if (this._uvs32.length > 0) {
  58196. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58197. }
  58198. if (this._colors32.length > 0) {
  58199. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58200. }
  58201. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58202. vertexData.applyToMesh(mesh, this._updatable);
  58203. this.mesh = mesh;
  58204. this.mesh.isPickable = this._pickable;
  58205. // free memory
  58206. if (!this._depthSort) {
  58207. this._indices = null;
  58208. }
  58209. this._positions = null;
  58210. this._normals = null;
  58211. this._uvs = null;
  58212. this._colors = null;
  58213. if (!this._updatable) {
  58214. this.particles.length = 0;
  58215. }
  58216. return mesh;
  58217. };
  58218. /**
  58219. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58220. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58221. * Thus the particles generated from `digest()` have their property `position` set yet.
  58222. * @param mesh ( Mesh ) is the mesh to be digested
  58223. * @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
  58224. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58225. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58226. * @returns the current SPS
  58227. */
  58228. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58229. var size = (options && options.facetNb) || 1;
  58230. var number = (options && options.number) || 0;
  58231. var delta = (options && options.delta) || 0;
  58232. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58233. var meshInd = mesh.getIndices();
  58234. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58235. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58236. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58237. var f = 0; // facet counter
  58238. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58239. // compute size from number
  58240. if (number) {
  58241. number = (number > totalFacets) ? totalFacets : number;
  58242. size = Math.round(totalFacets / number);
  58243. delta = 0;
  58244. }
  58245. else {
  58246. size = (size > totalFacets) ? totalFacets : size;
  58247. }
  58248. var facetPos = []; // submesh positions
  58249. var facetInd = []; // submesh indices
  58250. var facetUV = []; // submesh UV
  58251. var facetCol = []; // submesh colors
  58252. var barycenter = BABYLON.Vector3.Zero();
  58253. var sizeO = size;
  58254. while (f < totalFacets) {
  58255. size = sizeO + Math.floor((1 + delta) * Math.random());
  58256. if (f > totalFacets - size) {
  58257. size = totalFacets - f;
  58258. }
  58259. // reset temp arrays
  58260. facetPos.length = 0;
  58261. facetInd.length = 0;
  58262. facetUV.length = 0;
  58263. facetCol.length = 0;
  58264. // iterate over "size" facets
  58265. var fi = 0;
  58266. for (var j = f * 3; j < (f + size) * 3; j++) {
  58267. facetInd.push(fi);
  58268. var i = meshInd[j];
  58269. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58270. if (meshUV) {
  58271. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58272. }
  58273. if (meshCol) {
  58274. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58275. }
  58276. fi++;
  58277. }
  58278. // create a model shape for each single particle
  58279. var idx = this.nbParticles;
  58280. var shape = this._posToShape(facetPos);
  58281. var shapeUV = this._uvsToShapeUV(facetUV);
  58282. // compute the barycenter of the shape
  58283. var v;
  58284. for (v = 0; v < shape.length; v++) {
  58285. barycenter.addInPlace(shape[v]);
  58286. }
  58287. barycenter.scaleInPlace(1 / shape.length);
  58288. // shift the shape from its barycenter to the origin
  58289. for (v = 0; v < shape.length; v++) {
  58290. shape[v].subtractInPlace(barycenter);
  58291. }
  58292. var bInfo;
  58293. if (this._particlesIntersect) {
  58294. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58295. }
  58296. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58297. // add the particle in the SPS
  58298. var currentPos = this._positions.length;
  58299. var currentInd = this._indices.length;
  58300. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58301. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58302. // initialize the particle position
  58303. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58304. this._index += shape.length;
  58305. idx++;
  58306. this.nbParticles++;
  58307. this._shapeCounter++;
  58308. f += size;
  58309. }
  58310. return this;
  58311. };
  58312. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58313. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58314. var index = 0;
  58315. var idx = 0;
  58316. for (var p = 0; p < this.particles.length; p++) {
  58317. this._particle = this.particles[p];
  58318. this._shape = this._particle._model._shape;
  58319. if (this._particle.rotationQuaternion) {
  58320. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58321. }
  58322. else {
  58323. this._yaw = this._particle.rotation.y;
  58324. this._pitch = this._particle.rotation.x;
  58325. this._roll = this._particle.rotation.z;
  58326. this._quaternionRotationYPR();
  58327. }
  58328. this._quaternionToRotationMatrix();
  58329. this._rotMatrix.invertToRef(this._invertMatrix);
  58330. for (var pt = 0; pt < this._shape.length; pt++) {
  58331. idx = index + pt * 3;
  58332. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58333. this._fixedNormal32[idx] = this._normal.x;
  58334. this._fixedNormal32[idx + 1] = this._normal.y;
  58335. this._fixedNormal32[idx + 2] = this._normal.z;
  58336. }
  58337. index = idx + 3;
  58338. }
  58339. };
  58340. //reset copy
  58341. SolidParticleSystem.prototype._resetCopy = function () {
  58342. this._copy.position.x = 0;
  58343. this._copy.position.y = 0;
  58344. this._copy.position.z = 0;
  58345. this._copy.rotation.x = 0;
  58346. this._copy.rotation.y = 0;
  58347. this._copy.rotation.z = 0;
  58348. this._copy.rotationQuaternion = null;
  58349. this._copy.scaling.x = 1.0;
  58350. this._copy.scaling.y = 1.0;
  58351. this._copy.scaling.z = 1.0;
  58352. this._copy.uvs.x = 0;
  58353. this._copy.uvs.y = 0;
  58354. this._copy.uvs.z = 1.0;
  58355. this._copy.uvs.w = 1.0;
  58356. this._copy.color = null;
  58357. this._copy.translateFromPivot = false;
  58358. };
  58359. // _meshBuilder : inserts the shape model in the global SPS mesh
  58360. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58361. var i;
  58362. var u = 0;
  58363. var c = 0;
  58364. var n = 0;
  58365. this._resetCopy();
  58366. if (options && options.positionFunction) { // call to custom positionFunction
  58367. options.positionFunction(this._copy, idx, idxInShape);
  58368. this._mustUnrotateFixedNormals = true;
  58369. }
  58370. if (this._copy.rotationQuaternion) {
  58371. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58372. }
  58373. else {
  58374. this._yaw = this._copy.rotation.y;
  58375. this._pitch = this._copy.rotation.x;
  58376. this._roll = this._copy.rotation.z;
  58377. this._quaternionRotationYPR();
  58378. }
  58379. this._quaternionToRotationMatrix();
  58380. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58381. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58382. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58383. if (this._copy.translateFromPivot) {
  58384. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58385. }
  58386. else {
  58387. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58388. }
  58389. for (i = 0; i < shape.length; i++) {
  58390. this._vertex.x = shape[i].x;
  58391. this._vertex.y = shape[i].y;
  58392. this._vertex.z = shape[i].z;
  58393. if (options && options.vertexFunction) {
  58394. options.vertexFunction(this._copy, this._vertex, i);
  58395. }
  58396. this._vertex.x *= this._copy.scaling.x;
  58397. this._vertex.y *= this._copy.scaling.y;
  58398. this._vertex.z *= this._copy.scaling.z;
  58399. this._vertex.x -= this._scaledPivot.x;
  58400. this._vertex.y -= this._scaledPivot.y;
  58401. this._vertex.z -= this._scaledPivot.z;
  58402. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58403. this._rotated.addInPlace(this._pivotBackTranslation);
  58404. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58405. if (meshUV) {
  58406. 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);
  58407. u += 2;
  58408. }
  58409. if (this._copy.color) {
  58410. this._color = this._copy.color;
  58411. }
  58412. else if (meshCol && meshCol[c] !== undefined) {
  58413. this._color.r = meshCol[c];
  58414. this._color.g = meshCol[c + 1];
  58415. this._color.b = meshCol[c + 2];
  58416. this._color.a = meshCol[c + 3];
  58417. }
  58418. else {
  58419. this._color.r = 1.0;
  58420. this._color.g = 1.0;
  58421. this._color.b = 1.0;
  58422. this._color.a = 1.0;
  58423. }
  58424. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58425. c += 4;
  58426. if (!this.recomputeNormals && meshNor) {
  58427. this._normal.x = meshNor[n];
  58428. this._normal.y = meshNor[n + 1];
  58429. this._normal.z = meshNor[n + 2];
  58430. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58431. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58432. n += 3;
  58433. }
  58434. }
  58435. for (i = 0; i < meshInd.length; i++) {
  58436. var current_ind = p + meshInd[i];
  58437. indices.push(current_ind);
  58438. if (current_ind > 65535) {
  58439. this._needs32Bits = true;
  58440. }
  58441. }
  58442. if (this._pickable) {
  58443. var nbfaces = meshInd.length / 3;
  58444. for (i = 0; i < nbfaces; i++) {
  58445. this.pickedParticles.push({ idx: idx, faceId: i });
  58446. }
  58447. }
  58448. if (this._depthSort) {
  58449. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58450. }
  58451. return this._copy;
  58452. };
  58453. // returns a shape array from positions array
  58454. SolidParticleSystem.prototype._posToShape = function (positions) {
  58455. var shape = [];
  58456. for (var i = 0; i < positions.length; i += 3) {
  58457. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58458. }
  58459. return shape;
  58460. };
  58461. // returns a shapeUV array from a Vector4 uvs
  58462. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58463. var shapeUV = [];
  58464. if (uvs) {
  58465. for (var i = 0; i < uvs.length; i++)
  58466. shapeUV.push(uvs[i]);
  58467. }
  58468. return shapeUV;
  58469. };
  58470. // adds a new particle object in the particles array
  58471. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58472. if (bInfo === void 0) { bInfo = null; }
  58473. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58474. this.particles.push(sp);
  58475. return sp;
  58476. };
  58477. /**
  58478. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58479. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58480. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58481. * @param nb (positive integer) the number of particles to be created from this model
  58482. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58483. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58484. * @returns the number of shapes in the system
  58485. */
  58486. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58487. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58488. var meshInd = mesh.getIndices();
  58489. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58490. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58491. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58492. var bbInfo;
  58493. if (this._particlesIntersect) {
  58494. bbInfo = mesh.getBoundingInfo();
  58495. }
  58496. var shape = this._posToShape(meshPos);
  58497. var shapeUV = this._uvsToShapeUV(meshUV);
  58498. var posfunc = options ? options.positionFunction : null;
  58499. var vtxfunc = options ? options.vertexFunction : null;
  58500. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58501. // particles
  58502. var sp;
  58503. var currentCopy;
  58504. var idx = this.nbParticles;
  58505. for (var i = 0; i < nb; i++) {
  58506. var currentPos = this._positions.length;
  58507. var currentInd = this._indices.length;
  58508. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58509. if (this._updatable) {
  58510. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58511. sp.position.copyFrom(currentCopy.position);
  58512. sp.rotation.copyFrom(currentCopy.rotation);
  58513. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58514. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58515. }
  58516. if (currentCopy.color && sp.color) {
  58517. sp.color.copyFrom(currentCopy.color);
  58518. }
  58519. sp.scaling.copyFrom(currentCopy.scaling);
  58520. sp.uvs.copyFrom(currentCopy.uvs);
  58521. }
  58522. this._index += shape.length;
  58523. idx++;
  58524. }
  58525. this.nbParticles += nb;
  58526. this._shapeCounter++;
  58527. return this._shapeCounter - 1;
  58528. };
  58529. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58530. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58531. this._resetCopy();
  58532. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58533. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58534. }
  58535. if (this._copy.rotationQuaternion) {
  58536. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58537. }
  58538. else {
  58539. this._yaw = this._copy.rotation.y;
  58540. this._pitch = this._copy.rotation.x;
  58541. this._roll = this._copy.rotation.z;
  58542. this._quaternionRotationYPR();
  58543. }
  58544. this._quaternionToRotationMatrix();
  58545. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58546. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58547. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58548. if (this._copy.translateFromPivot) {
  58549. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58550. }
  58551. else {
  58552. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58553. }
  58554. this._shape = particle._model._shape;
  58555. for (var pt = 0; pt < this._shape.length; pt++) {
  58556. this._vertex.x = this._shape[pt].x;
  58557. this._vertex.y = this._shape[pt].y;
  58558. this._vertex.z = this._shape[pt].z;
  58559. if (particle._model._vertexFunction) {
  58560. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58561. }
  58562. this._vertex.x *= this._copy.scaling.x;
  58563. this._vertex.y *= this._copy.scaling.y;
  58564. this._vertex.z *= this._copy.scaling.z;
  58565. this._vertex.x -= this._scaledPivot.x;
  58566. this._vertex.y -= this._scaledPivot.y;
  58567. this._vertex.z -= this._scaledPivot.z;
  58568. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58569. this._rotated.addInPlace(this._pivotBackTranslation);
  58570. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58571. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58572. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58573. }
  58574. particle.position.x = 0.0;
  58575. particle.position.y = 0.0;
  58576. particle.position.z = 0.0;
  58577. particle.rotation.x = 0.0;
  58578. particle.rotation.y = 0.0;
  58579. particle.rotation.z = 0.0;
  58580. particle.rotationQuaternion = null;
  58581. particle.scaling.x = 1.0;
  58582. particle.scaling.y = 1.0;
  58583. particle.scaling.z = 1.0;
  58584. particle.uvs.x = 0.0;
  58585. particle.uvs.y = 0.0;
  58586. particle.uvs.z = 1.0;
  58587. particle.uvs.w = 1.0;
  58588. particle.pivot.x = 0.0;
  58589. particle.pivot.y = 0.0;
  58590. particle.pivot.z = 0.0;
  58591. particle.translateFromPivot = false;
  58592. particle.parentId = null;
  58593. };
  58594. /**
  58595. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58596. * @returns the SPS.
  58597. */
  58598. SolidParticleSystem.prototype.rebuildMesh = function () {
  58599. for (var p = 0; p < this.particles.length; p++) {
  58600. this._rebuildParticle(this.particles[p]);
  58601. }
  58602. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58603. return this;
  58604. };
  58605. /**
  58606. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58607. * This method calls `updateParticle()` for each particle of the SPS.
  58608. * For an animated SPS, it is usually called within the render loop.
  58609. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58610. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58611. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58612. * @returns the SPS.
  58613. */
  58614. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58615. if (start === void 0) { start = 0; }
  58616. if (end === void 0) { end = this.nbParticles - 1; }
  58617. if (update === void 0) { update = true; }
  58618. if (!this._updatable) {
  58619. return this;
  58620. }
  58621. // custom beforeUpdate
  58622. this.beforeUpdateParticles(start, end, update);
  58623. this._cam_axisX.x = 1.0;
  58624. this._cam_axisX.y = 0.0;
  58625. this._cam_axisX.z = 0.0;
  58626. this._cam_axisY.x = 0.0;
  58627. this._cam_axisY.y = 1.0;
  58628. this._cam_axisY.z = 0.0;
  58629. this._cam_axisZ.x = 0.0;
  58630. this._cam_axisZ.y = 0.0;
  58631. this._cam_axisZ.z = 1.0;
  58632. // cases when the World Matrix is to be computed first
  58633. if (this.billboard || this._depthSort) {
  58634. this.mesh.computeWorldMatrix(true);
  58635. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58636. }
  58637. // if the particles will always face the camera
  58638. if (this.billboard) {
  58639. // compute the camera position and un-rotate it by the current mesh rotation
  58640. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58641. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58642. this._cam_axisZ.normalize();
  58643. // same for camera up vector extracted from the cam view matrix
  58644. var view = this._camera.getViewMatrix(true);
  58645. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58646. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58647. this._cam_axisY.normalize();
  58648. this._cam_axisX.normalize();
  58649. }
  58650. // if depthSort, compute the camera global position in the mesh local system
  58651. if (this._depthSort) {
  58652. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58653. }
  58654. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58655. var idx = 0; // current position index in the global array positions32
  58656. var index = 0; // position start index in the global array positions32 of the current particle
  58657. var colidx = 0; // current color index in the global array colors32
  58658. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58659. var uvidx = 0; // current uv index in the global array uvs32
  58660. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58661. var pt = 0; // current index in the particle model shape
  58662. if (this.mesh.isFacetDataEnabled) {
  58663. this._computeBoundingBox = true;
  58664. }
  58665. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58666. if (this._computeBoundingBox) {
  58667. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58668. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58669. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58670. }
  58671. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58672. if (this.mesh._boundingInfo) {
  58673. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58674. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58675. }
  58676. }
  58677. }
  58678. // particle loop
  58679. index = this.particles[start]._pos;
  58680. var vpos = (index / 3) | 0;
  58681. colorIndex = vpos * 4;
  58682. uvIndex = vpos * 2;
  58683. for (var p = start; p <= end; p++) {
  58684. this._particle = this.particles[p];
  58685. this._shape = this._particle._model._shape;
  58686. this._shapeUV = this._particle._model._shapeUV;
  58687. // call to custom user function to update the particle properties
  58688. this.updateParticle(this._particle);
  58689. // camera-particle distance for depth sorting
  58690. if (this._depthSort && this._depthSortParticles) {
  58691. var dsp = this.depthSortedParticles[p];
  58692. dsp.ind = this._particle._ind;
  58693. dsp.indicesLength = this._particle._model._indicesLength;
  58694. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58695. }
  58696. // skip the computations for inactive or already invisible particles
  58697. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58698. // increment indexes for the next particle
  58699. pt = this._shape.length;
  58700. index += pt * 3;
  58701. colorIndex += pt * 4;
  58702. uvIndex += pt * 2;
  58703. continue;
  58704. }
  58705. if (this._particle.isVisible) {
  58706. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58707. this._particleHasParent = (this._particle.parentId !== null);
  58708. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58709. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58710. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58711. // particle rotation matrix
  58712. if (this.billboard) {
  58713. this._particle.rotation.x = 0.0;
  58714. this._particle.rotation.y = 0.0;
  58715. }
  58716. if (this._computeParticleRotation || this.billboard) {
  58717. if (this._particle.rotationQuaternion) {
  58718. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58719. }
  58720. else {
  58721. this._yaw = this._particle.rotation.y;
  58722. this._pitch = this._particle.rotation.x;
  58723. this._roll = this._particle.rotation.z;
  58724. this._quaternionRotationYPR();
  58725. }
  58726. this._quaternionToRotationMatrix();
  58727. }
  58728. if (this._particleHasParent) {
  58729. this._parent = this.particles[this._particle.parentId];
  58730. 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];
  58731. 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];
  58732. 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];
  58733. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58734. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58735. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58736. if (this._computeParticleRotation || this.billboard) {
  58737. 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];
  58738. 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];
  58739. 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];
  58740. 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];
  58741. 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];
  58742. 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];
  58743. 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];
  58744. 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];
  58745. 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];
  58746. }
  58747. }
  58748. else {
  58749. this._particle._globalPosition.x = this._particle.position.x;
  58750. this._particle._globalPosition.y = this._particle.position.y;
  58751. this._particle._globalPosition.z = this._particle.position.z;
  58752. if (this._computeParticleRotation || this.billboard) {
  58753. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58754. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58755. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58756. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58757. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58758. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58759. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58760. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58761. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58762. }
  58763. }
  58764. if (this._particle.translateFromPivot) {
  58765. this._pivotBackTranslation.x = 0.0;
  58766. this._pivotBackTranslation.y = 0.0;
  58767. this._pivotBackTranslation.z = 0.0;
  58768. }
  58769. else {
  58770. this._pivotBackTranslation.x = this._scaledPivot.x;
  58771. this._pivotBackTranslation.y = this._scaledPivot.y;
  58772. this._pivotBackTranslation.z = this._scaledPivot.z;
  58773. }
  58774. // particle vertex loop
  58775. for (pt = 0; pt < this._shape.length; pt++) {
  58776. idx = index + pt * 3;
  58777. colidx = colorIndex + pt * 4;
  58778. uvidx = uvIndex + pt * 2;
  58779. this._vertex.x = this._shape[pt].x;
  58780. this._vertex.y = this._shape[pt].y;
  58781. this._vertex.z = this._shape[pt].z;
  58782. if (this._computeParticleVertex) {
  58783. this.updateParticleVertex(this._particle, this._vertex, pt);
  58784. }
  58785. // positions
  58786. this._vertex.x *= this._particle.scaling.x;
  58787. this._vertex.y *= this._particle.scaling.y;
  58788. this._vertex.z *= this._particle.scaling.z;
  58789. this._vertex.x -= this._scaledPivot.x;
  58790. this._vertex.y -= this._scaledPivot.y;
  58791. this._vertex.z -= this._scaledPivot.z;
  58792. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58793. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58794. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58795. this._rotated.x += this._pivotBackTranslation.x;
  58796. this._rotated.y += this._pivotBackTranslation.y;
  58797. this._rotated.z += this._pivotBackTranslation.z;
  58798. 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;
  58799. 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;
  58800. 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;
  58801. if (this._computeBoundingBox) {
  58802. if (this._positions32[idx] < this._minimum.x) {
  58803. this._minimum.x = this._positions32[idx];
  58804. }
  58805. if (this._positions32[idx] > this._maximum.x) {
  58806. this._maximum.x = this._positions32[idx];
  58807. }
  58808. if (this._positions32[idx + 1] < this._minimum.y) {
  58809. this._minimum.y = this._positions32[idx + 1];
  58810. }
  58811. if (this._positions32[idx + 1] > this._maximum.y) {
  58812. this._maximum.y = this._positions32[idx + 1];
  58813. }
  58814. if (this._positions32[idx + 2] < this._minimum.z) {
  58815. this._minimum.z = this._positions32[idx + 2];
  58816. }
  58817. if (this._positions32[idx + 2] > this._maximum.z) {
  58818. this._maximum.z = this._positions32[idx + 2];
  58819. }
  58820. }
  58821. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58822. if (!this._computeParticleVertex) {
  58823. this._normal.x = this._fixedNormal32[idx];
  58824. this._normal.y = this._fixedNormal32[idx + 1];
  58825. this._normal.z = this._fixedNormal32[idx + 2];
  58826. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58827. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58828. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58829. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58830. 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;
  58831. 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;
  58832. }
  58833. if (this._computeParticleColor && this._particle.color) {
  58834. this._colors32[colidx] = this._particle.color.r;
  58835. this._colors32[colidx + 1] = this._particle.color.g;
  58836. this._colors32[colidx + 2] = this._particle.color.b;
  58837. this._colors32[colidx + 3] = this._particle.color.a;
  58838. }
  58839. if (this._computeParticleTexture) {
  58840. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58841. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58842. }
  58843. }
  58844. }
  58845. // particle just set invisible : scaled to zero and positioned at the origin
  58846. else {
  58847. this._particle._stillInvisible = true; // mark the particle as invisible
  58848. for (pt = 0; pt < this._shape.length; pt++) {
  58849. idx = index + pt * 3;
  58850. colidx = colorIndex + pt * 4;
  58851. uvidx = uvIndex + pt * 2;
  58852. this._positions32[idx] = 0.0;
  58853. this._positions32[idx + 1] = 0.0;
  58854. this._positions32[idx + 2] = 0.0;
  58855. this._normals32[idx] = 0.0;
  58856. this._normals32[idx + 1] = 0.0;
  58857. this._normals32[idx + 2] = 0.0;
  58858. if (this._computeParticleColor && this._particle.color) {
  58859. this._colors32[colidx] = this._particle.color.r;
  58860. this._colors32[colidx + 1] = this._particle.color.g;
  58861. this._colors32[colidx + 2] = this._particle.color.b;
  58862. this._colors32[colidx + 3] = this._particle.color.a;
  58863. }
  58864. if (this._computeParticleTexture) {
  58865. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58866. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58867. }
  58868. }
  58869. }
  58870. // if the particle intersections must be computed : update the bbInfo
  58871. if (this._particlesIntersect) {
  58872. var bInfo = this._particle._boundingInfo;
  58873. var bBox = bInfo.boundingBox;
  58874. var bSphere = bInfo.boundingSphere;
  58875. if (!this._bSphereOnly) {
  58876. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58877. for (var b = 0; b < bBox.vectors.length; b++) {
  58878. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58879. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58880. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58881. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58882. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58883. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58884. 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;
  58885. 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;
  58886. 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;
  58887. }
  58888. bBox._update(this.mesh._worldMatrix);
  58889. }
  58890. // place and scale the particle bouding sphere in the SPS local system, then update it
  58891. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58892. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58893. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58894. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58895. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58896. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58897. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58898. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58899. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58900. 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));
  58901. bSphere._update(this.mesh._worldMatrix);
  58902. }
  58903. // increment indexes for the next particle
  58904. index = idx + 3;
  58905. colorIndex = colidx + 4;
  58906. uvIndex = uvidx + 2;
  58907. }
  58908. // if the VBO must be updated
  58909. if (update) {
  58910. if (this._computeParticleColor) {
  58911. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58912. }
  58913. if (this._computeParticleTexture) {
  58914. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58915. }
  58916. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58917. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58918. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58919. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58920. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58921. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58922. for (var i = 0; i < this._normals32.length; i++) {
  58923. this._fixedNormal32[i] = this._normals32[i];
  58924. }
  58925. }
  58926. if (!this.mesh.areNormalsFrozen) {
  58927. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58928. }
  58929. }
  58930. if (this._depthSort && this._depthSortParticles) {
  58931. this.depthSortedParticles.sort(this._depthSortFunction);
  58932. var dspl = this.depthSortedParticles.length;
  58933. var sorted = 0;
  58934. var lind = 0;
  58935. var sind = 0;
  58936. var sid = 0;
  58937. for (sorted = 0; sorted < dspl; sorted++) {
  58938. lind = this.depthSortedParticles[sorted].indicesLength;
  58939. sind = this.depthSortedParticles[sorted].ind;
  58940. for (var i = 0; i < lind; i++) {
  58941. this._indices32[sid] = this._indices[sind + i];
  58942. sid++;
  58943. }
  58944. }
  58945. this.mesh.updateIndices(this._indices32);
  58946. }
  58947. }
  58948. if (this._computeBoundingBox) {
  58949. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58950. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58951. }
  58952. this.afterUpdateParticles(start, end, update);
  58953. return this;
  58954. };
  58955. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58956. this._halfroll = this._roll * 0.5;
  58957. this._halfpitch = this._pitch * 0.5;
  58958. this._halfyaw = this._yaw * 0.5;
  58959. this._sinRoll = Math.sin(this._halfroll);
  58960. this._cosRoll = Math.cos(this._halfroll);
  58961. this._sinPitch = Math.sin(this._halfpitch);
  58962. this._cosPitch = Math.cos(this._halfpitch);
  58963. this._sinYaw = Math.sin(this._halfyaw);
  58964. this._cosYaw = Math.cos(this._halfyaw);
  58965. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58966. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58967. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58968. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58969. };
  58970. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58971. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58972. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58973. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58974. this._rotMatrix.m[3] = 0;
  58975. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58976. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58977. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58978. this._rotMatrix.m[7] = 0;
  58979. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58980. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58981. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58982. this._rotMatrix.m[11] = 0;
  58983. this._rotMatrix.m[12] = 0;
  58984. this._rotMatrix.m[13] = 0;
  58985. this._rotMatrix.m[14] = 0;
  58986. this._rotMatrix.m[15] = 1.0;
  58987. };
  58988. /**
  58989. * Disposes the SPS.
  58990. */
  58991. SolidParticleSystem.prototype.dispose = function () {
  58992. this.mesh.dispose();
  58993. this.vars = null;
  58994. // drop references to internal big arrays for the GC
  58995. this._positions = null;
  58996. this._indices = null;
  58997. this._normals = null;
  58998. this._uvs = null;
  58999. this._colors = null;
  59000. this._indices32 = null;
  59001. this._positions32 = null;
  59002. this._normals32 = null;
  59003. this._fixedNormal32 = null;
  59004. this._uvs32 = null;
  59005. this._colors32 = null;
  59006. this.pickedParticles = null;
  59007. };
  59008. /**
  59009. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59010. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59011. * @returns the SPS.
  59012. */
  59013. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59014. if (!this._isVisibilityBoxLocked) {
  59015. this.mesh.refreshBoundingInfo();
  59016. }
  59017. return this;
  59018. };
  59019. /**
  59020. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59021. * @param size the size (float) of the visibility box
  59022. * note : this doesn't lock the SPS mesh bounding box.
  59023. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59024. */
  59025. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59026. var vis = size / 2;
  59027. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59028. };
  59029. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59030. /**
  59031. * Gets whether the SPS as always visible or not
  59032. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59033. */
  59034. get: function () {
  59035. return this._alwaysVisible;
  59036. },
  59037. /**
  59038. * Sets the SPS as always visible or not
  59039. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59040. */
  59041. set: function (val) {
  59042. this._alwaysVisible = val;
  59043. this.mesh.alwaysSelectAsActiveMesh = val;
  59044. },
  59045. enumerable: true,
  59046. configurable: true
  59047. });
  59048. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59049. /**
  59050. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59051. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59052. */
  59053. get: function () {
  59054. return this._isVisibilityBoxLocked;
  59055. },
  59056. /**
  59057. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59058. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59059. */
  59060. set: function (val) {
  59061. this._isVisibilityBoxLocked = val;
  59062. var boundingInfo = this.mesh.getBoundingInfo();
  59063. boundingInfo.isLocked = val;
  59064. },
  59065. enumerable: true,
  59066. configurable: true
  59067. });
  59068. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59069. /**
  59070. * Gets if `setParticles()` computes the particle rotations or not.
  59071. * Default value : true. The SPS is faster when it's set to false.
  59072. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59073. */
  59074. get: function () {
  59075. return this._computeParticleRotation;
  59076. },
  59077. /**
  59078. * Tells to `setParticles()` to compute the particle rotations or not.
  59079. * Default value : true. The SPS is faster when it's set to false.
  59080. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59081. */
  59082. set: function (val) {
  59083. this._computeParticleRotation = val;
  59084. },
  59085. enumerable: true,
  59086. configurable: true
  59087. });
  59088. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59089. /**
  59090. * Gets if `setParticles()` computes the particle colors or not.
  59091. * Default value : true. The SPS is faster when it's set to false.
  59092. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59093. */
  59094. get: function () {
  59095. return this._computeParticleColor;
  59096. },
  59097. /**
  59098. * Tells to `setParticles()` to compute the particle colors or not.
  59099. * Default value : true. The SPS is faster when it's set to false.
  59100. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59101. */
  59102. set: function (val) {
  59103. this._computeParticleColor = val;
  59104. },
  59105. enumerable: true,
  59106. configurable: true
  59107. });
  59108. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59109. /**
  59110. * Gets if `setParticles()` computes the particle textures or not.
  59111. * Default value : true. The SPS is faster when it's set to false.
  59112. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59113. */
  59114. get: function () {
  59115. return this._computeParticleTexture;
  59116. },
  59117. set: function (val) {
  59118. this._computeParticleTexture = val;
  59119. },
  59120. enumerable: true,
  59121. configurable: true
  59122. });
  59123. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59124. /**
  59125. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59126. * Default value : false. The SPS is faster when it's set to false.
  59127. * Note : the particle custom vertex positions aren't stored values.
  59128. */
  59129. get: function () {
  59130. return this._computeParticleVertex;
  59131. },
  59132. /**
  59133. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59134. * Default value : false. The SPS is faster when it's set to false.
  59135. * Note : the particle custom vertex positions aren't stored values.
  59136. */
  59137. set: function (val) {
  59138. this._computeParticleVertex = val;
  59139. },
  59140. enumerable: true,
  59141. configurable: true
  59142. });
  59143. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59144. /**
  59145. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59146. */
  59147. get: function () {
  59148. return this._computeBoundingBox;
  59149. },
  59150. /**
  59151. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59152. */
  59153. set: function (val) {
  59154. this._computeBoundingBox = val;
  59155. },
  59156. enumerable: true,
  59157. configurable: true
  59158. });
  59159. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59160. /**
  59161. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59162. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59163. * Default : `true`
  59164. */
  59165. get: function () {
  59166. return this._depthSortParticles;
  59167. },
  59168. /**
  59169. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59170. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59171. * Default : `true`
  59172. */
  59173. set: function (val) {
  59174. this._depthSortParticles = val;
  59175. },
  59176. enumerable: true,
  59177. configurable: true
  59178. });
  59179. // =======================================================================
  59180. // Particle behavior logic
  59181. // these following methods may be overwritten by the user to fit his needs
  59182. /**
  59183. * This function does nothing. It may be overwritten to set all the particle first values.
  59184. * The SPS doesn't call this function, you may have to call it by your own.
  59185. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59186. */
  59187. SolidParticleSystem.prototype.initParticles = function () {
  59188. };
  59189. /**
  59190. * This function does nothing. It may be overwritten to recycle a particle.
  59191. * The SPS doesn't call this function, you may have to call it by your own.
  59192. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59193. * @param particle The particle to recycle
  59194. * @returns the recycled particle
  59195. */
  59196. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59197. return particle;
  59198. };
  59199. /**
  59200. * Updates a particle : this function should be overwritten by the user.
  59201. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59202. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59203. * @example : just set a particle position or velocity and recycle conditions
  59204. * @param particle The particle to update
  59205. * @returns the updated particle
  59206. */
  59207. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59208. return particle;
  59209. };
  59210. /**
  59211. * Updates a vertex of a particle : it can be overwritten by the user.
  59212. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59213. * @param particle the current particle
  59214. * @param vertex the current index of the current particle
  59215. * @param pt the index of the current vertex in the particle shape
  59216. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59217. * @example : just set a vertex particle position
  59218. * @returns the updated vertex
  59219. */
  59220. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59221. return vertex;
  59222. };
  59223. /**
  59224. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59225. * This does nothing and may be overwritten by the user.
  59226. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59227. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59228. * @param update the boolean update value actually passed to setParticles()
  59229. */
  59230. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59231. };
  59232. /**
  59233. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59234. * This will be passed three parameters.
  59235. * This does nothing and may be overwritten by the user.
  59236. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59237. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59238. * @param update the boolean update value actually passed to setParticles()
  59239. */
  59240. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59241. };
  59242. return SolidParticleSystem;
  59243. }());
  59244. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59245. })(BABYLON || (BABYLON = {}));
  59246. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59247. var BABYLON;
  59248. (function (BABYLON) {
  59249. var ShaderMaterial = /** @class */ (function (_super) {
  59250. __extends(ShaderMaterial, _super);
  59251. function ShaderMaterial(name, scene, shaderPath, options) {
  59252. var _this = _super.call(this, name, scene) || this;
  59253. _this._textures = {};
  59254. _this._textureArrays = {};
  59255. _this._floats = {};
  59256. _this._ints = {};
  59257. _this._floatsArrays = {};
  59258. _this._colors3 = {};
  59259. _this._colors3Arrays = {};
  59260. _this._colors4 = {};
  59261. _this._vectors2 = {};
  59262. _this._vectors3 = {};
  59263. _this._vectors4 = {};
  59264. _this._matrices = {};
  59265. _this._matrices3x3 = {};
  59266. _this._matrices2x2 = {};
  59267. _this._vectors2Arrays = {};
  59268. _this._vectors3Arrays = {};
  59269. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59270. _this._shaderPath = shaderPath;
  59271. options.needAlphaBlending = options.needAlphaBlending || false;
  59272. options.needAlphaTesting = options.needAlphaTesting || false;
  59273. options.attributes = options.attributes || ["position", "normal", "uv"];
  59274. options.uniforms = options.uniforms || ["worldViewProjection"];
  59275. options.uniformBuffers = options.uniformBuffers || [];
  59276. options.samplers = options.samplers || [];
  59277. options.defines = options.defines || [];
  59278. _this._options = options;
  59279. return _this;
  59280. }
  59281. ShaderMaterial.prototype.getClassName = function () {
  59282. return "ShaderMaterial";
  59283. };
  59284. ShaderMaterial.prototype.needAlphaBlending = function () {
  59285. return this._options.needAlphaBlending;
  59286. };
  59287. ShaderMaterial.prototype.needAlphaTesting = function () {
  59288. return this._options.needAlphaTesting;
  59289. };
  59290. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59291. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59292. this._options.uniforms.push(uniformName);
  59293. }
  59294. };
  59295. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59296. if (this._options.samplers.indexOf(name) === -1) {
  59297. this._options.samplers.push(name);
  59298. }
  59299. this._textures[name] = texture;
  59300. return this;
  59301. };
  59302. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59303. if (this._options.samplers.indexOf(name) === -1) {
  59304. this._options.samplers.push(name);
  59305. }
  59306. this._checkUniform(name);
  59307. this._textureArrays[name] = textures;
  59308. return this;
  59309. };
  59310. ShaderMaterial.prototype.setFloat = function (name, value) {
  59311. this._checkUniform(name);
  59312. this._floats[name] = value;
  59313. return this;
  59314. };
  59315. ShaderMaterial.prototype.setInt = function (name, value) {
  59316. this._checkUniform(name);
  59317. this._ints[name] = value;
  59318. return this;
  59319. };
  59320. ShaderMaterial.prototype.setFloats = function (name, value) {
  59321. this._checkUniform(name);
  59322. this._floatsArrays[name] = value;
  59323. return this;
  59324. };
  59325. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59326. this._checkUniform(name);
  59327. this._colors3[name] = value;
  59328. return this;
  59329. };
  59330. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59331. this._checkUniform(name);
  59332. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59333. color.toArray(arr, arr.length);
  59334. return arr;
  59335. }, []);
  59336. return this;
  59337. };
  59338. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59339. this._checkUniform(name);
  59340. this._colors4[name] = value;
  59341. return this;
  59342. };
  59343. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59344. this._checkUniform(name);
  59345. this._vectors2[name] = value;
  59346. return this;
  59347. };
  59348. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59349. this._checkUniform(name);
  59350. this._vectors3[name] = value;
  59351. return this;
  59352. };
  59353. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59354. this._checkUniform(name);
  59355. this._vectors4[name] = value;
  59356. return this;
  59357. };
  59358. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59359. this._checkUniform(name);
  59360. this._matrices[name] = value;
  59361. return this;
  59362. };
  59363. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59364. this._checkUniform(name);
  59365. this._matrices3x3[name] = value;
  59366. return this;
  59367. };
  59368. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59369. this._checkUniform(name);
  59370. this._matrices2x2[name] = value;
  59371. return this;
  59372. };
  59373. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59374. this._checkUniform(name);
  59375. this._vectors2Arrays[name] = value;
  59376. return this;
  59377. };
  59378. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59379. this._checkUniform(name);
  59380. this._vectors3Arrays[name] = value;
  59381. return this;
  59382. };
  59383. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59384. if (!mesh) {
  59385. return true;
  59386. }
  59387. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59388. return false;
  59389. }
  59390. return false;
  59391. };
  59392. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59393. var scene = this.getScene();
  59394. var engine = scene.getEngine();
  59395. if (!this.checkReadyOnEveryCall) {
  59396. if (this._renderId === scene.getRenderId()) {
  59397. if (this._checkCache(scene, mesh, useInstances)) {
  59398. return true;
  59399. }
  59400. }
  59401. }
  59402. // Instances
  59403. var defines = [];
  59404. var attribs = [];
  59405. var fallbacks = new BABYLON.EffectFallbacks();
  59406. if (useInstances) {
  59407. defines.push("#define INSTANCES");
  59408. }
  59409. for (var index = 0; index < this._options.defines.length; index++) {
  59410. defines.push(this._options.defines[index]);
  59411. }
  59412. for (var index = 0; index < this._options.attributes.length; index++) {
  59413. attribs.push(this._options.attributes[index]);
  59414. }
  59415. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59416. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59417. defines.push("#define VERTEXCOLOR");
  59418. }
  59419. // Bones
  59420. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59421. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59422. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59423. if (mesh.numBoneInfluencers > 4) {
  59424. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59425. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59426. }
  59427. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59428. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59429. fallbacks.addCPUSkinningFallback(0, mesh);
  59430. if (this._options.uniforms.indexOf("mBones") === -1) {
  59431. this._options.uniforms.push("mBones");
  59432. }
  59433. }
  59434. else {
  59435. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59436. }
  59437. // Textures
  59438. for (var name in this._textures) {
  59439. if (!this._textures[name].isReady()) {
  59440. return false;
  59441. }
  59442. }
  59443. // Alpha test
  59444. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59445. defines.push("#define ALPHATEST");
  59446. }
  59447. var previousEffect = this._effect;
  59448. var join = defines.join("\n");
  59449. this._effect = engine.createEffect(this._shaderPath, {
  59450. attributes: attribs,
  59451. uniformsNames: this._options.uniforms,
  59452. uniformBuffersNames: this._options.uniformBuffers,
  59453. samplers: this._options.samplers,
  59454. defines: join,
  59455. fallbacks: fallbacks,
  59456. onCompiled: this.onCompiled,
  59457. onError: this.onError
  59458. }, engine);
  59459. if (!this._effect.isReady()) {
  59460. return false;
  59461. }
  59462. if (previousEffect !== this._effect) {
  59463. scene.resetCachedMaterial();
  59464. }
  59465. this._renderId = scene.getRenderId();
  59466. return true;
  59467. };
  59468. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59469. var scene = this.getScene();
  59470. if (!this._effect) {
  59471. return;
  59472. }
  59473. if (this._options.uniforms.indexOf("world") !== -1) {
  59474. this._effect.setMatrix("world", world);
  59475. }
  59476. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59477. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59478. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59479. }
  59480. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59481. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59482. }
  59483. };
  59484. ShaderMaterial.prototype.bind = function (world, mesh) {
  59485. // Std values
  59486. this.bindOnlyWorldMatrix(world);
  59487. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59488. if (this._options.uniforms.indexOf("view") !== -1) {
  59489. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59490. }
  59491. if (this._options.uniforms.indexOf("projection") !== -1) {
  59492. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59493. }
  59494. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59495. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59496. }
  59497. // Bones
  59498. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59499. var name;
  59500. // Texture
  59501. for (name in this._textures) {
  59502. this._effect.setTexture(name, this._textures[name]);
  59503. }
  59504. // Texture arrays
  59505. for (name in this._textureArrays) {
  59506. this._effect.setTextureArray(name, this._textureArrays[name]);
  59507. }
  59508. // Int
  59509. for (name in this._ints) {
  59510. this._effect.setInt(name, this._ints[name]);
  59511. }
  59512. // Float
  59513. for (name in this._floats) {
  59514. this._effect.setFloat(name, this._floats[name]);
  59515. }
  59516. // Floats
  59517. for (name in this._floatsArrays) {
  59518. this._effect.setArray(name, this._floatsArrays[name]);
  59519. }
  59520. // Color3
  59521. for (name in this._colors3) {
  59522. this._effect.setColor3(name, this._colors3[name]);
  59523. }
  59524. for (name in this._colors3Arrays) {
  59525. this._effect.setArray3(name, this._colors3Arrays[name]);
  59526. }
  59527. // Color4
  59528. for (name in this._colors4) {
  59529. var color = this._colors4[name];
  59530. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59531. }
  59532. // Vector2
  59533. for (name in this._vectors2) {
  59534. this._effect.setVector2(name, this._vectors2[name]);
  59535. }
  59536. // Vector3
  59537. for (name in this._vectors3) {
  59538. this._effect.setVector3(name, this._vectors3[name]);
  59539. }
  59540. // Vector4
  59541. for (name in this._vectors4) {
  59542. this._effect.setVector4(name, this._vectors4[name]);
  59543. }
  59544. // Matrix
  59545. for (name in this._matrices) {
  59546. this._effect.setMatrix(name, this._matrices[name]);
  59547. }
  59548. // Matrix 3x3
  59549. for (name in this._matrices3x3) {
  59550. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59551. }
  59552. // Matrix 2x2
  59553. for (name in this._matrices2x2) {
  59554. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59555. }
  59556. // Vector2Array
  59557. for (name in this._vectors2Arrays) {
  59558. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59559. }
  59560. // Vector3Array
  59561. for (name in this._vectors3Arrays) {
  59562. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59563. }
  59564. }
  59565. this._afterBind(mesh);
  59566. };
  59567. ShaderMaterial.prototype.getActiveTextures = function () {
  59568. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59569. for (var name in this._textures) {
  59570. activeTextures.push(this._textures[name]);
  59571. }
  59572. for (var name in this._textureArrays) {
  59573. var array = this._textureArrays[name];
  59574. for (var index = 0; index < array.length; index++) {
  59575. activeTextures.push(array[index]);
  59576. }
  59577. }
  59578. return activeTextures;
  59579. };
  59580. ShaderMaterial.prototype.hasTexture = function (texture) {
  59581. if (_super.prototype.hasTexture.call(this, texture)) {
  59582. return true;
  59583. }
  59584. for (var name in this._textures) {
  59585. if (this._textures[name] === texture) {
  59586. return true;
  59587. }
  59588. }
  59589. for (var name in this._textureArrays) {
  59590. var array = this._textureArrays[name];
  59591. for (var index = 0; index < array.length; index++) {
  59592. if (array[index] === texture) {
  59593. return true;
  59594. }
  59595. }
  59596. }
  59597. return false;
  59598. };
  59599. ShaderMaterial.prototype.clone = function (name) {
  59600. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59601. return newShaderMaterial;
  59602. };
  59603. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59604. if (forceDisposeTextures) {
  59605. var name;
  59606. for (name in this._textures) {
  59607. this._textures[name].dispose();
  59608. }
  59609. for (name in this._textureArrays) {
  59610. var array = this._textureArrays[name];
  59611. for (var index = 0; index < array.length; index++) {
  59612. array[index].dispose();
  59613. }
  59614. }
  59615. }
  59616. this._textures = {};
  59617. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59618. };
  59619. ShaderMaterial.prototype.serialize = function () {
  59620. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59621. serializationObject.customType = "BABYLON.ShaderMaterial";
  59622. serializationObject.options = this._options;
  59623. serializationObject.shaderPath = this._shaderPath;
  59624. var name;
  59625. // Texture
  59626. serializationObject.textures = {};
  59627. for (name in this._textures) {
  59628. serializationObject.textures[name] = this._textures[name].serialize();
  59629. }
  59630. // Texture arrays
  59631. serializationObject.textureArrays = {};
  59632. for (name in this._textureArrays) {
  59633. serializationObject.textureArrays[name] = [];
  59634. var array = this._textureArrays[name];
  59635. for (var index = 0; index < array.length; index++) {
  59636. serializationObject.textureArrays[name].push(array[index].serialize());
  59637. }
  59638. }
  59639. // Float
  59640. serializationObject.floats = {};
  59641. for (name in this._floats) {
  59642. serializationObject.floats[name] = this._floats[name];
  59643. }
  59644. // Float s
  59645. serializationObject.FloatArrays = {};
  59646. for (name in this._floatsArrays) {
  59647. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59648. }
  59649. // Color3
  59650. serializationObject.colors3 = {};
  59651. for (name in this._colors3) {
  59652. serializationObject.colors3[name] = this._colors3[name].asArray();
  59653. }
  59654. // Color3 array
  59655. serializationObject.colors3Arrays = {};
  59656. for (name in this._colors3Arrays) {
  59657. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59658. }
  59659. // Color4
  59660. serializationObject.colors4 = {};
  59661. for (name in this._colors4) {
  59662. serializationObject.colors4[name] = this._colors4[name].asArray();
  59663. }
  59664. // Vector2
  59665. serializationObject.vectors2 = {};
  59666. for (name in this._vectors2) {
  59667. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59668. }
  59669. // Vector3
  59670. serializationObject.vectors3 = {};
  59671. for (name in this._vectors3) {
  59672. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59673. }
  59674. // Vector4
  59675. serializationObject.vectors4 = {};
  59676. for (name in this._vectors4) {
  59677. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59678. }
  59679. // Matrix
  59680. serializationObject.matrices = {};
  59681. for (name in this._matrices) {
  59682. serializationObject.matrices[name] = this._matrices[name].asArray();
  59683. }
  59684. // Matrix 3x3
  59685. serializationObject.matrices3x3 = {};
  59686. for (name in this._matrices3x3) {
  59687. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59688. }
  59689. // Matrix 2x2
  59690. serializationObject.matrices2x2 = {};
  59691. for (name in this._matrices2x2) {
  59692. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59693. }
  59694. // Vector2Array
  59695. serializationObject.vectors2Arrays = {};
  59696. for (name in this._vectors2Arrays) {
  59697. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59698. }
  59699. // Vector3Array
  59700. serializationObject.vectors3Arrays = {};
  59701. for (name in this._vectors3Arrays) {
  59702. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59703. }
  59704. return serializationObject;
  59705. };
  59706. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59707. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59708. var name;
  59709. // Texture
  59710. for (name in source.textures) {
  59711. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59712. }
  59713. // Texture arrays
  59714. for (name in source.textureArrays) {
  59715. var array = source.textureArrays[name];
  59716. var textureArray = new Array();
  59717. for (var index = 0; index < array.length; index++) {
  59718. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59719. }
  59720. material.setTextureArray(name, textureArray);
  59721. }
  59722. // Float
  59723. for (name in source.floats) {
  59724. material.setFloat(name, source.floats[name]);
  59725. }
  59726. // Float s
  59727. for (name in source.floatsArrays) {
  59728. material.setFloats(name, source.floatsArrays[name]);
  59729. }
  59730. // Color3
  59731. for (name in source.colors3) {
  59732. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59733. }
  59734. // Color3 arrays
  59735. for (name in source.colors3Arrays) {
  59736. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59737. if (i % 3 === 0) {
  59738. arr.push([num]);
  59739. }
  59740. else {
  59741. arr[arr.length - 1].push(num);
  59742. }
  59743. return arr;
  59744. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59745. material.setColor3Array(name, colors);
  59746. }
  59747. // Color4
  59748. for (name in source.colors4) {
  59749. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59750. }
  59751. // Vector2
  59752. for (name in source.vectors2) {
  59753. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59754. }
  59755. // Vector3
  59756. for (name in source.vectors3) {
  59757. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59758. }
  59759. // Vector4
  59760. for (name in source.vectors4) {
  59761. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59762. }
  59763. // Matrix
  59764. for (name in source.matrices) {
  59765. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59766. }
  59767. // Matrix 3x3
  59768. for (name in source.matrices3x3) {
  59769. material.setMatrix3x3(name, source.matrices3x3[name]);
  59770. }
  59771. // Matrix 2x2
  59772. for (name in source.matrices2x2) {
  59773. material.setMatrix2x2(name, source.matrices2x2[name]);
  59774. }
  59775. // Vector2Array
  59776. for (name in source.vectors2Arrays) {
  59777. material.setArray2(name, source.vectors2Arrays[name]);
  59778. }
  59779. // Vector3Array
  59780. for (name in source.vectors3Arrays) {
  59781. material.setArray3(name, source.vectors3Arrays[name]);
  59782. }
  59783. return material;
  59784. };
  59785. return ShaderMaterial;
  59786. }(BABYLON.Material));
  59787. BABYLON.ShaderMaterial = ShaderMaterial;
  59788. })(BABYLON || (BABYLON = {}));
  59789. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59790. var BABYLON;
  59791. (function (BABYLON) {
  59792. var GroundMesh = /** @class */ (function (_super) {
  59793. __extends(GroundMesh, _super);
  59794. function GroundMesh(name, scene) {
  59795. var _this = _super.call(this, name, scene) || this;
  59796. _this.generateOctree = false;
  59797. return _this;
  59798. }
  59799. GroundMesh.prototype.getClassName = function () {
  59800. return "GroundMesh";
  59801. };
  59802. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59803. get: function () {
  59804. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59805. },
  59806. enumerable: true,
  59807. configurable: true
  59808. });
  59809. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59810. get: function () {
  59811. return this._subdivisionsX;
  59812. },
  59813. enumerable: true,
  59814. configurable: true
  59815. });
  59816. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59817. get: function () {
  59818. return this._subdivisionsY;
  59819. },
  59820. enumerable: true,
  59821. configurable: true
  59822. });
  59823. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59824. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59825. this._subdivisionsX = chunksCount;
  59826. this._subdivisionsY = chunksCount;
  59827. this.subdivide(chunksCount);
  59828. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59829. };
  59830. /**
  59831. * Returns a height (y) value in the Worl system :
  59832. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59833. * Returns the ground y position if (x, z) are outside the ground surface.
  59834. */
  59835. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59836. var world = this.getWorldMatrix();
  59837. var invMat = BABYLON.Tmp.Matrix[5];
  59838. world.invertToRef(invMat);
  59839. var tmpVect = BABYLON.Tmp.Vector3[8];
  59840. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59841. x = tmpVect.x;
  59842. z = tmpVect.z;
  59843. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59844. return this.position.y;
  59845. }
  59846. if (!this._heightQuads || this._heightQuads.length == 0) {
  59847. this._initHeightQuads();
  59848. this._computeHeightQuads();
  59849. }
  59850. var facet = this._getFacetAt(x, z);
  59851. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59852. // return y in the World system
  59853. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59854. return tmpVect.y;
  59855. };
  59856. /**
  59857. * Returns a normalized vector (Vector3) orthogonal to the ground
  59858. * at the ground coordinates (x, z) expressed in the World system.
  59859. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59860. */
  59861. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59862. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59863. this.getNormalAtCoordinatesToRef(x, z, normal);
  59864. return normal;
  59865. };
  59866. /**
  59867. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59868. * at the ground coordinates (x, z) expressed in the World system.
  59869. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59870. * Returns the GroundMesh.
  59871. */
  59872. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59873. var world = this.getWorldMatrix();
  59874. var tmpMat = BABYLON.Tmp.Matrix[5];
  59875. world.invertToRef(tmpMat);
  59876. var tmpVect = BABYLON.Tmp.Vector3[8];
  59877. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59878. x = tmpVect.x;
  59879. z = tmpVect.z;
  59880. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59881. return this;
  59882. }
  59883. if (!this._heightQuads || this._heightQuads.length == 0) {
  59884. this._initHeightQuads();
  59885. this._computeHeightQuads();
  59886. }
  59887. var facet = this._getFacetAt(x, z);
  59888. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59889. return this;
  59890. };
  59891. /**
  59892. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59893. * if the ground has been updated.
  59894. * This can be used in the render loop.
  59895. * Returns the GroundMesh.
  59896. */
  59897. GroundMesh.prototype.updateCoordinateHeights = function () {
  59898. if (!this._heightQuads || this._heightQuads.length == 0) {
  59899. this._initHeightQuads();
  59900. }
  59901. this._computeHeightQuads();
  59902. return this;
  59903. };
  59904. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59905. GroundMesh.prototype._getFacetAt = function (x, z) {
  59906. // retrieve col and row from x, z coordinates in the ground local system
  59907. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59908. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59909. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59910. var facet;
  59911. if (z < quad.slope.x * x + quad.slope.y) {
  59912. facet = quad.facet1;
  59913. }
  59914. else {
  59915. facet = quad.facet2;
  59916. }
  59917. return facet;
  59918. };
  59919. // Creates and populates the heightMap array with "facet" elements :
  59920. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59921. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59922. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59923. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59924. // Returns the GroundMesh.
  59925. GroundMesh.prototype._initHeightQuads = function () {
  59926. var subdivisionsX = this._subdivisionsX;
  59927. var subdivisionsY = this._subdivisionsY;
  59928. this._heightQuads = new Array();
  59929. for (var row = 0; row < subdivisionsY; row++) {
  59930. for (var col = 0; col < subdivisionsX; col++) {
  59931. 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) };
  59932. this._heightQuads[row * subdivisionsX + col] = quad;
  59933. }
  59934. }
  59935. return this;
  59936. };
  59937. // Compute each quad element values and update the the heightMap array :
  59938. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59939. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59940. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59941. // Returns the GroundMesh.
  59942. GroundMesh.prototype._computeHeightQuads = function () {
  59943. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59944. if (!positions) {
  59945. return this;
  59946. }
  59947. var v1 = BABYLON.Tmp.Vector3[3];
  59948. var v2 = BABYLON.Tmp.Vector3[2];
  59949. var v3 = BABYLON.Tmp.Vector3[1];
  59950. var v4 = BABYLON.Tmp.Vector3[0];
  59951. var v1v2 = BABYLON.Tmp.Vector3[4];
  59952. var v1v3 = BABYLON.Tmp.Vector3[5];
  59953. var v1v4 = BABYLON.Tmp.Vector3[6];
  59954. var norm1 = BABYLON.Tmp.Vector3[7];
  59955. var norm2 = BABYLON.Tmp.Vector3[8];
  59956. var i = 0;
  59957. var j = 0;
  59958. var k = 0;
  59959. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59960. var h = 0;
  59961. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59962. var d2 = 0;
  59963. var subdivisionsX = this._subdivisionsX;
  59964. var subdivisionsY = this._subdivisionsY;
  59965. for (var row = 0; row < subdivisionsY; row++) {
  59966. for (var col = 0; col < subdivisionsX; col++) {
  59967. i = col * 3;
  59968. j = row * (subdivisionsX + 1) * 3;
  59969. k = (row + 1) * (subdivisionsX + 1) * 3;
  59970. v1.x = positions[j + i];
  59971. v1.y = positions[j + i + 1];
  59972. v1.z = positions[j + i + 2];
  59973. v2.x = positions[j + i + 3];
  59974. v2.y = positions[j + i + 4];
  59975. v2.z = positions[j + i + 5];
  59976. v3.x = positions[k + i];
  59977. v3.y = positions[k + i + 1];
  59978. v3.z = positions[k + i + 2];
  59979. v4.x = positions[k + i + 3];
  59980. v4.y = positions[k + i + 4];
  59981. v4.z = positions[k + i + 5];
  59982. // 2D slope V1V4
  59983. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59984. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59985. // facet equations :
  59986. // we compute each facet normal vector
  59987. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59988. // we compute the value d by applying the equation to v1 which belongs to the plane
  59989. // then we store the facet equation in a Vector4
  59990. v2.subtractToRef(v1, v1v2);
  59991. v3.subtractToRef(v1, v1v3);
  59992. v4.subtractToRef(v1, v1v4);
  59993. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59994. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59995. norm1.normalize();
  59996. norm2.normalize();
  59997. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59998. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59999. var quad = this._heightQuads[row * subdivisionsX + col];
  60000. quad.slope.copyFromFloats(cd, h);
  60001. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60002. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60003. }
  60004. }
  60005. return this;
  60006. };
  60007. GroundMesh.prototype.serialize = function (serializationObject) {
  60008. _super.prototype.serialize.call(this, serializationObject);
  60009. serializationObject.subdivisionsX = this._subdivisionsX;
  60010. serializationObject.subdivisionsY = this._subdivisionsY;
  60011. serializationObject.minX = this._minX;
  60012. serializationObject.maxX = this._maxX;
  60013. serializationObject.minZ = this._minZ;
  60014. serializationObject.maxZ = this._maxZ;
  60015. serializationObject.width = this._width;
  60016. serializationObject.height = this._height;
  60017. };
  60018. GroundMesh.Parse = function (parsedMesh, scene) {
  60019. var result = new GroundMesh(parsedMesh.name, scene);
  60020. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60021. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60022. result._minX = parsedMesh.minX;
  60023. result._maxX = parsedMesh.maxX;
  60024. result._minZ = parsedMesh.minZ;
  60025. result._maxZ = parsedMesh.maxZ;
  60026. result._width = parsedMesh.width;
  60027. result._height = parsedMesh.height;
  60028. return result;
  60029. };
  60030. return GroundMesh;
  60031. }(BABYLON.Mesh));
  60032. BABYLON.GroundMesh = GroundMesh;
  60033. })(BABYLON || (BABYLON = {}));
  60034. //# sourceMappingURL=babylon.groundMesh.js.map
  60035. var BABYLON;
  60036. (function (BABYLON) {
  60037. /**
  60038. * Creates an instance based on a source mesh.
  60039. */
  60040. var InstancedMesh = /** @class */ (function (_super) {
  60041. __extends(InstancedMesh, _super);
  60042. function InstancedMesh(name, source) {
  60043. var _this = _super.call(this, name, source.getScene()) || this;
  60044. source.instances.push(_this);
  60045. _this._sourceMesh = source;
  60046. _this.position.copyFrom(source.position);
  60047. _this.rotation.copyFrom(source.rotation);
  60048. _this.scaling.copyFrom(source.scaling);
  60049. if (source.rotationQuaternion) {
  60050. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60051. }
  60052. _this.infiniteDistance = source.infiniteDistance;
  60053. _this.setPivotMatrix(source.getPivotMatrix());
  60054. _this.refreshBoundingInfo();
  60055. _this._syncSubMeshes();
  60056. return _this;
  60057. }
  60058. /**
  60059. * Returns the string "InstancedMesh".
  60060. */
  60061. InstancedMesh.prototype.getClassName = function () {
  60062. return "InstancedMesh";
  60063. };
  60064. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60065. // Methods
  60066. get: function () {
  60067. return this._sourceMesh.receiveShadows;
  60068. },
  60069. enumerable: true,
  60070. configurable: true
  60071. });
  60072. Object.defineProperty(InstancedMesh.prototype, "material", {
  60073. get: function () {
  60074. return this._sourceMesh.material;
  60075. },
  60076. enumerable: true,
  60077. configurable: true
  60078. });
  60079. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60080. get: function () {
  60081. return this._sourceMesh.visibility;
  60082. },
  60083. enumerable: true,
  60084. configurable: true
  60085. });
  60086. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60087. get: function () {
  60088. return this._sourceMesh.skeleton;
  60089. },
  60090. enumerable: true,
  60091. configurable: true
  60092. });
  60093. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60094. get: function () {
  60095. return this._sourceMesh.renderingGroupId;
  60096. },
  60097. set: function (value) {
  60098. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60099. return;
  60100. }
  60101. //no-op with warning
  60102. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60103. },
  60104. enumerable: true,
  60105. configurable: true
  60106. });
  60107. /**
  60108. * Returns the total number of vertices (integer).
  60109. */
  60110. InstancedMesh.prototype.getTotalVertices = function () {
  60111. return this._sourceMesh.getTotalVertices();
  60112. };
  60113. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60114. get: function () {
  60115. return this._sourceMesh;
  60116. },
  60117. enumerable: true,
  60118. configurable: true
  60119. });
  60120. /**
  60121. * Is this node ready to be used/rendered
  60122. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60123. * @return {boolean} is it ready
  60124. */
  60125. InstancedMesh.prototype.isReady = function (completeCheck) {
  60126. if (completeCheck === void 0) { completeCheck = false; }
  60127. return this._sourceMesh.isReady(completeCheck, true);
  60128. };
  60129. /**
  60130. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60131. */
  60132. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60133. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60134. };
  60135. /**
  60136. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60137. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60138. * The `data` are either a numeric array either a Float32Array.
  60139. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60140. * 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).
  60141. * Note that a new underlying VertexBuffer object is created each call.
  60142. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60143. *
  60144. * Possible `kind` values :
  60145. * - BABYLON.VertexBuffer.PositionKind
  60146. * - BABYLON.VertexBuffer.UVKind
  60147. * - BABYLON.VertexBuffer.UV2Kind
  60148. * - BABYLON.VertexBuffer.UV3Kind
  60149. * - BABYLON.VertexBuffer.UV4Kind
  60150. * - BABYLON.VertexBuffer.UV5Kind
  60151. * - BABYLON.VertexBuffer.UV6Kind
  60152. * - BABYLON.VertexBuffer.ColorKind
  60153. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60154. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60155. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60156. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60157. *
  60158. * Returns the Mesh.
  60159. */
  60160. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60161. if (this.sourceMesh) {
  60162. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60163. }
  60164. return this.sourceMesh;
  60165. };
  60166. /**
  60167. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60168. * If the mesh has no geometry, it is simply returned as it is.
  60169. * The `data` are either a numeric array either a Float32Array.
  60170. * No new underlying VertexBuffer object is created.
  60171. * 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.
  60172. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60173. *
  60174. * Possible `kind` values :
  60175. * - BABYLON.VertexBuffer.PositionKind
  60176. * - BABYLON.VertexBuffer.UVKind
  60177. * - BABYLON.VertexBuffer.UV2Kind
  60178. * - BABYLON.VertexBuffer.UV3Kind
  60179. * - BABYLON.VertexBuffer.UV4Kind
  60180. * - BABYLON.VertexBuffer.UV5Kind
  60181. * - BABYLON.VertexBuffer.UV6Kind
  60182. * - BABYLON.VertexBuffer.ColorKind
  60183. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60184. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60185. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60186. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60187. *
  60188. * Returns the Mesh.
  60189. */
  60190. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60191. if (this.sourceMesh) {
  60192. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60193. }
  60194. return this.sourceMesh;
  60195. };
  60196. /**
  60197. * Sets the mesh indices.
  60198. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60199. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60200. * This method creates a new index buffer each call.
  60201. * Returns the Mesh.
  60202. */
  60203. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60204. if (totalVertices === void 0) { totalVertices = null; }
  60205. if (this.sourceMesh) {
  60206. this.sourceMesh.setIndices(indices, totalVertices);
  60207. }
  60208. return this.sourceMesh;
  60209. };
  60210. /**
  60211. * Boolean : True if the mesh owns the requested kind of data.
  60212. */
  60213. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60214. return this._sourceMesh.isVerticesDataPresent(kind);
  60215. };
  60216. /**
  60217. * Returns an array of indices (IndicesArray).
  60218. */
  60219. InstancedMesh.prototype.getIndices = function () {
  60220. return this._sourceMesh.getIndices();
  60221. };
  60222. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60223. get: function () {
  60224. return this._sourceMesh._positions;
  60225. },
  60226. enumerable: true,
  60227. configurable: true
  60228. });
  60229. /**
  60230. * Sets a new updated BoundingInfo to the mesh.
  60231. * Returns the mesh.
  60232. */
  60233. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60234. var meshBB = this._sourceMesh.getBoundingInfo();
  60235. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60236. this._updateBoundingInfo();
  60237. return this;
  60238. };
  60239. InstancedMesh.prototype._preActivate = function () {
  60240. if (this._currentLOD) {
  60241. this._currentLOD._preActivate();
  60242. }
  60243. return this;
  60244. };
  60245. InstancedMesh.prototype._activate = function (renderId) {
  60246. if (this._currentLOD) {
  60247. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60248. }
  60249. return this;
  60250. };
  60251. /**
  60252. * Returns the current associated LOD AbstractMesh.
  60253. */
  60254. InstancedMesh.prototype.getLOD = function (camera) {
  60255. if (!camera) {
  60256. return this;
  60257. }
  60258. var boundingInfo = this.getBoundingInfo();
  60259. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60260. if (this._currentLOD === this.sourceMesh) {
  60261. return this;
  60262. }
  60263. return this._currentLOD;
  60264. };
  60265. InstancedMesh.prototype._syncSubMeshes = function () {
  60266. this.releaseSubMeshes();
  60267. if (this._sourceMesh.subMeshes) {
  60268. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60269. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60270. }
  60271. }
  60272. return this;
  60273. };
  60274. InstancedMesh.prototype._generatePointsArray = function () {
  60275. return this._sourceMesh._generatePointsArray();
  60276. };
  60277. /**
  60278. * Creates a new InstancedMesh from the current mesh.
  60279. * - name (string) : the cloned mesh name
  60280. * - newParent (optional Node) : the optional Node to parent the clone to.
  60281. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60282. *
  60283. * Returns the clone.
  60284. */
  60285. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60286. var result = this._sourceMesh.createInstance(name);
  60287. // Deep copy
  60288. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60289. // Bounding info
  60290. this.refreshBoundingInfo();
  60291. // Parent
  60292. if (newParent) {
  60293. result.parent = newParent;
  60294. }
  60295. if (!doNotCloneChildren) {
  60296. // Children
  60297. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60298. var mesh = this.getScene().meshes[index];
  60299. if (mesh.parent === this) {
  60300. mesh.clone(mesh.name, result);
  60301. }
  60302. }
  60303. }
  60304. result.computeWorldMatrix(true);
  60305. return result;
  60306. };
  60307. /**
  60308. * Disposes the InstancedMesh.
  60309. * Returns nothing.
  60310. */
  60311. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60312. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60313. // Remove from mesh
  60314. var index = this._sourceMesh.instances.indexOf(this);
  60315. this._sourceMesh.instances.splice(index, 1);
  60316. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60317. };
  60318. return InstancedMesh;
  60319. }(BABYLON.AbstractMesh));
  60320. BABYLON.InstancedMesh = InstancedMesh;
  60321. })(BABYLON || (BABYLON = {}));
  60322. //# sourceMappingURL=babylon.instancedMesh.js.map
  60323. var BABYLON;
  60324. (function (BABYLON) {
  60325. var LinesMesh = /** @class */ (function (_super) {
  60326. __extends(LinesMesh, _super);
  60327. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60328. if (scene === void 0) { scene = null; }
  60329. if (parent === void 0) { parent = null; }
  60330. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60331. _this.useVertexColor = useVertexColor;
  60332. _this.useVertexAlpha = useVertexAlpha;
  60333. _this.color = new BABYLON.Color3(1, 1, 1);
  60334. _this.alpha = 1;
  60335. if (source) {
  60336. _this.color = source.color.clone();
  60337. _this.alpha = source.alpha;
  60338. _this.useVertexColor = source.useVertexColor;
  60339. _this.useVertexAlpha = source.useVertexAlpha;
  60340. }
  60341. _this._intersectionThreshold = 0.1;
  60342. var defines = [];
  60343. var options = {
  60344. attributes: [BABYLON.VertexBuffer.PositionKind],
  60345. uniforms: ["world", "viewProjection"],
  60346. needAlphaBlending: true,
  60347. defines: defines
  60348. };
  60349. if (useVertexAlpha === false) {
  60350. options.needAlphaBlending = false;
  60351. }
  60352. if (!useVertexColor) {
  60353. options.uniforms.push("color");
  60354. }
  60355. else {
  60356. options.defines.push("#define VERTEXCOLOR");
  60357. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60358. }
  60359. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60360. return _this;
  60361. }
  60362. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60363. /**
  60364. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60365. * This margin is expressed in world space coordinates, so its value may vary.
  60366. * Default value is 0.1
  60367. * @returns the intersection Threshold value.
  60368. */
  60369. get: function () {
  60370. return this._intersectionThreshold;
  60371. },
  60372. /**
  60373. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60374. * This margin is expressed in world space coordinates, so its value may vary.
  60375. * @param value the new threshold to apply
  60376. */
  60377. set: function (value) {
  60378. if (this._intersectionThreshold === value) {
  60379. return;
  60380. }
  60381. this._intersectionThreshold = value;
  60382. if (this.geometry) {
  60383. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60384. }
  60385. },
  60386. enumerable: true,
  60387. configurable: true
  60388. });
  60389. /**
  60390. * Returns the string "LineMesh"
  60391. */
  60392. LinesMesh.prototype.getClassName = function () {
  60393. return "LinesMesh";
  60394. };
  60395. Object.defineProperty(LinesMesh.prototype, "material", {
  60396. get: function () {
  60397. return this._colorShader;
  60398. },
  60399. set: function (value) {
  60400. // Do nothing
  60401. },
  60402. enumerable: true,
  60403. configurable: true
  60404. });
  60405. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60406. get: function () {
  60407. return false;
  60408. },
  60409. enumerable: true,
  60410. configurable: true
  60411. });
  60412. LinesMesh.prototype.createInstance = function (name) {
  60413. throw new Error("LinesMeshes do not support createInstance.");
  60414. };
  60415. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60416. if (!this._geometry) {
  60417. return this;
  60418. }
  60419. // VBOs
  60420. this._geometry._bind(this._colorShader.getEffect());
  60421. // Color
  60422. if (!this.useVertexColor) {
  60423. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60424. }
  60425. return this;
  60426. };
  60427. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60428. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60429. return this;
  60430. }
  60431. var engine = this.getScene().getEngine();
  60432. // Draw order
  60433. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60434. return this;
  60435. };
  60436. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60437. this._colorShader.dispose();
  60438. _super.prototype.dispose.call(this, doNotRecurse);
  60439. };
  60440. /**
  60441. * Returns a new LineMesh object cloned from the current one.
  60442. */
  60443. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60444. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60445. };
  60446. return LinesMesh;
  60447. }(BABYLON.Mesh));
  60448. BABYLON.LinesMesh = LinesMesh;
  60449. })(BABYLON || (BABYLON = {}));
  60450. //# sourceMappingURL=babylon.linesMesh.js.map
  60451. var BABYLON;
  60452. (function (BABYLON) {
  60453. /**
  60454. * Class containing static functions to help procedurally build meshes
  60455. */
  60456. var MeshBuilder = /** @class */ (function () {
  60457. function MeshBuilder() {
  60458. }
  60459. MeshBuilder.updateSideOrientation = function (orientation) {
  60460. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60461. return BABYLON.Mesh.DOUBLESIDE;
  60462. }
  60463. if (orientation === undefined || orientation === null) {
  60464. return BABYLON.Mesh.FRONTSIDE;
  60465. }
  60466. return orientation;
  60467. };
  60468. /**
  60469. * Creates a box mesh
  60470. * * The parameter `size` sets the size (float) of each box side (default 1)
  60471. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60472. * * 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)
  60473. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60474. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60475. * * 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
  60476. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60477. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60478. * @param name defines the name of the mesh
  60479. * @param options defines the options used to create the mesh
  60480. * @param scene defines the hosting scene
  60481. * @returns the box mesh
  60482. */
  60483. MeshBuilder.CreateBox = function (name, options, scene) {
  60484. if (scene === void 0) { scene = null; }
  60485. var box = new BABYLON.Mesh(name, scene);
  60486. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60487. box._originalBuilderSideOrientation = options.sideOrientation;
  60488. var vertexData = BABYLON.VertexData.CreateBox(options);
  60489. vertexData.applyToMesh(box, options.updatable);
  60490. return box;
  60491. };
  60492. /**
  60493. * Creates a sphere mesh
  60494. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60495. * * 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`)
  60496. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60497. * * 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
  60498. * * 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)
  60499. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60500. * * 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
  60501. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60502. * @param name defines the name of the mesh
  60503. * @param options defines the options used to create the mesh
  60504. * @param scene defines the hosting scene
  60505. * @returns the sphere mesh
  60506. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60507. */
  60508. MeshBuilder.CreateSphere = function (name, options, scene) {
  60509. var sphere = new BABYLON.Mesh(name, scene);
  60510. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60511. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60512. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60513. vertexData.applyToMesh(sphere, options.updatable);
  60514. return sphere;
  60515. };
  60516. /**
  60517. * Creates a plane polygonal mesh. By default, this is a disc
  60518. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60519. * * 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
  60520. * * 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
  60521. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60522. * * 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
  60523. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60524. * @param name defines the name of the mesh
  60525. * @param options defines the options used to create the mesh
  60526. * @param scene defines the hosting scene
  60527. * @returns the plane polygonal mesh
  60528. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60529. */
  60530. MeshBuilder.CreateDisc = function (name, options, scene) {
  60531. if (scene === void 0) { scene = null; }
  60532. var disc = new BABYLON.Mesh(name, scene);
  60533. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60534. disc._originalBuilderSideOrientation = options.sideOrientation;
  60535. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60536. vertexData.applyToMesh(disc, options.updatable);
  60537. return disc;
  60538. };
  60539. /**
  60540. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60541. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60542. * * 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`)
  60543. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60544. * * 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
  60545. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60546. * * 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
  60547. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60548. * @param name defines the name of the mesh
  60549. * @param options defines the options used to create the mesh
  60550. * @param scene defines the hosting scene
  60551. * @returns the icosahedron mesh
  60552. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60553. */
  60554. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60555. var sphere = new BABYLON.Mesh(name, scene);
  60556. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60557. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60558. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60559. vertexData.applyToMesh(sphere, options.updatable);
  60560. return sphere;
  60561. };
  60562. ;
  60563. /**
  60564. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60565. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60566. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60567. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60568. * * 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
  60569. * * 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
  60570. * * 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
  60571. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60572. * * 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
  60573. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60574. * * 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
  60575. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60576. * * 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
  60577. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60578. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60579. * @param name defines the name of the mesh
  60580. * @param options defines the options used to create the mesh
  60581. * @param scene defines the hosting scene
  60582. * @returns the ribbon mesh
  60583. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60584. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60585. */
  60586. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60587. if (scene === void 0) { scene = null; }
  60588. var pathArray = options.pathArray;
  60589. var closeArray = options.closeArray;
  60590. var closePath = options.closePath;
  60591. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60592. var instance = options.instance;
  60593. var updatable = options.updatable;
  60594. if (instance) { // existing ribbon instance update
  60595. // positionFunction : ribbon case
  60596. // only pathArray and sideOrientation parameters are taken into account for positions update
  60597. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60598. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60599. var positionFunction = function (positions) {
  60600. var minlg = pathArray[0].length;
  60601. var i = 0;
  60602. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60603. for (var si = 1; si <= ns; si++) {
  60604. for (var p = 0; p < pathArray.length; p++) {
  60605. var path = pathArray[p];
  60606. var l = path.length;
  60607. minlg = (minlg < l) ? minlg : l;
  60608. var j = 0;
  60609. while (j < minlg) {
  60610. positions[i] = path[j].x;
  60611. positions[i + 1] = path[j].y;
  60612. positions[i + 2] = path[j].z;
  60613. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60614. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60615. }
  60616. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60617. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60618. }
  60619. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60620. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60621. }
  60622. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60623. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60624. }
  60625. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60626. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60627. }
  60628. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60629. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60630. }
  60631. j++;
  60632. i += 3;
  60633. }
  60634. if (instance._closePath) {
  60635. positions[i] = path[0].x;
  60636. positions[i + 1] = path[0].y;
  60637. positions[i + 2] = path[0].z;
  60638. i += 3;
  60639. }
  60640. }
  60641. }
  60642. };
  60643. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60644. positionFunction(positions);
  60645. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60646. instance._boundingInfo.update(instance._worldMatrix);
  60647. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60648. if (options.colors) {
  60649. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60650. for (var c = 0; c < options.colors.length; c++) {
  60651. colors[c * 4] = options.colors[c].r;
  60652. colors[c * 4 + 1] = options.colors[c].g;
  60653. colors[c * 4 + 2] = options.colors[c].b;
  60654. colors[c * 4 + 3] = options.colors[c].a;
  60655. }
  60656. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60657. }
  60658. if (options.uvs) {
  60659. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60660. for (var i = 0; i < options.uvs.length; i++) {
  60661. uvs[i * 2] = options.uvs[i].x;
  60662. uvs[i * 2 + 1] = options.uvs[i].y;
  60663. }
  60664. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60665. }
  60666. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60667. var indices = instance.getIndices();
  60668. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60669. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60670. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60671. if (instance._closePath) {
  60672. var indexFirst = 0;
  60673. var indexLast = 0;
  60674. for (var p = 0; p < pathArray.length; p++) {
  60675. indexFirst = instance._idx[p] * 3;
  60676. if (p + 1 < pathArray.length) {
  60677. indexLast = (instance._idx[p + 1] - 1) * 3;
  60678. }
  60679. else {
  60680. indexLast = normals.length - 3;
  60681. }
  60682. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60683. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60684. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60685. normals[indexLast] = normals[indexFirst];
  60686. normals[indexLast + 1] = normals[indexFirst + 1];
  60687. normals[indexLast + 2] = normals[indexFirst + 2];
  60688. }
  60689. }
  60690. if (!(instance.areNormalsFrozen)) {
  60691. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60692. }
  60693. }
  60694. return instance;
  60695. }
  60696. else { // new ribbon creation
  60697. var ribbon = new BABYLON.Mesh(name, scene);
  60698. ribbon._originalBuilderSideOrientation = sideOrientation;
  60699. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60700. if (closePath) {
  60701. ribbon._idx = vertexData._idx;
  60702. }
  60703. ribbon._closePath = closePath;
  60704. ribbon._closeArray = closeArray;
  60705. vertexData.applyToMesh(ribbon, updatable);
  60706. return ribbon;
  60707. }
  60708. };
  60709. /**
  60710. * Creates a cylinder or a cone mesh
  60711. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60712. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60713. * * 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.
  60714. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60715. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60716. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60717. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60718. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60719. * * 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).
  60720. * * 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
  60721. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60722. * * 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
  60723. * * 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.
  60724. * * If `enclose` is false, a ring surface is one element.
  60725. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60726. * * 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
  60727. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60728. * * 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
  60729. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60730. * @param name defines the name of the mesh
  60731. * @param options defines the options used to create the mesh
  60732. * @param scene defines the hosting scene
  60733. * @returns the cylinder mesh
  60734. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60735. */
  60736. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60737. var cylinder = new BABYLON.Mesh(name, scene);
  60738. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60739. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60740. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60741. vertexData.applyToMesh(cylinder, options.updatable);
  60742. return cylinder;
  60743. };
  60744. /**
  60745. * Creates a torus mesh
  60746. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60747. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60748. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60749. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60750. * * 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
  60751. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60752. * @param name defines the name of the mesh
  60753. * @param options defines the options used to create the mesh
  60754. * @param scene defines the hosting scene
  60755. * @returns the torus mesh
  60756. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60757. */
  60758. MeshBuilder.CreateTorus = function (name, options, scene) {
  60759. var torus = new BABYLON.Mesh(name, scene);
  60760. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60761. torus._originalBuilderSideOrientation = options.sideOrientation;
  60762. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60763. vertexData.applyToMesh(torus, options.updatable);
  60764. return torus;
  60765. };
  60766. /**
  60767. * Creates a torus knot mesh
  60768. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60769. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60770. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60771. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60772. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60773. * * 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
  60774. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60775. * @param name defines the name of the mesh
  60776. * @param options defines the options used to create the mesh
  60777. * @param scene defines the hosting scene
  60778. * @returns the torus knot mesh
  60779. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60780. */
  60781. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60782. var torusKnot = new BABYLON.Mesh(name, scene);
  60783. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60784. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60785. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60786. vertexData.applyToMesh(torusKnot, options.updatable);
  60787. return torusKnot;
  60788. };
  60789. /**
  60790. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60791. * * 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
  60792. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60793. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60794. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60795. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60796. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60797. * * 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
  60798. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60799. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60800. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60801. * @param name defines the name of the new line system
  60802. * @param options defines the options used to create the line system
  60803. * @param scene defines the hosting scene
  60804. * @returns a new line system mesh
  60805. */
  60806. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60807. var instance = options.instance;
  60808. var lines = options.lines;
  60809. var colors = options.colors;
  60810. if (instance) { // lines update
  60811. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60812. var vertexColor;
  60813. var lineColors;
  60814. if (colors) {
  60815. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60816. }
  60817. var i = 0;
  60818. var c = 0;
  60819. for (var l = 0; l < lines.length; l++) {
  60820. var points = lines[l];
  60821. for (var p = 0; p < points.length; p++) {
  60822. positions[i] = points[p].x;
  60823. positions[i + 1] = points[p].y;
  60824. positions[i + 2] = points[p].z;
  60825. if (colors && vertexColor) {
  60826. lineColors = colors[l];
  60827. vertexColor[c] = lineColors[p].r;
  60828. vertexColor[c + 1] = lineColors[p].g;
  60829. vertexColor[c + 2] = lineColors[p].b;
  60830. vertexColor[c + 3] = lineColors[p].a;
  60831. c += 4;
  60832. }
  60833. i += 3;
  60834. }
  60835. }
  60836. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60837. if (colors && vertexColor) {
  60838. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60839. }
  60840. return instance;
  60841. }
  60842. // line system creation
  60843. var useVertexColor = (colors) ? true : false;
  60844. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60845. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60846. vertexData.applyToMesh(lineSystem, options.updatable);
  60847. return lineSystem;
  60848. };
  60849. /**
  60850. * Creates a line mesh
  60851. * 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
  60852. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60853. * * The parameter `points` is an array successive Vector3
  60854. * * 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
  60855. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60856. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60857. * * When updating an instance, remember that only point positions can change, not the number of points
  60858. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60859. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60860. * @param name defines the name of the new line system
  60861. * @param options defines the options used to create the line system
  60862. * @param scene defines the hosting scene
  60863. * @returns a new line mesh
  60864. */
  60865. MeshBuilder.CreateLines = function (name, options, scene) {
  60866. if (scene === void 0) { scene = null; }
  60867. var colors = (options.colors) ? [options.colors] : null;
  60868. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60869. return lines;
  60870. };
  60871. /**
  60872. * Creates a dashed line mesh
  60873. * * 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
  60874. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60875. * * The parameter `points` is an array successive Vector3
  60876. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60877. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60878. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60879. * * 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
  60880. * * When updating an instance, remember that only point positions can change, not the number of points
  60881. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60882. * @param name defines the name of the mesh
  60883. * @param options defines the options used to create the mesh
  60884. * @param scene defines the hosting scene
  60885. * @returns the dashed line mesh
  60886. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60887. */
  60888. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60889. if (scene === void 0) { scene = null; }
  60890. var points = options.points;
  60891. var instance = options.instance;
  60892. var gapSize = options.gapSize || 1;
  60893. var dashSize = options.dashSize || 3;
  60894. if (instance) { // dashed lines update
  60895. var positionFunction = function (positions) {
  60896. var curvect = BABYLON.Vector3.Zero();
  60897. var nbSeg = positions.length / 6;
  60898. var lg = 0;
  60899. var nb = 0;
  60900. var shft = 0;
  60901. var dashshft = 0;
  60902. var curshft = 0;
  60903. var p = 0;
  60904. var i = 0;
  60905. var j = 0;
  60906. for (i = 0; i < points.length - 1; i++) {
  60907. points[i + 1].subtractToRef(points[i], curvect);
  60908. lg += curvect.length();
  60909. }
  60910. shft = lg / nbSeg;
  60911. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60912. for (i = 0; i < points.length - 1; i++) {
  60913. points[i + 1].subtractToRef(points[i], curvect);
  60914. nb = Math.floor(curvect.length() / shft);
  60915. curvect.normalize();
  60916. j = 0;
  60917. while (j < nb && p < positions.length) {
  60918. curshft = shft * j;
  60919. positions[p] = points[i].x + curshft * curvect.x;
  60920. positions[p + 1] = points[i].y + curshft * curvect.y;
  60921. positions[p + 2] = points[i].z + curshft * curvect.z;
  60922. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60923. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60924. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60925. p += 6;
  60926. j++;
  60927. }
  60928. }
  60929. while (p < positions.length) {
  60930. positions[p] = points[i].x;
  60931. positions[p + 1] = points[i].y;
  60932. positions[p + 2] = points[i].z;
  60933. p += 3;
  60934. }
  60935. };
  60936. instance.updateMeshPositions(positionFunction, false);
  60937. return instance;
  60938. }
  60939. // dashed lines creation
  60940. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60941. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60942. vertexData.applyToMesh(dashedLines, options.updatable);
  60943. dashedLines.dashSize = dashSize;
  60944. dashedLines.gapSize = gapSize;
  60945. return dashedLines;
  60946. };
  60947. /**
  60948. * 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.
  60949. * * 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.
  60950. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60951. * * 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.
  60952. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60953. * * 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
  60954. * * 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
  60955. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60956. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60957. * * 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
  60958. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  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 extruded shape mesh
  60964. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60965. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60966. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60967. */
  60968. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60969. if (scene === void 0) { scene = null; }
  60970. var path = options.path;
  60971. var shape = options.shape;
  60972. var scale = options.scale || 1;
  60973. var rotation = options.rotation || 0;
  60974. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60975. var updatable = options.updatable;
  60976. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60977. var instance = options.instance || null;
  60978. var invertUV = options.invertUV || false;
  60979. 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);
  60980. };
  60981. /**
  60982. * Creates an custom extruded shape mesh.
  60983. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60984. * * 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.
  60985. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60986. * * 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
  60987. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60988. * * 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
  60989. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60990. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60991. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60992. * * 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
  60993. * * 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
  60994. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60995. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60996. * * 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
  60997. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60998. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60999. * @param name defines the name of the mesh
  61000. * @param options defines the options used to create the mesh
  61001. * @param scene defines the hosting scene
  61002. * @returns the custom extruded shape mesh
  61003. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61004. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61005. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61006. */
  61007. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61008. var path = options.path;
  61009. var shape = options.shape;
  61010. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61011. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61012. var ribbonCloseArray = options.ribbonCloseArray || false;
  61013. var ribbonClosePath = options.ribbonClosePath || false;
  61014. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61015. var updatable = options.updatable;
  61016. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61017. var instance = options.instance;
  61018. var invertUV = options.invertUV || false;
  61019. 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);
  61020. };
  61021. /**
  61022. * Creates lathe mesh.
  61023. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61024. * * 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
  61025. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61026. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61027. * * 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
  61028. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61029. * * 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
  61030. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61031. * * 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
  61032. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61033. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61034. * @param name defines the name of the mesh
  61035. * @param options defines the options used to create the mesh
  61036. * @param scene defines the hosting scene
  61037. * @returns the lathe mesh
  61038. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61039. */
  61040. MeshBuilder.CreateLathe = function (name, options, scene) {
  61041. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61042. var closed = (options.closed === undefined) ? true : options.closed;
  61043. var shape = options.shape;
  61044. var radius = options.radius || 1;
  61045. var tessellation = options.tessellation || 64;
  61046. var updatable = options.updatable;
  61047. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61048. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61049. var pi2 = Math.PI * 2;
  61050. var paths = new Array();
  61051. var invertUV = options.invertUV || false;
  61052. var i = 0;
  61053. var p = 0;
  61054. var step = pi2 / tessellation * arc;
  61055. var rotated;
  61056. var path = new Array();
  61057. for (i = 0; i <= tessellation; i++) {
  61058. var path = [];
  61059. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61060. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61061. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61062. }
  61063. for (p = 0; p < shape.length; p++) {
  61064. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61065. path.push(rotated);
  61066. }
  61067. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61068. 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));
  61069. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61070. }
  61071. paths.push(path);
  61072. }
  61073. // lathe ribbon
  61074. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61075. return lathe;
  61076. };
  61077. /**
  61078. * Creates a plane mesh
  61079. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61080. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61081. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61082. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61083. * * 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
  61084. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61085. * @param name defines the name of the mesh
  61086. * @param options defines the options used to create the mesh
  61087. * @param scene defines the hosting scene
  61088. * @returns the plane mesh
  61089. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61090. */
  61091. MeshBuilder.CreatePlane = function (name, options, scene) {
  61092. var plane = new BABYLON.Mesh(name, scene);
  61093. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61094. plane._originalBuilderSideOrientation = options.sideOrientation;
  61095. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61096. vertexData.applyToMesh(plane, options.updatable);
  61097. if (options.sourcePlane) {
  61098. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61099. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61100. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61101. plane.rotate(vectorProduct, product);
  61102. }
  61103. return plane;
  61104. };
  61105. /**
  61106. * Creates a ground mesh
  61107. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61108. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61109. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61110. * @param name defines the name of the mesh
  61111. * @param options defines the options used to create the mesh
  61112. * @param scene defines the hosting scene
  61113. * @returns the ground mesh
  61114. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61115. */
  61116. MeshBuilder.CreateGround = function (name, options, scene) {
  61117. var ground = new BABYLON.GroundMesh(name, scene);
  61118. ground._setReady(false);
  61119. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61120. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61121. ground._width = options.width || 1;
  61122. ground._height = options.height || 1;
  61123. ground._maxX = ground._width / 2;
  61124. ground._maxZ = ground._height / 2;
  61125. ground._minX = -ground._maxX;
  61126. ground._minZ = -ground._maxZ;
  61127. var vertexData = BABYLON.VertexData.CreateGround(options);
  61128. vertexData.applyToMesh(ground, options.updatable);
  61129. ground._setReady(true);
  61130. return ground;
  61131. };
  61132. /**
  61133. * Creates a tiled ground mesh
  61134. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61135. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61136. * * 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
  61137. * * 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
  61138. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61139. * @param name defines the name of the mesh
  61140. * @param options defines the options used to create the mesh
  61141. * @param scene defines the hosting scene
  61142. * @returns the tiled ground mesh
  61143. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61144. */
  61145. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61146. var tiledGround = new BABYLON.Mesh(name, scene);
  61147. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61148. vertexData.applyToMesh(tiledGround, options.updatable);
  61149. return tiledGround;
  61150. };
  61151. /**
  61152. * Creates a ground mesh from a height map
  61153. * * The parameter `url` sets the URL of the height map image resource.
  61154. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61155. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61156. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61157. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61158. * * 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.
  61159. * * 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).
  61160. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61161. * @param name defines the name of the mesh
  61162. * @param url defines the url to the height map
  61163. * @param options defines the options used to create the mesh
  61164. * @param scene defines the hosting scene
  61165. * @returns the ground mesh
  61166. * @see http://doc.babylonjs.com/babylon101/height_map
  61167. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61168. */
  61169. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61170. var width = options.width || 10.0;
  61171. var height = options.height || 10.0;
  61172. var subdivisions = options.subdivisions || 1 | 0;
  61173. var minHeight = options.minHeight || 0.0;
  61174. var maxHeight = options.maxHeight || 1.0;
  61175. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61176. var updatable = options.updatable;
  61177. var onReady = options.onReady;
  61178. var ground = new BABYLON.GroundMesh(name, scene);
  61179. ground._subdivisionsX = subdivisions;
  61180. ground._subdivisionsY = subdivisions;
  61181. ground._width = width;
  61182. ground._height = height;
  61183. ground._maxX = ground._width / 2.0;
  61184. ground._maxZ = ground._height / 2.0;
  61185. ground._minX = -ground._maxX;
  61186. ground._minZ = -ground._maxZ;
  61187. ground._setReady(false);
  61188. var onload = function (img) {
  61189. // Getting height map data
  61190. var canvas = document.createElement("canvas");
  61191. var context = canvas.getContext("2d");
  61192. if (!context) {
  61193. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61194. }
  61195. if (scene.isDisposed) {
  61196. return;
  61197. }
  61198. var bufferWidth = img.width;
  61199. var bufferHeight = img.height;
  61200. canvas.width = bufferWidth;
  61201. canvas.height = bufferHeight;
  61202. context.drawImage(img, 0, 0);
  61203. // Create VertexData from map data
  61204. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61205. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61206. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61207. width: width, height: height,
  61208. subdivisions: subdivisions,
  61209. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61210. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61211. });
  61212. vertexData.applyToMesh(ground, updatable);
  61213. //execute ready callback, if set
  61214. if (onReady) {
  61215. onReady(ground);
  61216. }
  61217. ground._setReady(true);
  61218. };
  61219. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61220. return ground;
  61221. };
  61222. /**
  61223. * Creates a polygon mesh
  61224. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61225. * * 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
  61226. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61227. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61228. * * 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)
  61229. * * Remember you can only change the shape positions, not their number when updating a polygon
  61230. * @param name defines the name of the mesh
  61231. * @param options defines the options used to create the mesh
  61232. * @param scene defines the hosting scene
  61233. * @returns the polygon mesh
  61234. */
  61235. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61236. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61237. var shape = options.shape;
  61238. var holes = options.holes || [];
  61239. var depth = options.depth || 0;
  61240. var contours = [];
  61241. var hole = [];
  61242. for (var i = 0; i < shape.length; i++) {
  61243. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61244. }
  61245. var epsilon = 0.00000001;
  61246. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61247. contours.pop();
  61248. }
  61249. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61250. for (var hNb = 0; hNb < holes.length; hNb++) {
  61251. hole = [];
  61252. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61253. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61254. }
  61255. polygonTriangulation.addHole(hole);
  61256. }
  61257. var polygon = polygonTriangulation.build(options.updatable, depth);
  61258. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61259. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61260. vertexData.applyToMesh(polygon, options.updatable);
  61261. return polygon;
  61262. };
  61263. ;
  61264. /**
  61265. * Creates an extruded polygon mesh, with depth in the Y direction.
  61266. * * 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)
  61267. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61268. * @param name defines the name of the mesh
  61269. * @param options defines the options used to create the mesh
  61270. * @param scene defines the hosting scene
  61271. * @returns the polygon mesh
  61272. */
  61273. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61274. return MeshBuilder.CreatePolygon(name, options, scene);
  61275. };
  61276. ;
  61277. /**
  61278. * Creates a tube mesh.
  61279. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61280. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61281. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61282. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61283. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61284. * * 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)
  61285. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61286. * * 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
  61287. * * 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
  61288. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61289. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61290. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61291. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61292. * @param name defines the name of the mesh
  61293. * @param options defines the options used to create the mesh
  61294. * @param scene defines the hosting scene
  61295. * @returns the tube mesh
  61296. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61297. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61298. */
  61299. MeshBuilder.CreateTube = function (name, options, scene) {
  61300. var path = options.path;
  61301. var instance = options.instance;
  61302. var radius = 1.0;
  61303. if (instance) {
  61304. radius = instance.radius;
  61305. }
  61306. if (options.radius !== undefined) {
  61307. radius = options.radius;
  61308. }
  61309. ;
  61310. var tessellation = options.tessellation || 64 | 0;
  61311. var radiusFunction = options.radiusFunction || null;
  61312. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61313. var invertUV = options.invertUV || false;
  61314. var updatable = options.updatable;
  61315. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61316. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61317. // tube geometry
  61318. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61319. var tangents = path3D.getTangents();
  61320. var normals = path3D.getNormals();
  61321. var distances = path3D.getDistances();
  61322. var pi2 = Math.PI * 2;
  61323. var step = pi2 / tessellation * arc;
  61324. var returnRadius = function () { return radius; };
  61325. var radiusFunctionFinal = radiusFunction || returnRadius;
  61326. var circlePath;
  61327. var rad;
  61328. var normal;
  61329. var rotated;
  61330. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61331. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61332. for (var i = 0; i < path.length; i++) {
  61333. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61334. circlePath = Array(); // current circle array
  61335. normal = normals[i]; // current normal
  61336. for (var t = 0; t < tessellation; t++) {
  61337. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61338. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61339. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61340. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61341. circlePath[t] = rotated;
  61342. }
  61343. circlePaths[index] = circlePath;
  61344. index++;
  61345. }
  61346. // cap
  61347. var capPath = function (nbPoints, pathIndex) {
  61348. var pointCap = Array();
  61349. for (var i = 0; i < nbPoints; i++) {
  61350. pointCap.push(path[pathIndex]);
  61351. }
  61352. return pointCap;
  61353. };
  61354. switch (cap) {
  61355. case BABYLON.Mesh.NO_CAP:
  61356. break;
  61357. case BABYLON.Mesh.CAP_START:
  61358. circlePaths[0] = capPath(tessellation, 0);
  61359. circlePaths[1] = circlePaths[2].slice(0);
  61360. break;
  61361. case BABYLON.Mesh.CAP_END:
  61362. circlePaths[index] = circlePaths[index - 1].slice(0);
  61363. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61364. break;
  61365. case BABYLON.Mesh.CAP_ALL:
  61366. circlePaths[0] = capPath(tessellation, 0);
  61367. circlePaths[1] = circlePaths[2].slice(0);
  61368. circlePaths[index] = circlePaths[index - 1].slice(0);
  61369. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61370. break;
  61371. default:
  61372. break;
  61373. }
  61374. return circlePaths;
  61375. };
  61376. var path3D;
  61377. var pathArray;
  61378. if (instance) { // tube update
  61379. var arc = options.arc || instance.arc;
  61380. path3D = (instance.path3D).update(path);
  61381. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61382. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61383. instance.path3D = path3D;
  61384. instance.pathArray = pathArray;
  61385. instance.arc = arc;
  61386. instance.radius = radius;
  61387. return instance;
  61388. }
  61389. // tube creation
  61390. path3D = new BABYLON.Path3D(path);
  61391. var newPathArray = new Array();
  61392. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61393. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61394. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61395. tube.pathArray = pathArray;
  61396. tube.path3D = path3D;
  61397. tube.tessellation = tessellation;
  61398. tube.cap = cap;
  61399. tube.arc = options.arc;
  61400. tube.radius = radius;
  61401. return tube;
  61402. };
  61403. /**
  61404. * Creates a polyhedron mesh
  61405. * * 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
  61406. * * The parameter `size` (positive float, default 1) sets the polygon size
  61407. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61408. * * 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`
  61409. * * 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
  61410. * * 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)`)
  61411. * * 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
  61412. * * 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
  61413. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61414. * * 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
  61415. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61416. * @param name defines the name of the mesh
  61417. * @param options defines the options used to create the mesh
  61418. * @param scene defines the hosting scene
  61419. * @returns the polyhedron mesh
  61420. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61421. */
  61422. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61423. var polyhedron = new BABYLON.Mesh(name, scene);
  61424. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61425. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61426. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61427. vertexData.applyToMesh(polyhedron, options.updatable);
  61428. return polyhedron;
  61429. };
  61430. /**
  61431. * Creates a decal mesh.
  61432. * 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
  61433. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61434. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61435. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61436. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61437. * @param name defines the name of the mesh
  61438. * @param sourceMesh defines the mesh where the decal must be applied
  61439. * @param options defines the options used to create the mesh
  61440. * @param scene defines the hosting scene
  61441. * @returns the decal mesh
  61442. * @see http://doc.babylonjs.com/how_to/decals
  61443. */
  61444. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61445. var indices = sourceMesh.getIndices();
  61446. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61447. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61448. var position = options.position || BABYLON.Vector3.Zero();
  61449. var normal = options.normal || BABYLON.Vector3.Up();
  61450. var size = options.size || BABYLON.Vector3.One();
  61451. var angle = options.angle || 0;
  61452. // Getting correct rotation
  61453. if (!normal) {
  61454. var target = new BABYLON.Vector3(0, 0, 1);
  61455. var camera = sourceMesh.getScene().activeCamera;
  61456. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61457. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61458. }
  61459. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61460. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61461. var pitch = Math.atan2(normal.y, len);
  61462. // Matrix
  61463. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61464. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61465. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61466. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61467. var vertexData = new BABYLON.VertexData();
  61468. vertexData.indices = [];
  61469. vertexData.positions = [];
  61470. vertexData.normals = [];
  61471. vertexData.uvs = [];
  61472. var currentVertexDataIndex = 0;
  61473. var extractDecalVector3 = function (indexId) {
  61474. var result = new BABYLON.PositionNormalVertex();
  61475. if (!indices || !positions || !normals) {
  61476. return result;
  61477. }
  61478. var vertexId = indices[indexId];
  61479. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61480. // Send vector to decal local world
  61481. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61482. // Get normal
  61483. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61484. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61485. return result;
  61486. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61487. var clip = function (vertices, axis) {
  61488. if (vertices.length === 0) {
  61489. return vertices;
  61490. }
  61491. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61492. var clipVertices = function (v0, v1) {
  61493. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61494. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61495. };
  61496. var result = new Array();
  61497. for (var index = 0; index < vertices.length; index += 3) {
  61498. var v1Out;
  61499. var v2Out;
  61500. var v3Out;
  61501. var total = 0;
  61502. var nV1 = null;
  61503. var nV2 = null;
  61504. var nV3 = null;
  61505. var nV4 = null;
  61506. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61507. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61508. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61509. v1Out = d1 > 0;
  61510. v2Out = d2 > 0;
  61511. v3Out = d3 > 0;
  61512. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61513. switch (total) {
  61514. case 0:
  61515. result.push(vertices[index]);
  61516. result.push(vertices[index + 1]);
  61517. result.push(vertices[index + 2]);
  61518. break;
  61519. case 1:
  61520. if (v1Out) {
  61521. nV1 = vertices[index + 1];
  61522. nV2 = vertices[index + 2];
  61523. nV3 = clipVertices(vertices[index], nV1);
  61524. nV4 = clipVertices(vertices[index], nV2);
  61525. }
  61526. if (v2Out) {
  61527. nV1 = vertices[index];
  61528. nV2 = vertices[index + 2];
  61529. nV3 = clipVertices(vertices[index + 1], nV1);
  61530. nV4 = clipVertices(vertices[index + 1], nV2);
  61531. result.push(nV3);
  61532. result.push(nV2.clone());
  61533. result.push(nV1.clone());
  61534. result.push(nV2.clone());
  61535. result.push(nV3.clone());
  61536. result.push(nV4);
  61537. break;
  61538. }
  61539. if (v3Out) {
  61540. nV1 = vertices[index];
  61541. nV2 = vertices[index + 1];
  61542. nV3 = clipVertices(vertices[index + 2], nV1);
  61543. nV4 = clipVertices(vertices[index + 2], nV2);
  61544. }
  61545. if (nV1 && nV2 && nV3 && nV4) {
  61546. result.push(nV1.clone());
  61547. result.push(nV2.clone());
  61548. result.push(nV3);
  61549. result.push(nV4);
  61550. result.push(nV3.clone());
  61551. result.push(nV2.clone());
  61552. }
  61553. break;
  61554. case 2:
  61555. if (!v1Out) {
  61556. nV1 = vertices[index].clone();
  61557. nV2 = clipVertices(nV1, vertices[index + 1]);
  61558. nV3 = clipVertices(nV1, vertices[index + 2]);
  61559. result.push(nV1);
  61560. result.push(nV2);
  61561. result.push(nV3);
  61562. }
  61563. if (!v2Out) {
  61564. nV1 = vertices[index + 1].clone();
  61565. nV2 = clipVertices(nV1, vertices[index + 2]);
  61566. nV3 = clipVertices(nV1, vertices[index]);
  61567. result.push(nV1);
  61568. result.push(nV2);
  61569. result.push(nV3);
  61570. }
  61571. if (!v3Out) {
  61572. nV1 = vertices[index + 2].clone();
  61573. nV2 = clipVertices(nV1, vertices[index]);
  61574. nV3 = clipVertices(nV1, vertices[index + 1]);
  61575. result.push(nV1);
  61576. result.push(nV2);
  61577. result.push(nV3);
  61578. }
  61579. break;
  61580. case 3:
  61581. break;
  61582. }
  61583. }
  61584. return result;
  61585. };
  61586. for (var index = 0; index < indices.length; index += 3) {
  61587. var faceVertices = new Array();
  61588. faceVertices.push(extractDecalVector3(index));
  61589. faceVertices.push(extractDecalVector3(index + 1));
  61590. faceVertices.push(extractDecalVector3(index + 2));
  61591. // Clip
  61592. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61593. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61594. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61595. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61596. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61597. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61598. if (faceVertices.length === 0) {
  61599. continue;
  61600. }
  61601. // Add UVs and get back to world
  61602. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61603. var vertex = faceVertices[vIndex];
  61604. //TODO check for Int32Array | Uint32Array | Uint16Array
  61605. vertexData.indices.push(currentVertexDataIndex);
  61606. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61607. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61608. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61609. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61610. currentVertexDataIndex++;
  61611. }
  61612. }
  61613. // Return mesh
  61614. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61615. vertexData.applyToMesh(decal);
  61616. decal.position = position.clone();
  61617. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61618. return decal;
  61619. };
  61620. // Privates
  61621. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61622. // extrusion geometry
  61623. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61624. var tangents = path3D.getTangents();
  61625. var normals = path3D.getNormals();
  61626. var binormals = path3D.getBinormals();
  61627. var distances = path3D.getDistances();
  61628. var angle = 0;
  61629. var returnScale = function () { return scale !== null ? scale : 1; };
  61630. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61631. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61632. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61633. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61634. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61635. for (var i = 0; i < curve.length; i++) {
  61636. var shapePath = new Array();
  61637. var angleStep = rotate(i, distances[i]);
  61638. var scaleRatio = scl(i, distances[i]);
  61639. for (var p = 0; p < shape.length; p++) {
  61640. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61641. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61642. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61643. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61644. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61645. shapePath[p] = rotated;
  61646. }
  61647. shapePaths[index] = shapePath;
  61648. angle += angleStep;
  61649. index++;
  61650. }
  61651. // cap
  61652. var capPath = function (shapePath) {
  61653. var pointCap = Array();
  61654. var barycenter = BABYLON.Vector3.Zero();
  61655. var i;
  61656. for (i = 0; i < shapePath.length; i++) {
  61657. barycenter.addInPlace(shapePath[i]);
  61658. }
  61659. barycenter.scaleInPlace(1.0 / shapePath.length);
  61660. for (i = 0; i < shapePath.length; i++) {
  61661. pointCap.push(barycenter);
  61662. }
  61663. return pointCap;
  61664. };
  61665. switch (cap) {
  61666. case BABYLON.Mesh.NO_CAP:
  61667. break;
  61668. case BABYLON.Mesh.CAP_START:
  61669. shapePaths[0] = capPath(shapePaths[2]);
  61670. shapePaths[1] = shapePaths[2];
  61671. break;
  61672. case BABYLON.Mesh.CAP_END:
  61673. shapePaths[index] = shapePaths[index - 1];
  61674. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61675. break;
  61676. case BABYLON.Mesh.CAP_ALL:
  61677. shapePaths[0] = capPath(shapePaths[2]);
  61678. shapePaths[1] = shapePaths[2];
  61679. shapePaths[index] = shapePaths[index - 1];
  61680. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61681. break;
  61682. default:
  61683. break;
  61684. }
  61685. return shapePaths;
  61686. };
  61687. var path3D;
  61688. var pathArray;
  61689. if (instance) { // instance update
  61690. path3D = (instance.path3D).update(curve);
  61691. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61692. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61693. return instance;
  61694. }
  61695. // extruded shape creation
  61696. path3D = new BABYLON.Path3D(curve);
  61697. var newShapePaths = new Array();
  61698. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61699. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61700. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61701. extrudedGeneric.pathArray = pathArray;
  61702. extrudedGeneric.path3D = path3D;
  61703. extrudedGeneric.cap = cap;
  61704. return extrudedGeneric;
  61705. };
  61706. return MeshBuilder;
  61707. }());
  61708. BABYLON.MeshBuilder = MeshBuilder;
  61709. })(BABYLON || (BABYLON = {}));
  61710. //# sourceMappingURL=babylon.meshBuilder.js.map
  61711. var BABYLON;
  61712. (function (BABYLON) {
  61713. /**
  61714. * Draco compression (https://google.github.io/draco/)
  61715. *
  61716. * This class wraps the Draco module.
  61717. *
  61718. * **Encoder**
  61719. *
  61720. * The encoder is not currently implemented.
  61721. *
  61722. * **Decoder**
  61723. *
  61724. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61725. *
  61726. * To update the configuration, use the following code:
  61727. * ```javascript
  61728. * BABYLON.DracoCompression.Configuration = {
  61729. * decoder: {
  61730. * wasmUrl: "<url to the WebAssembly library>",
  61731. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61732. * fallbackUrl: "<url to the fallback JavaScript library>",
  61733. * }
  61734. * };
  61735. * ```
  61736. *
  61737. * 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.
  61738. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61739. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61740. *
  61741. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61742. * ```javascript
  61743. * var dracoCompression = new BABYLON.DracoCompression();
  61744. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61745. * [BABYLON.VertexBuffer.PositionKind]: 0
  61746. * });
  61747. * ```
  61748. *
  61749. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61750. */
  61751. var DracoCompression = /** @class */ (function () {
  61752. /**
  61753. * Constructor
  61754. */
  61755. function DracoCompression() {
  61756. }
  61757. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61758. /**
  61759. * Returns true if the decoder is available.
  61760. */
  61761. get: function () {
  61762. if (typeof DracoDecoderModule !== "undefined") {
  61763. return true;
  61764. }
  61765. var decoder = DracoCompression.Configuration.decoder;
  61766. if (decoder) {
  61767. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61768. return true;
  61769. }
  61770. if (decoder.fallbackUrl) {
  61771. return true;
  61772. }
  61773. }
  61774. return false;
  61775. },
  61776. enumerable: true,
  61777. configurable: true
  61778. });
  61779. /**
  61780. * Stop all async operations and release resources.
  61781. */
  61782. DracoCompression.prototype.dispose = function () {
  61783. };
  61784. /**
  61785. * Decode Draco compressed mesh data to vertex data.
  61786. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61787. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61788. * @returns A promise that resolves with the decoded vertex data
  61789. */
  61790. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61791. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61792. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61793. var module = wrappedModule.module;
  61794. var vertexData = new BABYLON.VertexData();
  61795. var buffer = new module.DecoderBuffer();
  61796. buffer.Init(dataView, dataView.byteLength);
  61797. var decoder = new module.Decoder();
  61798. var geometry;
  61799. var status;
  61800. try {
  61801. var type = decoder.GetEncodedGeometryType(buffer);
  61802. switch (type) {
  61803. case module.TRIANGULAR_MESH:
  61804. geometry = new module.Mesh();
  61805. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61806. break;
  61807. case module.POINT_CLOUD:
  61808. geometry = new module.PointCloud();
  61809. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61810. break;
  61811. default:
  61812. throw new Error("Invalid geometry type " + type);
  61813. }
  61814. if (!status.ok() || !geometry.ptr) {
  61815. throw new Error(status.error_msg());
  61816. }
  61817. var numPoints = geometry.num_points();
  61818. if (type === module.TRIANGULAR_MESH) {
  61819. var numFaces = geometry.num_faces();
  61820. var faceIndices = new module.DracoInt32Array();
  61821. try {
  61822. var indices = new Uint32Array(numFaces * 3);
  61823. for (var i = 0; i < numFaces; i++) {
  61824. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61825. var offset = i * 3;
  61826. indices[offset + 0] = faceIndices.GetValue(0);
  61827. indices[offset + 1] = faceIndices.GetValue(1);
  61828. indices[offset + 2] = faceIndices.GetValue(2);
  61829. }
  61830. vertexData.indices = indices;
  61831. }
  61832. finally {
  61833. module.destroy(faceIndices);
  61834. }
  61835. }
  61836. for (var kind in attributes) {
  61837. var uniqueId = attributes[kind];
  61838. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61839. var dracoData = new module.DracoFloat32Array();
  61840. try {
  61841. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61842. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61843. for (var i = 0; i < babylonData.length; i++) {
  61844. babylonData[i] = dracoData.GetValue(i);
  61845. }
  61846. vertexData.set(babylonData, kind);
  61847. }
  61848. finally {
  61849. module.destroy(dracoData);
  61850. }
  61851. }
  61852. }
  61853. finally {
  61854. if (geometry) {
  61855. module.destroy(geometry);
  61856. }
  61857. module.destroy(decoder);
  61858. module.destroy(buffer);
  61859. }
  61860. return vertexData;
  61861. });
  61862. };
  61863. DracoCompression._GetDecoderModule = function () {
  61864. if (!DracoCompression._DecoderModulePromise) {
  61865. var promise = null;
  61866. var config_1 = {};
  61867. if (typeof DracoDecoderModule !== "undefined") {
  61868. promise = Promise.resolve();
  61869. }
  61870. else {
  61871. var decoder = DracoCompression.Configuration.decoder;
  61872. if (decoder) {
  61873. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61874. promise = Promise.all([
  61875. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61876. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61877. config_1.wasmBinary = data;
  61878. })
  61879. ]);
  61880. }
  61881. else if (decoder.fallbackUrl) {
  61882. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61883. }
  61884. }
  61885. }
  61886. if (!promise) {
  61887. throw new Error("Draco decoder module is not available");
  61888. }
  61889. DracoCompression._DecoderModulePromise = promise.then(function () {
  61890. return new Promise(function (resolve) {
  61891. config_1.onModuleLoaded = function (decoderModule) {
  61892. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61893. resolve({ module: decoderModule });
  61894. };
  61895. DracoDecoderModule(config_1);
  61896. });
  61897. });
  61898. }
  61899. return DracoCompression._DecoderModulePromise;
  61900. };
  61901. DracoCompression._LoadScriptAsync = function (url) {
  61902. return new Promise(function (resolve, reject) {
  61903. BABYLON.Tools.LoadScript(url, function () {
  61904. resolve();
  61905. }, function (message) {
  61906. reject(new Error(message));
  61907. });
  61908. });
  61909. };
  61910. DracoCompression._LoadFileAsync = function (url) {
  61911. return new Promise(function (resolve, reject) {
  61912. BABYLON.Tools.LoadFile(url, function (data) {
  61913. resolve(data);
  61914. }, undefined, undefined, true, function (request, exception) {
  61915. reject(exception);
  61916. });
  61917. });
  61918. };
  61919. /**
  61920. * The configuration. Defaults to the following urls:
  61921. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61922. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61923. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61924. */
  61925. DracoCompression.Configuration = {
  61926. decoder: {
  61927. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61928. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61929. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61930. }
  61931. };
  61932. return DracoCompression;
  61933. }());
  61934. BABYLON.DracoCompression = DracoCompression;
  61935. })(BABYLON || (BABYLON = {}));
  61936. //# sourceMappingURL=babylon.dracoCompression.js.map
  61937. var BABYLON;
  61938. (function (BABYLON) {
  61939. var AudioEngine = /** @class */ (function () {
  61940. function AudioEngine() {
  61941. this._audioContext = null;
  61942. this._audioContextInitialized = false;
  61943. this.canUseWebAudio = false;
  61944. this.WarnedWebAudioUnsupported = false;
  61945. this.unlocked = false;
  61946. this.isMP3supported = false;
  61947. this.isOGGsupported = false;
  61948. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61949. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61950. this.canUseWebAudio = true;
  61951. }
  61952. var audioElem = document.createElement('audio');
  61953. try {
  61954. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61955. this.isMP3supported = true;
  61956. }
  61957. }
  61958. catch (e) {
  61959. // protect error during capability check.
  61960. }
  61961. try {
  61962. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61963. this.isOGGsupported = true;
  61964. }
  61965. }
  61966. catch (e) {
  61967. // protect error during capability check.
  61968. }
  61969. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61970. this._unlockiOSaudio();
  61971. }
  61972. else {
  61973. this.unlocked = true;
  61974. }
  61975. }
  61976. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61977. get: function () {
  61978. if (!this._audioContextInitialized) {
  61979. this._initializeAudioContext();
  61980. }
  61981. return this._audioContext;
  61982. },
  61983. enumerable: true,
  61984. configurable: true
  61985. });
  61986. AudioEngine.prototype._unlockiOSaudio = function () {
  61987. var _this = this;
  61988. var unlockaudio = function () {
  61989. if (!_this.audioContext) {
  61990. return;
  61991. }
  61992. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61993. var source = _this.audioContext.createBufferSource();
  61994. source.buffer = buffer;
  61995. source.connect(_this.audioContext.destination);
  61996. source.start(0);
  61997. setTimeout(function () {
  61998. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61999. _this.unlocked = true;
  62000. window.removeEventListener('touchend', unlockaudio, false);
  62001. if (_this.onAudioUnlocked) {
  62002. _this.onAudioUnlocked();
  62003. }
  62004. }
  62005. }, 0);
  62006. };
  62007. window.addEventListener('touchend', unlockaudio, false);
  62008. };
  62009. AudioEngine.prototype._initializeAudioContext = function () {
  62010. try {
  62011. if (this.canUseWebAudio) {
  62012. this._audioContext = new AudioContext();
  62013. // create a global volume gain node
  62014. this.masterGain = this._audioContext.createGain();
  62015. this.masterGain.gain.value = 1;
  62016. this.masterGain.connect(this._audioContext.destination);
  62017. this._audioContextInitialized = true;
  62018. }
  62019. }
  62020. catch (e) {
  62021. this.canUseWebAudio = false;
  62022. BABYLON.Tools.Error("Web Audio: " + e.message);
  62023. }
  62024. };
  62025. AudioEngine.prototype.dispose = function () {
  62026. if (this.canUseWebAudio && this._audioContextInitialized) {
  62027. if (this._connectedAnalyser && this._audioContext) {
  62028. this._connectedAnalyser.stopDebugCanvas();
  62029. this._connectedAnalyser.dispose();
  62030. this.masterGain.disconnect();
  62031. this.masterGain.connect(this._audioContext.destination);
  62032. this._connectedAnalyser = null;
  62033. }
  62034. this.masterGain.gain.value = 1;
  62035. }
  62036. this.WarnedWebAudioUnsupported = false;
  62037. };
  62038. AudioEngine.prototype.getGlobalVolume = function () {
  62039. if (this.canUseWebAudio && this._audioContextInitialized) {
  62040. return this.masterGain.gain.value;
  62041. }
  62042. else {
  62043. return -1;
  62044. }
  62045. };
  62046. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62047. if (this.canUseWebAudio && this._audioContextInitialized) {
  62048. this.masterGain.gain.value = newVolume;
  62049. }
  62050. };
  62051. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62052. if (this._connectedAnalyser) {
  62053. this._connectedAnalyser.stopDebugCanvas();
  62054. }
  62055. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62056. this._connectedAnalyser = analyser;
  62057. this.masterGain.disconnect();
  62058. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62059. }
  62060. };
  62061. return AudioEngine;
  62062. }());
  62063. BABYLON.AudioEngine = AudioEngine;
  62064. })(BABYLON || (BABYLON = {}));
  62065. //# sourceMappingURL=babylon.audioEngine.js.map
  62066. var BABYLON;
  62067. (function (BABYLON) {
  62068. var Sound = /** @class */ (function () {
  62069. /**
  62070. * Create a sound and attach it to a scene
  62071. * @param name Name of your sound
  62072. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62073. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62074. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62075. */
  62076. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62077. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62078. var _this = this;
  62079. this.autoplay = false;
  62080. this.loop = false;
  62081. this.useCustomAttenuation = false;
  62082. this.spatialSound = false;
  62083. this.refDistance = 1;
  62084. this.rolloffFactor = 1;
  62085. this.maxDistance = 100;
  62086. this.distanceModel = "linear";
  62087. this._panningModel = "equalpower";
  62088. this._playbackRate = 1;
  62089. this._streaming = false;
  62090. this._startTime = 0;
  62091. this._startOffset = 0;
  62092. this._position = BABYLON.Vector3.Zero();
  62093. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62094. this._volume = 1;
  62095. this._isReadyToPlay = false;
  62096. this.isPlaying = false;
  62097. this.isPaused = false;
  62098. this._isDirectional = false;
  62099. // Used if you'd like to create a directional sound.
  62100. // If not set, the sound will be omnidirectional
  62101. this._coneInnerAngle = 360;
  62102. this._coneOuterAngle = 360;
  62103. this._coneOuterGain = 0;
  62104. this._isOutputConnected = false;
  62105. this._urlType = "Unknown";
  62106. this.name = name;
  62107. this._scene = scene;
  62108. this._readyToPlayCallback = readyToPlayCallback;
  62109. // Default custom attenuation function is a linear attenuation
  62110. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62111. if (currentDistance < maxDistance) {
  62112. return currentVolume * (1 - currentDistance / maxDistance);
  62113. }
  62114. else {
  62115. return 0;
  62116. }
  62117. };
  62118. if (options) {
  62119. this.autoplay = options.autoplay || false;
  62120. this.loop = options.loop || false;
  62121. // if volume === 0, we need another way to check this option
  62122. if (options.volume !== undefined) {
  62123. this._volume = options.volume;
  62124. }
  62125. this.spatialSound = options.spatialSound || false;
  62126. this.maxDistance = options.maxDistance || 100;
  62127. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62128. this.rolloffFactor = options.rolloffFactor || 1;
  62129. this.refDistance = options.refDistance || 1;
  62130. this.distanceModel = options.distanceModel || "linear";
  62131. this._playbackRate = options.playbackRate || 1;
  62132. this._streaming = options.streaming || false;
  62133. }
  62134. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62135. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62136. this._soundGain.gain.value = this._volume;
  62137. this._inputAudioNode = this._soundGain;
  62138. this._ouputAudioNode = this._soundGain;
  62139. if (this.spatialSound) {
  62140. this._createSpatialParameters();
  62141. }
  62142. this._scene.mainSoundTrack.AddSound(this);
  62143. var validParameter = true;
  62144. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62145. if (urlOrArrayBuffer) {
  62146. try {
  62147. if (typeof (urlOrArrayBuffer) === "string") {
  62148. this._urlType = "String";
  62149. }
  62150. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62151. this._urlType = "ArrayBuffer";
  62152. }
  62153. else if (urlOrArrayBuffer instanceof MediaStream) {
  62154. this._urlType = "MediaStream";
  62155. }
  62156. else if (Array.isArray(urlOrArrayBuffer)) {
  62157. this._urlType = "Array";
  62158. }
  62159. var urls = [];
  62160. var codecSupportedFound = false;
  62161. switch (this._urlType) {
  62162. case "MediaStream":
  62163. this._streaming = true;
  62164. this._isReadyToPlay = true;
  62165. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62166. if (this.autoplay) {
  62167. this.play();
  62168. }
  62169. if (this._readyToPlayCallback) {
  62170. this._readyToPlayCallback();
  62171. }
  62172. break;
  62173. case "ArrayBuffer":
  62174. if (urlOrArrayBuffer.byteLength > 0) {
  62175. codecSupportedFound = true;
  62176. this._soundLoaded(urlOrArrayBuffer);
  62177. }
  62178. break;
  62179. case "String":
  62180. urls.push(urlOrArrayBuffer);
  62181. case "Array":
  62182. if (urls.length === 0)
  62183. urls = urlOrArrayBuffer;
  62184. // If we found a supported format, we load it immediately and stop the loop
  62185. for (var i = 0; i < urls.length; i++) {
  62186. var url = urls[i];
  62187. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62188. codecSupportedFound = true;
  62189. }
  62190. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62191. codecSupportedFound = true;
  62192. }
  62193. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62194. codecSupportedFound = true;
  62195. }
  62196. if (url.indexOf("blob:") !== -1) {
  62197. codecSupportedFound = true;
  62198. }
  62199. if (codecSupportedFound) {
  62200. // Loading sound using XHR2
  62201. if (!this._streaming) {
  62202. this._scene._loadFile(url, function (data) {
  62203. _this._soundLoaded(data);
  62204. }, undefined, true, true, function (exception) {
  62205. if (exception) {
  62206. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62207. }
  62208. BABYLON.Tools.Error("Sound creation aborted.");
  62209. _this._scene.mainSoundTrack.RemoveSound(_this);
  62210. });
  62211. }
  62212. // Streaming sound using HTML5 Audio tag
  62213. else {
  62214. this._htmlAudioElement = new Audio(url);
  62215. this._htmlAudioElement.controls = false;
  62216. this._htmlAudioElement.loop = this.loop;
  62217. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62218. this._htmlAudioElement.preload = "auto";
  62219. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62220. _this._isReadyToPlay = true;
  62221. if (_this.autoplay) {
  62222. _this.play();
  62223. }
  62224. if (_this._readyToPlayCallback) {
  62225. _this._readyToPlayCallback();
  62226. }
  62227. });
  62228. document.body.appendChild(this._htmlAudioElement);
  62229. }
  62230. break;
  62231. }
  62232. }
  62233. break;
  62234. default:
  62235. validParameter = false;
  62236. break;
  62237. }
  62238. if (!validParameter) {
  62239. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62240. }
  62241. else {
  62242. if (!codecSupportedFound) {
  62243. this._isReadyToPlay = true;
  62244. // Simulating a ready to play event to avoid breaking code path
  62245. if (this._readyToPlayCallback) {
  62246. window.setTimeout(function () {
  62247. if (_this._readyToPlayCallback) {
  62248. _this._readyToPlayCallback();
  62249. }
  62250. }, 1000);
  62251. }
  62252. }
  62253. }
  62254. }
  62255. catch (ex) {
  62256. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62257. this._scene.mainSoundTrack.RemoveSound(this);
  62258. }
  62259. }
  62260. }
  62261. else {
  62262. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62263. this._scene.mainSoundTrack.AddSound(this);
  62264. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62265. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62266. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62267. }
  62268. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62269. if (this._readyToPlayCallback) {
  62270. window.setTimeout(function () {
  62271. if (_this._readyToPlayCallback) {
  62272. _this._readyToPlayCallback();
  62273. }
  62274. }, 1000);
  62275. }
  62276. }
  62277. }
  62278. Sound.prototype.dispose = function () {
  62279. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62280. if (this.isPlaying) {
  62281. this.stop();
  62282. }
  62283. this._isReadyToPlay = false;
  62284. if (this.soundTrackId === -1) {
  62285. this._scene.mainSoundTrack.RemoveSound(this);
  62286. }
  62287. else {
  62288. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62289. }
  62290. if (this._soundGain) {
  62291. this._soundGain.disconnect();
  62292. this._soundGain = null;
  62293. }
  62294. if (this._soundPanner) {
  62295. this._soundPanner.disconnect();
  62296. this._soundPanner = null;
  62297. }
  62298. if (this._soundSource) {
  62299. this._soundSource.disconnect();
  62300. this._soundSource = null;
  62301. }
  62302. this._audioBuffer = null;
  62303. if (this._htmlAudioElement) {
  62304. this._htmlAudioElement.pause();
  62305. this._htmlAudioElement.src = "";
  62306. document.body.removeChild(this._htmlAudioElement);
  62307. }
  62308. if (this._streamingSource) {
  62309. this._streamingSource.disconnect();
  62310. }
  62311. if (this._connectedMesh && this._registerFunc) {
  62312. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62313. this._connectedMesh = null;
  62314. }
  62315. }
  62316. };
  62317. Sound.prototype.isReady = function () {
  62318. return this._isReadyToPlay;
  62319. };
  62320. Sound.prototype._soundLoaded = function (audioData) {
  62321. var _this = this;
  62322. if (!BABYLON.Engine.audioEngine.audioContext) {
  62323. return;
  62324. }
  62325. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62326. _this._audioBuffer = buffer;
  62327. _this._isReadyToPlay = true;
  62328. if (_this.autoplay) {
  62329. _this.play();
  62330. }
  62331. if (_this._readyToPlayCallback) {
  62332. _this._readyToPlayCallback();
  62333. }
  62334. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62335. };
  62336. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62337. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62338. this._audioBuffer = audioBuffer;
  62339. this._isReadyToPlay = true;
  62340. }
  62341. };
  62342. Sound.prototype.updateOptions = function (options) {
  62343. if (options) {
  62344. this.loop = options.loop || this.loop;
  62345. this.maxDistance = options.maxDistance || this.maxDistance;
  62346. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62347. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62348. this.refDistance = options.refDistance || this.refDistance;
  62349. this.distanceModel = options.distanceModel || this.distanceModel;
  62350. this._playbackRate = options.playbackRate || this._playbackRate;
  62351. this._updateSpatialParameters();
  62352. if (this.isPlaying) {
  62353. if (this._streaming && this._htmlAudioElement) {
  62354. this._htmlAudioElement.playbackRate = this._playbackRate;
  62355. }
  62356. else {
  62357. if (this._soundSource) {
  62358. this._soundSource.playbackRate.value = this._playbackRate;
  62359. }
  62360. }
  62361. }
  62362. }
  62363. };
  62364. Sound.prototype._createSpatialParameters = function () {
  62365. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62366. if (this._scene.headphone) {
  62367. this._panningModel = "HRTF";
  62368. }
  62369. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62370. this._updateSpatialParameters();
  62371. this._soundPanner.connect(this._ouputAudioNode);
  62372. this._inputAudioNode = this._soundPanner;
  62373. }
  62374. };
  62375. Sound.prototype._updateSpatialParameters = function () {
  62376. if (this.spatialSound && this._soundPanner) {
  62377. if (this.useCustomAttenuation) {
  62378. // Tricks to disable in a way embedded Web Audio attenuation
  62379. this._soundPanner.distanceModel = "linear";
  62380. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62381. this._soundPanner.refDistance = 1;
  62382. this._soundPanner.rolloffFactor = 1;
  62383. this._soundPanner.panningModel = this._panningModel;
  62384. }
  62385. else {
  62386. this._soundPanner.distanceModel = this.distanceModel;
  62387. this._soundPanner.maxDistance = this.maxDistance;
  62388. this._soundPanner.refDistance = this.refDistance;
  62389. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62390. this._soundPanner.panningModel = this._panningModel;
  62391. }
  62392. }
  62393. };
  62394. Sound.prototype.switchPanningModelToHRTF = function () {
  62395. this._panningModel = "HRTF";
  62396. this._switchPanningModel();
  62397. };
  62398. Sound.prototype.switchPanningModelToEqualPower = function () {
  62399. this._panningModel = "equalpower";
  62400. this._switchPanningModel();
  62401. };
  62402. Sound.prototype._switchPanningModel = function () {
  62403. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62404. this._soundPanner.panningModel = this._panningModel;
  62405. }
  62406. };
  62407. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62408. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62409. if (this._isOutputConnected) {
  62410. this._ouputAudioNode.disconnect();
  62411. }
  62412. this._ouputAudioNode.connect(soundTrackAudioNode);
  62413. this._isOutputConnected = true;
  62414. }
  62415. };
  62416. /**
  62417. * Transform this sound into a directional source
  62418. * @param coneInnerAngle Size of the inner cone in degree
  62419. * @param coneOuterAngle Size of the outer cone in degree
  62420. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62421. */
  62422. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62423. if (coneOuterAngle < coneInnerAngle) {
  62424. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62425. return;
  62426. }
  62427. this._coneInnerAngle = coneInnerAngle;
  62428. this._coneOuterAngle = coneOuterAngle;
  62429. this._coneOuterGain = coneOuterGain;
  62430. this._isDirectional = true;
  62431. if (this.isPlaying && this.loop) {
  62432. this.stop();
  62433. this.play();
  62434. }
  62435. };
  62436. Sound.prototype.setPosition = function (newPosition) {
  62437. this._position = newPosition;
  62438. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62439. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62440. }
  62441. };
  62442. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62443. this._localDirection = newLocalDirection;
  62444. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62445. this._updateDirection();
  62446. }
  62447. };
  62448. Sound.prototype._updateDirection = function () {
  62449. if (!this._connectedMesh || !this._soundPanner) {
  62450. return;
  62451. }
  62452. var mat = this._connectedMesh.getWorldMatrix();
  62453. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62454. direction.normalize();
  62455. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62456. };
  62457. Sound.prototype.updateDistanceFromListener = function () {
  62458. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62459. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62460. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62461. }
  62462. };
  62463. Sound.prototype.setAttenuationFunction = function (callback) {
  62464. this._customAttenuationFunction = callback;
  62465. };
  62466. /**
  62467. * Play the sound
  62468. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62469. * @param offset (optional) Start the sound setting it at a specific time
  62470. */
  62471. Sound.prototype.play = function (time, offset) {
  62472. var _this = this;
  62473. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62474. try {
  62475. if (this._startOffset < 0) {
  62476. time = -this._startOffset;
  62477. this._startOffset = 0;
  62478. }
  62479. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62480. if (!this._soundSource || !this._streamingSource) {
  62481. if (this.spatialSound && this._soundPanner) {
  62482. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62483. if (this._isDirectional) {
  62484. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62485. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62486. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62487. if (this._connectedMesh) {
  62488. this._updateDirection();
  62489. }
  62490. else {
  62491. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62492. }
  62493. }
  62494. }
  62495. }
  62496. if (this._streaming) {
  62497. if (!this._streamingSource) {
  62498. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62499. this._htmlAudioElement.onended = function () { _this._onended(); };
  62500. this._htmlAudioElement.playbackRate = this._playbackRate;
  62501. }
  62502. this._streamingSource.disconnect();
  62503. this._streamingSource.connect(this._inputAudioNode);
  62504. if (this._htmlAudioElement) {
  62505. this._htmlAudioElement.play();
  62506. }
  62507. }
  62508. else {
  62509. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62510. this._soundSource.buffer = this._audioBuffer;
  62511. this._soundSource.connect(this._inputAudioNode);
  62512. this._soundSource.loop = this.loop;
  62513. this._soundSource.playbackRate.value = this._playbackRate;
  62514. this._soundSource.onended = function () { _this._onended(); };
  62515. if (this._soundSource.buffer) {
  62516. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62517. }
  62518. }
  62519. this._startTime = startTime;
  62520. this.isPlaying = true;
  62521. this.isPaused = false;
  62522. }
  62523. catch (ex) {
  62524. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62525. }
  62526. }
  62527. };
  62528. Sound.prototype._onended = function () {
  62529. this.isPlaying = false;
  62530. if (this.onended) {
  62531. this.onended();
  62532. }
  62533. };
  62534. /**
  62535. * Stop the sound
  62536. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62537. */
  62538. Sound.prototype.stop = function (time) {
  62539. if (this.isPlaying) {
  62540. if (this._streaming) {
  62541. if (this._htmlAudioElement) {
  62542. this._htmlAudioElement.pause();
  62543. // Test needed for Firefox or it will generate an Invalid State Error
  62544. if (this._htmlAudioElement.currentTime > 0) {
  62545. this._htmlAudioElement.currentTime = 0;
  62546. }
  62547. }
  62548. else {
  62549. this._streamingSource.disconnect();
  62550. }
  62551. }
  62552. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62553. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62554. this._soundSource.stop(stopTime);
  62555. this._soundSource.onended = function () { };
  62556. if (!this.isPaused) {
  62557. this._startOffset = 0;
  62558. }
  62559. }
  62560. this.isPlaying = false;
  62561. }
  62562. };
  62563. Sound.prototype.pause = function () {
  62564. if (this.isPlaying) {
  62565. this.isPaused = true;
  62566. if (this._streaming) {
  62567. if (this._htmlAudioElement) {
  62568. this._htmlAudioElement.pause();
  62569. }
  62570. else {
  62571. this._streamingSource.disconnect();
  62572. }
  62573. }
  62574. else if (BABYLON.Engine.audioEngine.audioContext) {
  62575. this.stop(0);
  62576. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62577. }
  62578. }
  62579. };
  62580. Sound.prototype.setVolume = function (newVolume, time) {
  62581. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62582. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62583. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62584. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62585. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62586. }
  62587. else {
  62588. this._soundGain.gain.value = newVolume;
  62589. }
  62590. }
  62591. this._volume = newVolume;
  62592. };
  62593. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62594. this._playbackRate = newPlaybackRate;
  62595. if (this.isPlaying) {
  62596. if (this._streaming && this._htmlAudioElement) {
  62597. this._htmlAudioElement.playbackRate = this._playbackRate;
  62598. }
  62599. else if (this._soundSource) {
  62600. this._soundSource.playbackRate.value = this._playbackRate;
  62601. }
  62602. }
  62603. };
  62604. Sound.prototype.getVolume = function () {
  62605. return this._volume;
  62606. };
  62607. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62608. var _this = this;
  62609. if (this._connectedMesh && this._registerFunc) {
  62610. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62611. this._registerFunc = null;
  62612. }
  62613. this._connectedMesh = meshToConnectTo;
  62614. if (!this.spatialSound) {
  62615. this.spatialSound = true;
  62616. this._createSpatialParameters();
  62617. if (this.isPlaying && this.loop) {
  62618. this.stop();
  62619. this.play();
  62620. }
  62621. }
  62622. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62623. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62624. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62625. };
  62626. Sound.prototype.detachFromMesh = function () {
  62627. if (this._connectedMesh && this._registerFunc) {
  62628. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62629. this._registerFunc = null;
  62630. this._connectedMesh = null;
  62631. }
  62632. };
  62633. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62634. if (!node.getBoundingInfo) {
  62635. return;
  62636. }
  62637. var mesh = node;
  62638. var boundingInfo = mesh.getBoundingInfo();
  62639. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62640. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62641. this._updateDirection();
  62642. }
  62643. };
  62644. Sound.prototype.clone = function () {
  62645. var _this = this;
  62646. if (!this._streaming) {
  62647. var setBufferAndRun = function () {
  62648. if (_this._isReadyToPlay) {
  62649. clonedSound._audioBuffer = _this.getAudioBuffer();
  62650. clonedSound._isReadyToPlay = true;
  62651. if (clonedSound.autoplay) {
  62652. clonedSound.play();
  62653. }
  62654. }
  62655. else {
  62656. window.setTimeout(setBufferAndRun, 300);
  62657. }
  62658. };
  62659. var currentOptions = {
  62660. autoplay: this.autoplay, loop: this.loop,
  62661. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62662. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62663. refDistance: this.refDistance, distanceModel: this.distanceModel
  62664. };
  62665. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62666. if (this.useCustomAttenuation) {
  62667. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62668. }
  62669. clonedSound.setPosition(this._position);
  62670. clonedSound.setPlaybackRate(this._playbackRate);
  62671. setBufferAndRun();
  62672. return clonedSound;
  62673. }
  62674. // Can't clone a streaming sound
  62675. else {
  62676. return null;
  62677. }
  62678. };
  62679. Sound.prototype.getAudioBuffer = function () {
  62680. return this._audioBuffer;
  62681. };
  62682. Sound.prototype.serialize = function () {
  62683. var serializationObject = {
  62684. name: this.name,
  62685. url: this.name,
  62686. autoplay: this.autoplay,
  62687. loop: this.loop,
  62688. volume: this._volume,
  62689. spatialSound: this.spatialSound,
  62690. maxDistance: this.maxDistance,
  62691. rolloffFactor: this.rolloffFactor,
  62692. refDistance: this.refDistance,
  62693. distanceModel: this.distanceModel,
  62694. playbackRate: this._playbackRate,
  62695. panningModel: this._panningModel,
  62696. soundTrackId: this.soundTrackId
  62697. };
  62698. if (this.spatialSound) {
  62699. if (this._connectedMesh)
  62700. serializationObject.connectedMeshId = this._connectedMesh.id;
  62701. serializationObject.position = this._position.asArray();
  62702. serializationObject.refDistance = this.refDistance;
  62703. serializationObject.distanceModel = this.distanceModel;
  62704. serializationObject.isDirectional = this._isDirectional;
  62705. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62706. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62707. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62708. serializationObject.coneOuterGain = this._coneOuterGain;
  62709. }
  62710. return serializationObject;
  62711. };
  62712. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62713. var soundName = parsedSound.name;
  62714. var soundUrl;
  62715. if (parsedSound.url) {
  62716. soundUrl = rootUrl + parsedSound.url;
  62717. }
  62718. else {
  62719. soundUrl = rootUrl + soundName;
  62720. }
  62721. var options = {
  62722. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62723. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62724. rolloffFactor: parsedSound.rolloffFactor,
  62725. refDistance: parsedSound.refDistance,
  62726. distanceModel: parsedSound.distanceModel,
  62727. playbackRate: parsedSound.playbackRate
  62728. };
  62729. var newSound;
  62730. if (!sourceSound) {
  62731. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62732. scene._addPendingData(newSound);
  62733. }
  62734. else {
  62735. var setBufferAndRun = function () {
  62736. if (sourceSound._isReadyToPlay) {
  62737. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62738. newSound._isReadyToPlay = true;
  62739. if (newSound.autoplay) {
  62740. newSound.play();
  62741. }
  62742. }
  62743. else {
  62744. window.setTimeout(setBufferAndRun, 300);
  62745. }
  62746. };
  62747. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62748. setBufferAndRun();
  62749. }
  62750. if (parsedSound.position) {
  62751. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62752. newSound.setPosition(soundPosition);
  62753. }
  62754. if (parsedSound.isDirectional) {
  62755. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62756. if (parsedSound.localDirectionToMesh) {
  62757. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62758. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62759. }
  62760. }
  62761. if (parsedSound.connectedMeshId) {
  62762. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62763. if (connectedMesh) {
  62764. newSound.attachToMesh(connectedMesh);
  62765. }
  62766. }
  62767. return newSound;
  62768. };
  62769. return Sound;
  62770. }());
  62771. BABYLON.Sound = Sound;
  62772. })(BABYLON || (BABYLON = {}));
  62773. //# sourceMappingURL=babylon.sound.js.map
  62774. var BABYLON;
  62775. (function (BABYLON) {
  62776. var SoundTrack = /** @class */ (function () {
  62777. function SoundTrack(scene, options) {
  62778. this.id = -1;
  62779. this._isMainTrack = false;
  62780. this._isInitialized = false;
  62781. this._scene = scene;
  62782. this.soundCollection = new Array();
  62783. this._options = options;
  62784. if (!this._isMainTrack) {
  62785. this._scene.soundTracks.push(this);
  62786. this.id = this._scene.soundTracks.length - 1;
  62787. }
  62788. }
  62789. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62790. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62791. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62792. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62793. if (this._options) {
  62794. if (this._options.volume) {
  62795. this._outputAudioNode.gain.value = this._options.volume;
  62796. }
  62797. if (this._options.mainTrack) {
  62798. this._isMainTrack = this._options.mainTrack;
  62799. }
  62800. }
  62801. this._isInitialized = true;
  62802. }
  62803. };
  62804. SoundTrack.prototype.dispose = function () {
  62805. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62806. if (this._connectedAnalyser) {
  62807. this._connectedAnalyser.stopDebugCanvas();
  62808. }
  62809. while (this.soundCollection.length) {
  62810. this.soundCollection[0].dispose();
  62811. }
  62812. if (this._outputAudioNode) {
  62813. this._outputAudioNode.disconnect();
  62814. }
  62815. this._outputAudioNode = null;
  62816. }
  62817. };
  62818. SoundTrack.prototype.AddSound = function (sound) {
  62819. if (!this._isInitialized) {
  62820. this._initializeSoundTrackAudioGraph();
  62821. }
  62822. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62823. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62824. }
  62825. if (sound.soundTrackId) {
  62826. if (sound.soundTrackId === -1) {
  62827. this._scene.mainSoundTrack.RemoveSound(sound);
  62828. }
  62829. else {
  62830. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62831. }
  62832. }
  62833. this.soundCollection.push(sound);
  62834. sound.soundTrackId = this.id;
  62835. };
  62836. SoundTrack.prototype.RemoveSound = function (sound) {
  62837. var index = this.soundCollection.indexOf(sound);
  62838. if (index !== -1) {
  62839. this.soundCollection.splice(index, 1);
  62840. }
  62841. };
  62842. SoundTrack.prototype.setVolume = function (newVolume) {
  62843. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62844. this._outputAudioNode.gain.value = newVolume;
  62845. }
  62846. };
  62847. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62848. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62849. for (var i = 0; i < this.soundCollection.length; i++) {
  62850. this.soundCollection[i].switchPanningModelToHRTF();
  62851. }
  62852. }
  62853. };
  62854. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62855. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62856. for (var i = 0; i < this.soundCollection.length; i++) {
  62857. this.soundCollection[i].switchPanningModelToEqualPower();
  62858. }
  62859. }
  62860. };
  62861. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62862. if (this._connectedAnalyser) {
  62863. this._connectedAnalyser.stopDebugCanvas();
  62864. }
  62865. this._connectedAnalyser = analyser;
  62866. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62867. this._outputAudioNode.disconnect();
  62868. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62869. }
  62870. };
  62871. return SoundTrack;
  62872. }());
  62873. BABYLON.SoundTrack = SoundTrack;
  62874. })(BABYLON || (BABYLON = {}));
  62875. //# sourceMappingURL=babylon.soundtrack.js.map
  62876. var BABYLON;
  62877. (function (BABYLON) {
  62878. /**
  62879. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62880. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62881. */
  62882. var Analyser = /** @class */ (function () {
  62883. /**
  62884. * Creates a new analyser
  62885. * @param scene defines hosting scene
  62886. */
  62887. function Analyser(scene) {
  62888. /**
  62889. * Gets or sets the smoothing
  62890. * @ignorenaming
  62891. */
  62892. this.SMOOTHING = 0.75;
  62893. /**
  62894. * Gets or sets the FFT table size
  62895. * @ignorenaming
  62896. */
  62897. this.FFT_SIZE = 512;
  62898. /**
  62899. * Gets or sets the bar graph amplitude
  62900. * @ignorenaming
  62901. */
  62902. this.BARGRAPHAMPLITUDE = 256;
  62903. /**
  62904. * Gets or sets the position of the debug canvas
  62905. * @ignorenaming
  62906. */
  62907. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62908. /**
  62909. * Gets or sets the debug canvas size
  62910. * @ignorenaming
  62911. */
  62912. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62913. this._scene = scene;
  62914. this._audioEngine = BABYLON.Engine.audioEngine;
  62915. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62916. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62917. this._webAudioAnalyser.minDecibels = -140;
  62918. this._webAudioAnalyser.maxDecibels = 0;
  62919. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62920. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62921. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62922. }
  62923. }
  62924. /**
  62925. * Get the number of data values you will have to play with for the visualization
  62926. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62927. * @returns a number
  62928. */
  62929. Analyser.prototype.getFrequencyBinCount = function () {
  62930. if (this._audioEngine.canUseWebAudio) {
  62931. return this._webAudioAnalyser.frequencyBinCount;
  62932. }
  62933. else {
  62934. return 0;
  62935. }
  62936. };
  62937. /**
  62938. * Gets the current frequency data as a byte array
  62939. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62940. * @returns a Uint8Array
  62941. */
  62942. Analyser.prototype.getByteFrequencyData = function () {
  62943. if (this._audioEngine.canUseWebAudio) {
  62944. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62945. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62946. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62947. }
  62948. return this._byteFreqs;
  62949. };
  62950. /**
  62951. * Gets the current waveform as a byte array
  62952. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62953. * @returns a Uint8Array
  62954. */
  62955. Analyser.prototype.getByteTimeDomainData = function () {
  62956. if (this._audioEngine.canUseWebAudio) {
  62957. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62958. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62959. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62960. }
  62961. return this._byteTime;
  62962. };
  62963. /**
  62964. * Gets the current frequency data as a float array
  62965. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62966. * @returns a Float32Array
  62967. */
  62968. Analyser.prototype.getFloatFrequencyData = function () {
  62969. if (this._audioEngine.canUseWebAudio) {
  62970. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62971. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62972. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62973. }
  62974. return this._floatFreqs;
  62975. };
  62976. /**
  62977. * Renders the debug canvas
  62978. */
  62979. Analyser.prototype.drawDebugCanvas = function () {
  62980. var _this = this;
  62981. if (this._audioEngine.canUseWebAudio) {
  62982. if (!this._debugCanvas) {
  62983. this._debugCanvas = document.createElement("canvas");
  62984. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62985. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62986. this._debugCanvas.style.position = "absolute";
  62987. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62988. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62989. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62990. document.body.appendChild(this._debugCanvas);
  62991. this._registerFunc = function () {
  62992. _this.drawDebugCanvas();
  62993. };
  62994. this._scene.registerBeforeRender(this._registerFunc);
  62995. }
  62996. if (this._registerFunc && this._debugCanvasContext) {
  62997. var workingArray = this.getByteFrequencyData();
  62998. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62999. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63000. // Draw the frequency domain chart.
  63001. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63002. var value = workingArray[i];
  63003. var percent = value / this.BARGRAPHAMPLITUDE;
  63004. var height = this.DEBUGCANVASSIZE.height * percent;
  63005. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63006. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63007. var hue = i / this.getFrequencyBinCount() * 360;
  63008. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63009. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63010. }
  63011. }
  63012. }
  63013. };
  63014. /**
  63015. * Stops rendering the debug canvas and removes it
  63016. */
  63017. Analyser.prototype.stopDebugCanvas = function () {
  63018. if (this._debugCanvas) {
  63019. if (this._registerFunc) {
  63020. this._scene.unregisterBeforeRender(this._registerFunc);
  63021. this._registerFunc = null;
  63022. }
  63023. document.body.removeChild(this._debugCanvas);
  63024. this._debugCanvas = null;
  63025. this._debugCanvasContext = null;
  63026. }
  63027. };
  63028. /**
  63029. * Connects two audio nodes
  63030. * @param inputAudioNode defines first node to connect
  63031. * @param outputAudioNode defines second node to connect
  63032. */
  63033. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63034. if (this._audioEngine.canUseWebAudio) {
  63035. inputAudioNode.connect(this._webAudioAnalyser);
  63036. this._webAudioAnalyser.connect(outputAudioNode);
  63037. }
  63038. };
  63039. /**
  63040. * Releases all associated resources
  63041. */
  63042. Analyser.prototype.dispose = function () {
  63043. if (this._audioEngine.canUseWebAudio) {
  63044. this._webAudioAnalyser.disconnect();
  63045. }
  63046. };
  63047. return Analyser;
  63048. }());
  63049. BABYLON.Analyser = Analyser;
  63050. })(BABYLON || (BABYLON = {}));
  63051. //# sourceMappingURL=babylon.analyser.js.map
  63052. var BABYLON;
  63053. (function (BABYLON) {
  63054. var CubeTexture = /** @class */ (function (_super) {
  63055. __extends(CubeTexture, _super);
  63056. /**
  63057. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63058. * as prefiltered data.
  63059. * @param rootUrl defines the url of the texture or the root name of the six images
  63060. * @param scene defines the scene the texture is attached to
  63061. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63062. * @param noMipmap defines if mipmaps should be created or not
  63063. * @param files defines the six files to load for the different faces
  63064. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63065. * @param onError defines a callback triggered in case of error during load
  63066. * @param format defines the internal format to use for the texture once loaded
  63067. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63068. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63069. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63070. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63071. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63072. * @return the cube texture
  63073. */
  63074. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63075. if (extensions === void 0) { extensions = null; }
  63076. if (noMipmap === void 0) { noMipmap = false; }
  63077. if (files === void 0) { files = null; }
  63078. if (onLoad === void 0) { onLoad = null; }
  63079. if (onError === void 0) { onError = null; }
  63080. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63081. if (prefiltered === void 0) { prefiltered = false; }
  63082. if (forcedExtension === void 0) { forcedExtension = null; }
  63083. if (createPolynomials === void 0) { createPolynomials = false; }
  63084. if (lodScale === void 0) { lodScale = 0.8; }
  63085. if (lodOffset === void 0) { lodOffset = 0; }
  63086. var _this = _super.call(this, scene) || this;
  63087. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63088. /**
  63089. * Gets or sets the center of the bounding box associated with the cube texture
  63090. * It must define where the camera used to render the texture was set
  63091. */
  63092. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63093. _this._rotationY = 0;
  63094. /** @hidden */
  63095. _this._prefiltered = false;
  63096. _this.name = rootUrl;
  63097. _this.url = rootUrl;
  63098. _this._noMipmap = noMipmap;
  63099. _this.hasAlpha = false;
  63100. _this._format = format;
  63101. _this.isCube = true;
  63102. _this._textureMatrix = BABYLON.Matrix.Identity();
  63103. _this._createPolynomials = createPolynomials;
  63104. if (!rootUrl && !files) {
  63105. return _this;
  63106. }
  63107. var lastDot = rootUrl.lastIndexOf(".");
  63108. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63109. var isDDS = (extension === ".dds");
  63110. var isEnv = (extension === ".env");
  63111. if (isEnv) {
  63112. _this.gammaSpace = false;
  63113. _this._prefiltered = false;
  63114. }
  63115. else {
  63116. _this._prefiltered = prefiltered;
  63117. if (prefiltered) {
  63118. _this.gammaSpace = false;
  63119. }
  63120. }
  63121. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63122. if (!files) {
  63123. if (!isEnv && !isDDS && !extensions) {
  63124. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63125. }
  63126. files = [];
  63127. if (extensions) {
  63128. for (var index = 0; index < extensions.length; index++) {
  63129. files.push(rootUrl + extensions[index]);
  63130. }
  63131. }
  63132. }
  63133. _this._files = files;
  63134. if (!_this._texture) {
  63135. if (!scene.useDelayedTextureLoading) {
  63136. if (prefiltered) {
  63137. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63138. }
  63139. else {
  63140. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63141. }
  63142. }
  63143. else {
  63144. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63145. }
  63146. }
  63147. else if (onLoad) {
  63148. if (_this._texture.isReady) {
  63149. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63150. }
  63151. else {
  63152. _this._texture.onLoadedObservable.add(onLoad);
  63153. }
  63154. }
  63155. return _this;
  63156. }
  63157. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63158. get: function () {
  63159. return this._boundingBoxSize;
  63160. },
  63161. /**
  63162. * Gets or sets the size of the bounding box associated with the cube texture
  63163. * When defined, the cubemap will switch to local mode
  63164. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63165. * @example https://www.babylonjs-playground.com/#RNASML
  63166. */
  63167. set: function (value) {
  63168. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63169. return;
  63170. }
  63171. this._boundingBoxSize = value;
  63172. var scene = this.getScene();
  63173. if (scene) {
  63174. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63175. }
  63176. },
  63177. enumerable: true,
  63178. configurable: true
  63179. });
  63180. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63181. /**
  63182. * Gets texture matrix rotation angle around Y axis radians.
  63183. */
  63184. get: function () {
  63185. return this._rotationY;
  63186. },
  63187. /**
  63188. * Sets texture matrix rotation angle around Y axis in radians.
  63189. */
  63190. set: function (value) {
  63191. this._rotationY = value;
  63192. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63193. },
  63194. enumerable: true,
  63195. configurable: true
  63196. });
  63197. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63198. var rootUrlKey = "";
  63199. files.forEach(function (url) { return rootUrlKey += url; });
  63200. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63201. };
  63202. /**
  63203. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63204. * @param url defines the url of the prefiltered texture
  63205. * @param scene defines the scene the texture is attached to
  63206. * @param forcedExtension defines the extension of the file if different from the url
  63207. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63208. * @return the prefiltered texture
  63209. */
  63210. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63211. if (forcedExtension === void 0) { forcedExtension = null; }
  63212. if (createPolynomials === void 0) { createPolynomials = true; }
  63213. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63214. };
  63215. // Methods
  63216. CubeTexture.prototype.delayLoad = function () {
  63217. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63218. return;
  63219. }
  63220. var scene = this.getScene();
  63221. if (!scene) {
  63222. return;
  63223. }
  63224. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63225. this._texture = this._getFromCache(this.url, this._noMipmap);
  63226. if (!this._texture) {
  63227. if (this._prefiltered) {
  63228. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63229. }
  63230. else {
  63231. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63232. }
  63233. }
  63234. };
  63235. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63236. return this._textureMatrix;
  63237. };
  63238. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63239. this._textureMatrix = value;
  63240. };
  63241. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63242. var texture = BABYLON.SerializationHelper.Parse(function () {
  63243. var prefiltered = false;
  63244. if (parsedTexture.prefiltered) {
  63245. prefiltered = parsedTexture.prefiltered;
  63246. }
  63247. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63248. }, parsedTexture, scene);
  63249. // Local Cubemaps
  63250. if (parsedTexture.boundingBoxPosition) {
  63251. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63252. }
  63253. if (parsedTexture.boundingBoxSize) {
  63254. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63255. }
  63256. // Animations
  63257. if (parsedTexture.animations) {
  63258. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63259. var parsedAnimation = parsedTexture.animations[animationIndex];
  63260. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63261. }
  63262. }
  63263. return texture;
  63264. };
  63265. CubeTexture.prototype.clone = function () {
  63266. var _this = this;
  63267. return BABYLON.SerializationHelper.Clone(function () {
  63268. var scene = _this.getScene();
  63269. if (!scene) {
  63270. return _this;
  63271. }
  63272. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63273. }, this);
  63274. };
  63275. __decorate([
  63276. BABYLON.serialize("rotationY")
  63277. ], CubeTexture.prototype, "_rotationY", void 0);
  63278. return CubeTexture;
  63279. }(BABYLON.BaseTexture));
  63280. BABYLON.CubeTexture = CubeTexture;
  63281. })(BABYLON || (BABYLON = {}));
  63282. //# sourceMappingURL=babylon.cubeTexture.js.map
  63283. var BABYLON;
  63284. (function (BABYLON) {
  63285. var RenderTargetTexture = /** @class */ (function (_super) {
  63286. __extends(RenderTargetTexture, _super);
  63287. /**
  63288. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63289. * or used a shadow, depth texture...
  63290. * @param name The friendly name of the texture
  63291. * @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)
  63292. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63293. * @param generateMipMaps True if mip maps need to be generated after render.
  63294. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63295. * @param type The type of the buffer in the RTT (int, half float, float...)
  63296. * @param isCube True if a cube texture needs to be created
  63297. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63298. * @param generateDepthBuffer True to generate a depth buffer
  63299. * @param generateStencilBuffer True to generate a stencil buffer
  63300. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63301. */
  63302. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63303. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63304. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63305. if (isCube === void 0) { isCube = false; }
  63306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63307. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63308. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63309. if (isMulti === void 0) { isMulti = false; }
  63310. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63311. _this.isCube = isCube;
  63312. /**
  63313. * Use this list to define the list of mesh you want to render.
  63314. */
  63315. _this.renderList = new Array();
  63316. _this.renderParticles = true;
  63317. _this.renderSprites = false;
  63318. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63319. _this.ignoreCameraViewport = false;
  63320. // Events
  63321. /**
  63322. * An event triggered when the texture is unbind.
  63323. */
  63324. _this.onBeforeBindObservable = new BABYLON.Observable();
  63325. /**
  63326. * An event triggered when the texture is unbind.
  63327. */
  63328. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63329. /**
  63330. * An event triggered before rendering the texture
  63331. */
  63332. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63333. /**
  63334. * An event triggered after rendering the texture
  63335. */
  63336. _this.onAfterRenderObservable = new BABYLON.Observable();
  63337. /**
  63338. * An event triggered after the texture clear
  63339. */
  63340. _this.onClearObservable = new BABYLON.Observable();
  63341. _this._currentRefreshId = -1;
  63342. _this._refreshRate = 1;
  63343. _this._samples = 1;
  63344. /**
  63345. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63346. * It must define where the camera used to render the texture is set
  63347. */
  63348. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63349. scene = _this.getScene();
  63350. if (!scene) {
  63351. return _this;
  63352. }
  63353. _this._engine = scene.getEngine();
  63354. _this.name = name;
  63355. _this.isRenderTarget = true;
  63356. _this._initialSizeParameter = size;
  63357. _this._processSizeParameter(size);
  63358. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63359. });
  63360. _this._generateMipMaps = generateMipMaps ? true : false;
  63361. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63362. // Rendering groups
  63363. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63364. if (isMulti) {
  63365. return _this;
  63366. }
  63367. _this._renderTargetOptions = {
  63368. generateMipMaps: generateMipMaps,
  63369. type: type,
  63370. samplingMode: samplingMode,
  63371. generateDepthBuffer: generateDepthBuffer,
  63372. generateStencilBuffer: generateStencilBuffer
  63373. };
  63374. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63375. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63376. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63377. }
  63378. if (isCube) {
  63379. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63380. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63381. _this._textureMatrix = BABYLON.Matrix.Identity();
  63382. }
  63383. else {
  63384. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63385. }
  63386. return _this;
  63387. }
  63388. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63389. get: function () {
  63390. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63391. },
  63392. enumerable: true,
  63393. configurable: true
  63394. });
  63395. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63396. get: function () {
  63397. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63398. },
  63399. enumerable: true,
  63400. configurable: true
  63401. });
  63402. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63403. get: function () {
  63404. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63405. },
  63406. enumerable: true,
  63407. configurable: true
  63408. });
  63409. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63410. set: function (callback) {
  63411. if (this._onAfterUnbindObserver) {
  63412. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63413. }
  63414. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63415. },
  63416. enumerable: true,
  63417. configurable: true
  63418. });
  63419. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63420. set: function (callback) {
  63421. if (this._onBeforeRenderObserver) {
  63422. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63423. }
  63424. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63425. },
  63426. enumerable: true,
  63427. configurable: true
  63428. });
  63429. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63430. set: function (callback) {
  63431. if (this._onAfterRenderObserver) {
  63432. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63433. }
  63434. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63435. },
  63436. enumerable: true,
  63437. configurable: true
  63438. });
  63439. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63440. set: function (callback) {
  63441. if (this._onClearObserver) {
  63442. this.onClearObservable.remove(this._onClearObserver);
  63443. }
  63444. this._onClearObserver = this.onClearObservable.add(callback);
  63445. },
  63446. enumerable: true,
  63447. configurable: true
  63448. });
  63449. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63450. get: function () {
  63451. return this._renderTargetOptions;
  63452. },
  63453. enumerable: true,
  63454. configurable: true
  63455. });
  63456. RenderTargetTexture.prototype._onRatioRescale = function () {
  63457. if (this._sizeRatio) {
  63458. this.resize(this._initialSizeParameter);
  63459. }
  63460. };
  63461. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63462. get: function () {
  63463. return this._boundingBoxSize;
  63464. },
  63465. /**
  63466. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63467. * When defined, the cubemap will switch to local mode
  63468. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63469. * @example https://www.babylonjs-playground.com/#RNASML
  63470. */
  63471. set: function (value) {
  63472. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63473. return;
  63474. }
  63475. this._boundingBoxSize = value;
  63476. var scene = this.getScene();
  63477. if (scene) {
  63478. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63479. }
  63480. },
  63481. enumerable: true,
  63482. configurable: true
  63483. });
  63484. /**
  63485. * Creates a depth stencil texture.
  63486. * This is only available in WebGL 2 or with the depth texture extension available.
  63487. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63488. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63489. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63490. */
  63491. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63492. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63493. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63494. if (generateStencil === void 0) { generateStencil = false; }
  63495. if (!this.getScene()) {
  63496. return;
  63497. }
  63498. var engine = this.getScene().getEngine();
  63499. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63500. bilinearFiltering: bilinearFiltering,
  63501. comparisonFunction: comparisonFunction,
  63502. generateStencil: generateStencil,
  63503. isCube: this.isCube
  63504. });
  63505. engine.setFrameBufferDepthStencilTexture(this);
  63506. };
  63507. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63508. if (size.ratio) {
  63509. this._sizeRatio = size.ratio;
  63510. this._size = {
  63511. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63512. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63513. };
  63514. }
  63515. else {
  63516. this._size = size;
  63517. }
  63518. };
  63519. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63520. get: function () {
  63521. return this._samples;
  63522. },
  63523. set: function (value) {
  63524. if (this._samples === value) {
  63525. return;
  63526. }
  63527. var scene = this.getScene();
  63528. if (!scene) {
  63529. return;
  63530. }
  63531. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63532. },
  63533. enumerable: true,
  63534. configurable: true
  63535. });
  63536. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63537. this._currentRefreshId = -1;
  63538. };
  63539. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63540. get: function () {
  63541. return this._refreshRate;
  63542. },
  63543. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63544. set: function (value) {
  63545. this._refreshRate = value;
  63546. this.resetRefreshCounter();
  63547. },
  63548. enumerable: true,
  63549. configurable: true
  63550. });
  63551. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63552. if (!this._postProcessManager) {
  63553. var scene = this.getScene();
  63554. if (!scene) {
  63555. return;
  63556. }
  63557. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63558. this._postProcesses = new Array();
  63559. }
  63560. this._postProcesses.push(postProcess);
  63561. this._postProcesses[0].autoClear = false;
  63562. };
  63563. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63564. if (!this._postProcesses) {
  63565. return;
  63566. }
  63567. if (dispose) {
  63568. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63569. var postProcess = _a[_i];
  63570. postProcess.dispose();
  63571. }
  63572. }
  63573. this._postProcesses = [];
  63574. };
  63575. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63576. if (!this._postProcesses) {
  63577. return;
  63578. }
  63579. var index = this._postProcesses.indexOf(postProcess);
  63580. if (index === -1) {
  63581. return;
  63582. }
  63583. this._postProcesses.splice(index, 1);
  63584. if (this._postProcesses.length > 0) {
  63585. this._postProcesses[0].autoClear = false;
  63586. }
  63587. };
  63588. RenderTargetTexture.prototype._shouldRender = function () {
  63589. if (this._currentRefreshId === -1) { // At least render once
  63590. this._currentRefreshId = 1;
  63591. return true;
  63592. }
  63593. if (this.refreshRate === this._currentRefreshId) {
  63594. this._currentRefreshId = 1;
  63595. return true;
  63596. }
  63597. this._currentRefreshId++;
  63598. return false;
  63599. };
  63600. RenderTargetTexture.prototype.getRenderSize = function () {
  63601. if (this._size.width) {
  63602. return this._size.width;
  63603. }
  63604. return this._size;
  63605. };
  63606. RenderTargetTexture.prototype.getRenderWidth = function () {
  63607. if (this._size.width) {
  63608. return this._size.width;
  63609. }
  63610. return this._size;
  63611. };
  63612. RenderTargetTexture.prototype.getRenderHeight = function () {
  63613. if (this._size.width) {
  63614. return this._size.height;
  63615. }
  63616. return this._size;
  63617. };
  63618. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63619. get: function () {
  63620. return true;
  63621. },
  63622. enumerable: true,
  63623. configurable: true
  63624. });
  63625. RenderTargetTexture.prototype.scale = function (ratio) {
  63626. var newSize = this.getRenderSize() * ratio;
  63627. this.resize(newSize);
  63628. };
  63629. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63630. if (this.isCube) {
  63631. return this._textureMatrix;
  63632. }
  63633. return _super.prototype.getReflectionTextureMatrix.call(this);
  63634. };
  63635. RenderTargetTexture.prototype.resize = function (size) {
  63636. this.releaseInternalTexture();
  63637. var scene = this.getScene();
  63638. if (!scene) {
  63639. return;
  63640. }
  63641. this._processSizeParameter(size);
  63642. if (this.isCube) {
  63643. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63644. }
  63645. else {
  63646. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63647. }
  63648. };
  63649. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63650. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63651. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63652. var scene = this.getScene();
  63653. if (!scene) {
  63654. return;
  63655. }
  63656. var engine = scene.getEngine();
  63657. if (this.useCameraPostProcesses !== undefined) {
  63658. useCameraPostProcess = this.useCameraPostProcesses;
  63659. }
  63660. if (this._waitingRenderList) {
  63661. this.renderList = [];
  63662. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63663. var id = this._waitingRenderList[index];
  63664. var mesh_1 = scene.getMeshByID(id);
  63665. if (mesh_1) {
  63666. this.renderList.push(mesh_1);
  63667. }
  63668. }
  63669. delete this._waitingRenderList;
  63670. }
  63671. // Is predicate defined?
  63672. if (this.renderListPredicate) {
  63673. if (this.renderList) {
  63674. this.renderList.splice(0); // Clear previous renderList
  63675. }
  63676. else {
  63677. this.renderList = [];
  63678. }
  63679. var scene = this.getScene();
  63680. if (!scene) {
  63681. return;
  63682. }
  63683. var sceneMeshes = scene.meshes;
  63684. for (var index = 0; index < sceneMeshes.length; index++) {
  63685. var mesh = sceneMeshes[index];
  63686. if (this.renderListPredicate(mesh)) {
  63687. this.renderList.push(mesh);
  63688. }
  63689. }
  63690. }
  63691. this.onBeforeBindObservable.notifyObservers(this);
  63692. // Set custom projection.
  63693. // Needs to be before binding to prevent changing the aspect ratio.
  63694. var camera;
  63695. if (this.activeCamera) {
  63696. camera = this.activeCamera;
  63697. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63698. if (this.activeCamera !== scene.activeCamera) {
  63699. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63700. }
  63701. }
  63702. else {
  63703. camera = scene.activeCamera;
  63704. if (camera) {
  63705. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63706. }
  63707. }
  63708. // Prepare renderingManager
  63709. this._renderingManager.reset();
  63710. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63711. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63712. var sceneRenderId = scene.getRenderId();
  63713. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63714. var mesh = currentRenderList[meshIndex];
  63715. if (mesh) {
  63716. if (!mesh.isReady(this.refreshRate === 0)) {
  63717. this.resetRefreshCounter();
  63718. continue;
  63719. }
  63720. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63721. var isMasked = void 0;
  63722. if (!this.renderList && camera) {
  63723. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63724. }
  63725. else {
  63726. isMasked = false;
  63727. }
  63728. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63729. mesh._activate(sceneRenderId);
  63730. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63731. var subMesh = mesh.subMeshes[subIndex];
  63732. scene._activeIndices.addCount(subMesh.indexCount, false);
  63733. this._renderingManager.dispatch(subMesh, mesh);
  63734. }
  63735. }
  63736. }
  63737. }
  63738. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63739. var particleSystem = scene.particleSystems[particleIndex];
  63740. var emitter = particleSystem.emitter;
  63741. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63742. continue;
  63743. }
  63744. if (currentRenderList.indexOf(emitter) >= 0) {
  63745. this._renderingManager.dispatchParticles(particleSystem);
  63746. }
  63747. }
  63748. if (this.isCube) {
  63749. for (var face = 0; face < 6; face++) {
  63750. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63751. scene.incrementRenderId();
  63752. scene.resetCachedMaterial();
  63753. }
  63754. }
  63755. else {
  63756. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63757. }
  63758. this.onAfterUnbindObservable.notifyObservers(this);
  63759. if (scene.activeCamera) {
  63760. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63761. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63762. }
  63763. engine.setViewport(scene.activeCamera.viewport);
  63764. }
  63765. scene.resetCachedMaterial();
  63766. };
  63767. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63768. var minimum = 128;
  63769. var x = renderDimension * scale;
  63770. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63771. // Ensure we don't exceed the render dimension (while staying POT)
  63772. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63773. };
  63774. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63775. var _this = this;
  63776. if (!this._texture) {
  63777. return;
  63778. }
  63779. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63780. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63781. });
  63782. };
  63783. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63784. var scene = this.getScene();
  63785. if (!scene) {
  63786. return;
  63787. }
  63788. var engine = scene.getEngine();
  63789. if (!this._texture) {
  63790. return;
  63791. }
  63792. // Bind
  63793. if (this._postProcessManager) {
  63794. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63795. }
  63796. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63797. if (this._texture) {
  63798. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63799. }
  63800. }
  63801. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63802. // Clear
  63803. if (this.onClearObservable.hasObservers()) {
  63804. this.onClearObservable.notifyObservers(engine);
  63805. }
  63806. else {
  63807. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63808. }
  63809. if (!this._doNotChangeAspectRatio) {
  63810. scene.updateTransformMatrix(true);
  63811. }
  63812. // Render
  63813. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63814. if (this._postProcessManager) {
  63815. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63816. }
  63817. else if (useCameraPostProcess) {
  63818. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63819. }
  63820. if (!this._doNotChangeAspectRatio) {
  63821. scene.updateTransformMatrix(true);
  63822. }
  63823. // Dump ?
  63824. if (dumpForDebug) {
  63825. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63826. }
  63827. // Unbind
  63828. if (!this.isCube || faceIndex === 5) {
  63829. if (this.isCube) {
  63830. if (faceIndex === 5) {
  63831. engine.generateMipMapsForCubemap(this._texture);
  63832. }
  63833. }
  63834. this.unbindFrameBuffer(engine, faceIndex);
  63835. }
  63836. else {
  63837. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63838. }
  63839. };
  63840. /**
  63841. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63842. * This allowed control for front to back rendering or reversly depending of the special needs.
  63843. *
  63844. * @param renderingGroupId The rendering group id corresponding to its index
  63845. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63846. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63847. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63848. */
  63849. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63850. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63851. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63852. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63853. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63854. };
  63855. /**
  63856. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63857. *
  63858. * @param renderingGroupId The rendering group id corresponding to its index
  63859. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63860. */
  63861. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63862. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63863. };
  63864. RenderTargetTexture.prototype.clone = function () {
  63865. var textureSize = this.getSize();
  63866. 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);
  63867. // Base texture
  63868. newTexture.hasAlpha = this.hasAlpha;
  63869. newTexture.level = this.level;
  63870. // RenderTarget Texture
  63871. newTexture.coordinatesMode = this.coordinatesMode;
  63872. if (this.renderList) {
  63873. newTexture.renderList = this.renderList.slice(0);
  63874. }
  63875. return newTexture;
  63876. };
  63877. RenderTargetTexture.prototype.serialize = function () {
  63878. if (!this.name) {
  63879. return null;
  63880. }
  63881. var serializationObject = _super.prototype.serialize.call(this);
  63882. serializationObject.renderTargetSize = this.getRenderSize();
  63883. serializationObject.renderList = [];
  63884. if (this.renderList) {
  63885. for (var index = 0; index < this.renderList.length; index++) {
  63886. serializationObject.renderList.push(this.renderList[index].id);
  63887. }
  63888. }
  63889. return serializationObject;
  63890. };
  63891. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63892. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63893. var objBuffer = this.getInternalTexture();
  63894. var scene = this.getScene();
  63895. if (objBuffer && scene) {
  63896. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63897. }
  63898. };
  63899. RenderTargetTexture.prototype.dispose = function () {
  63900. if (this._postProcessManager) {
  63901. this._postProcessManager.dispose();
  63902. this._postProcessManager = null;
  63903. }
  63904. this.clearPostProcesses(true);
  63905. if (this._resizeObserver) {
  63906. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63907. this._resizeObserver = null;
  63908. }
  63909. this.renderList = null;
  63910. // Remove from custom render targets
  63911. var scene = this.getScene();
  63912. if (!scene) {
  63913. return;
  63914. }
  63915. var index = scene.customRenderTargets.indexOf(this);
  63916. if (index >= 0) {
  63917. scene.customRenderTargets.splice(index, 1);
  63918. }
  63919. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63920. var camera = _a[_i];
  63921. index = camera.customRenderTargets.indexOf(this);
  63922. if (index >= 0) {
  63923. camera.customRenderTargets.splice(index, 1);
  63924. }
  63925. }
  63926. _super.prototype.dispose.call(this);
  63927. };
  63928. RenderTargetTexture.prototype._rebuild = function () {
  63929. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63930. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63931. }
  63932. if (this._postProcessManager) {
  63933. this._postProcessManager._rebuild();
  63934. }
  63935. };
  63936. /**
  63937. * Clear the info related to rendering groups preventing retention point in material dispose.
  63938. */
  63939. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63940. if (this._renderingManager) {
  63941. this._renderingManager.freeRenderingGroups();
  63942. }
  63943. };
  63944. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63945. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63946. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63947. return RenderTargetTexture;
  63948. }(BABYLON.Texture));
  63949. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63950. })(BABYLON || (BABYLON = {}));
  63951. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63952. var BABYLON;
  63953. (function (BABYLON) {
  63954. ;
  63955. var MultiRenderTarget = /** @class */ (function (_super) {
  63956. __extends(MultiRenderTarget, _super);
  63957. function MultiRenderTarget(name, size, count, scene, options) {
  63958. var _this = this;
  63959. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63960. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63961. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63962. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63963. _this._engine = scene.getEngine();
  63964. if (!_this.isSupported) {
  63965. _this.dispose();
  63966. return;
  63967. }
  63968. var types = [];
  63969. var samplingModes = [];
  63970. for (var i = 0; i < count; i++) {
  63971. if (options && options.types && options.types[i] !== undefined) {
  63972. types.push(options.types[i]);
  63973. }
  63974. else {
  63975. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63976. }
  63977. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63978. samplingModes.push(options.samplingModes[i]);
  63979. }
  63980. else {
  63981. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63982. }
  63983. }
  63984. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63985. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63986. _this._size = size;
  63987. _this._multiRenderTargetOptions = {
  63988. samplingModes: samplingModes,
  63989. generateMipMaps: generateMipMaps,
  63990. generateDepthBuffer: generateDepthBuffer,
  63991. generateStencilBuffer: generateStencilBuffer,
  63992. generateDepthTexture: generateDepthTexture,
  63993. types: types,
  63994. textureCount: count
  63995. };
  63996. _this._createInternalTextures();
  63997. _this._createTextures();
  63998. return _this;
  63999. }
  64000. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64001. get: function () {
  64002. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64003. },
  64004. enumerable: true,
  64005. configurable: true
  64006. });
  64007. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64008. get: function () {
  64009. return this._textures;
  64010. },
  64011. enumerable: true,
  64012. configurable: true
  64013. });
  64014. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64015. get: function () {
  64016. return this._textures[this._textures.length - 1];
  64017. },
  64018. enumerable: true,
  64019. configurable: true
  64020. });
  64021. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64022. set: function (wrap) {
  64023. if (this._textures) {
  64024. for (var i = 0; i < this._textures.length; i++) {
  64025. this._textures[i].wrapU = wrap;
  64026. }
  64027. }
  64028. },
  64029. enumerable: true,
  64030. configurable: true
  64031. });
  64032. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64033. set: function (wrap) {
  64034. if (this._textures) {
  64035. for (var i = 0; i < this._textures.length; i++) {
  64036. this._textures[i].wrapV = wrap;
  64037. }
  64038. }
  64039. },
  64040. enumerable: true,
  64041. configurable: true
  64042. });
  64043. MultiRenderTarget.prototype._rebuild = function () {
  64044. this.releaseInternalTextures();
  64045. this._createInternalTextures();
  64046. for (var i = 0; i < this._internalTextures.length; i++) {
  64047. var texture = this._textures[i];
  64048. texture._texture = this._internalTextures[i];
  64049. }
  64050. // Keeps references to frame buffer and stencil/depth buffer
  64051. this._texture = this._internalTextures[0];
  64052. };
  64053. MultiRenderTarget.prototype._createInternalTextures = function () {
  64054. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64055. };
  64056. MultiRenderTarget.prototype._createTextures = function () {
  64057. this._textures = [];
  64058. for (var i = 0; i < this._internalTextures.length; i++) {
  64059. var texture = new BABYLON.Texture(null, this.getScene());
  64060. texture._texture = this._internalTextures[i];
  64061. this._textures.push(texture);
  64062. }
  64063. // Keeps references to frame buffer and stencil/depth buffer
  64064. this._texture = this._internalTextures[0];
  64065. };
  64066. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64067. get: function () {
  64068. return this._samples;
  64069. },
  64070. set: function (value) {
  64071. if (this._samples === value) {
  64072. return;
  64073. }
  64074. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64075. },
  64076. enumerable: true,
  64077. configurable: true
  64078. });
  64079. MultiRenderTarget.prototype.resize = function (size) {
  64080. this.releaseInternalTextures();
  64081. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64082. this._createInternalTextures();
  64083. };
  64084. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64085. var _this = this;
  64086. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64087. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64088. });
  64089. };
  64090. MultiRenderTarget.prototype.dispose = function () {
  64091. this.releaseInternalTextures();
  64092. _super.prototype.dispose.call(this);
  64093. };
  64094. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64095. if (!this._internalTextures) {
  64096. return;
  64097. }
  64098. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64099. if (this._internalTextures[i] !== undefined) {
  64100. this._internalTextures[i].dispose();
  64101. this._internalTextures.splice(i, 1);
  64102. }
  64103. }
  64104. };
  64105. return MultiRenderTarget;
  64106. }(BABYLON.RenderTargetTexture));
  64107. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64108. })(BABYLON || (BABYLON = {}));
  64109. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64110. var BABYLON;
  64111. (function (BABYLON) {
  64112. var MirrorTexture = /** @class */ (function (_super) {
  64113. __extends(MirrorTexture, _super);
  64114. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64115. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64117. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64118. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64119. _this.scene = scene;
  64120. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64121. _this._transformMatrix = BABYLON.Matrix.Zero();
  64122. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64123. _this._adaptiveBlurKernel = 0;
  64124. _this._blurKernelX = 0;
  64125. _this._blurKernelY = 0;
  64126. _this._blurRatio = 1.0;
  64127. _this.ignoreCameraViewport = true;
  64128. _this._updateGammaSpace();
  64129. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64130. _this._updateGammaSpace;
  64131. });
  64132. _this.onBeforeRenderObservable.add(function () {
  64133. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64134. _this._savedViewMatrix = scene.getViewMatrix();
  64135. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64136. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64137. scene.clipPlane = _this.mirrorPlane;
  64138. scene.getEngine().cullBackFaces = false;
  64139. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64140. });
  64141. _this.onAfterRenderObservable.add(function () {
  64142. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64143. scene.getEngine().cullBackFaces = true;
  64144. scene._mirroredCameraPosition = null;
  64145. delete scene.clipPlane;
  64146. });
  64147. return _this;
  64148. }
  64149. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64150. get: function () {
  64151. return this._blurRatio;
  64152. },
  64153. set: function (value) {
  64154. if (this._blurRatio === value) {
  64155. return;
  64156. }
  64157. this._blurRatio = value;
  64158. this._preparePostProcesses();
  64159. },
  64160. enumerable: true,
  64161. configurable: true
  64162. });
  64163. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64164. set: function (value) {
  64165. this._adaptiveBlurKernel = value;
  64166. this._autoComputeBlurKernel();
  64167. },
  64168. enumerable: true,
  64169. configurable: true
  64170. });
  64171. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64172. set: function (value) {
  64173. this.blurKernelX = value;
  64174. this.blurKernelY = value;
  64175. },
  64176. enumerable: true,
  64177. configurable: true
  64178. });
  64179. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64180. get: function () {
  64181. return this._blurKernelX;
  64182. },
  64183. set: function (value) {
  64184. if (this._blurKernelX === value) {
  64185. return;
  64186. }
  64187. this._blurKernelX = value;
  64188. this._preparePostProcesses();
  64189. },
  64190. enumerable: true,
  64191. configurable: true
  64192. });
  64193. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64194. get: function () {
  64195. return this._blurKernelY;
  64196. },
  64197. set: function (value) {
  64198. if (this._blurKernelY === value) {
  64199. return;
  64200. }
  64201. this._blurKernelY = value;
  64202. this._preparePostProcesses();
  64203. },
  64204. enumerable: true,
  64205. configurable: true
  64206. });
  64207. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64208. var engine = this.getScene().getEngine();
  64209. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64210. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64211. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64212. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64213. };
  64214. MirrorTexture.prototype._onRatioRescale = function () {
  64215. if (this._sizeRatio) {
  64216. this.resize(this._initialSizeParameter);
  64217. if (!this._adaptiveBlurKernel) {
  64218. this._preparePostProcesses();
  64219. }
  64220. }
  64221. if (this._adaptiveBlurKernel) {
  64222. this._autoComputeBlurKernel();
  64223. }
  64224. };
  64225. MirrorTexture.prototype._updateGammaSpace = function () {
  64226. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64227. };
  64228. MirrorTexture.prototype._preparePostProcesses = function () {
  64229. this.clearPostProcesses(true);
  64230. if (this._blurKernelX && this._blurKernelY) {
  64231. var engine = this.getScene().getEngine();
  64232. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64233. 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);
  64234. this._blurX.autoClear = false;
  64235. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64236. this._blurX.inputTexture = this._texture;
  64237. }
  64238. else {
  64239. this._blurX.alwaysForcePOT = true;
  64240. }
  64241. 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);
  64242. this._blurY.autoClear = false;
  64243. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64244. this.addPostProcess(this._blurX);
  64245. this.addPostProcess(this._blurY);
  64246. }
  64247. else {
  64248. if (this._blurY) {
  64249. this.removePostProcess(this._blurY);
  64250. this._blurY.dispose();
  64251. this._blurY = null;
  64252. }
  64253. if (this._blurX) {
  64254. this.removePostProcess(this._blurX);
  64255. this._blurX.dispose();
  64256. this._blurX = null;
  64257. }
  64258. }
  64259. };
  64260. MirrorTexture.prototype.clone = function () {
  64261. var scene = this.getScene();
  64262. if (!scene) {
  64263. return this;
  64264. }
  64265. var textureSize = this.getSize();
  64266. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64267. // Base texture
  64268. newTexture.hasAlpha = this.hasAlpha;
  64269. newTexture.level = this.level;
  64270. // Mirror Texture
  64271. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64272. if (this.renderList) {
  64273. newTexture.renderList = this.renderList.slice(0);
  64274. }
  64275. return newTexture;
  64276. };
  64277. MirrorTexture.prototype.serialize = function () {
  64278. if (!this.name) {
  64279. return null;
  64280. }
  64281. var serializationObject = _super.prototype.serialize.call(this);
  64282. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64283. return serializationObject;
  64284. };
  64285. MirrorTexture.prototype.dispose = function () {
  64286. _super.prototype.dispose.call(this);
  64287. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64288. };
  64289. return MirrorTexture;
  64290. }(BABYLON.RenderTargetTexture));
  64291. BABYLON.MirrorTexture = MirrorTexture;
  64292. })(BABYLON || (BABYLON = {}));
  64293. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64294. var BABYLON;
  64295. (function (BABYLON) {
  64296. /**
  64297. * Creates a refraction texture used by refraction channel of the standard material.
  64298. * @param name the texture name
  64299. * @param size size of the underlying texture
  64300. * @param scene root scene
  64301. */
  64302. var RefractionTexture = /** @class */ (function (_super) {
  64303. __extends(RefractionTexture, _super);
  64304. function RefractionTexture(name, size, scene, generateMipMaps) {
  64305. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64306. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64307. _this.depth = 2.0;
  64308. _this.onBeforeRenderObservable.add(function () {
  64309. scene.clipPlane = _this.refractionPlane;
  64310. });
  64311. _this.onAfterRenderObservable.add(function () {
  64312. delete scene.clipPlane;
  64313. });
  64314. return _this;
  64315. }
  64316. RefractionTexture.prototype.clone = function () {
  64317. var scene = this.getScene();
  64318. if (!scene) {
  64319. return this;
  64320. }
  64321. var textureSize = this.getSize();
  64322. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64323. // Base texture
  64324. newTexture.hasAlpha = this.hasAlpha;
  64325. newTexture.level = this.level;
  64326. // Refraction Texture
  64327. newTexture.refractionPlane = this.refractionPlane.clone();
  64328. if (this.renderList) {
  64329. newTexture.renderList = this.renderList.slice(0);
  64330. }
  64331. newTexture.depth = this.depth;
  64332. return newTexture;
  64333. };
  64334. RefractionTexture.prototype.serialize = function () {
  64335. if (!this.name) {
  64336. return null;
  64337. }
  64338. var serializationObject = _super.prototype.serialize.call(this);
  64339. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64340. serializationObject.depth = this.depth;
  64341. return serializationObject;
  64342. };
  64343. return RefractionTexture;
  64344. }(BABYLON.RenderTargetTexture));
  64345. BABYLON.RefractionTexture = RefractionTexture;
  64346. })(BABYLON || (BABYLON = {}));
  64347. //# sourceMappingURL=babylon.refractionTexture.js.map
  64348. var BABYLON;
  64349. (function (BABYLON) {
  64350. /**
  64351. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64352. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64353. */
  64354. var DynamicTexture = /** @class */ (function (_super) {
  64355. __extends(DynamicTexture, _super);
  64356. /**
  64357. * Creates a {BABYLON.DynamicTexture}
  64358. * @param name defines the name of the texture
  64359. * @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
  64360. * @param scene defines the scene where you want the texture
  64361. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64362. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64363. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64364. */
  64365. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64366. if (scene === void 0) { scene = null; }
  64367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64368. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64369. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64370. _this.name = name;
  64371. _this._engine = _this.getScene().getEngine();
  64372. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64373. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64374. _this._generateMipMaps = generateMipMaps;
  64375. if (options.getContext) {
  64376. _this._canvas = options;
  64377. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64378. }
  64379. else {
  64380. _this._canvas = document.createElement("canvas");
  64381. if (options.width || options.width === 0) {
  64382. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64383. }
  64384. else {
  64385. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64386. }
  64387. }
  64388. var textureSize = _this.getSize();
  64389. _this._canvas.width = textureSize.width;
  64390. _this._canvas.height = textureSize.height;
  64391. _this._context = _this._canvas.getContext("2d");
  64392. return _this;
  64393. }
  64394. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64395. /**
  64396. * Gets the current state of canRescale
  64397. */
  64398. get: function () {
  64399. return true;
  64400. },
  64401. enumerable: true,
  64402. configurable: true
  64403. });
  64404. DynamicTexture.prototype._recreate = function (textureSize) {
  64405. this._canvas.width = textureSize.width;
  64406. this._canvas.height = textureSize.height;
  64407. this.releaseInternalTexture();
  64408. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64409. };
  64410. /**
  64411. * Scales the texture
  64412. * @param ratio the scale factor to apply to both width and height
  64413. */
  64414. DynamicTexture.prototype.scale = function (ratio) {
  64415. var textureSize = this.getSize();
  64416. textureSize.width *= ratio;
  64417. textureSize.height *= ratio;
  64418. this._recreate(textureSize);
  64419. };
  64420. /**
  64421. * Resizes the texture
  64422. * @param width the new width
  64423. * @param height the new height
  64424. */
  64425. DynamicTexture.prototype.scaleTo = function (width, height) {
  64426. var textureSize = this.getSize();
  64427. textureSize.width = width;
  64428. textureSize.height = height;
  64429. this._recreate(textureSize);
  64430. };
  64431. /**
  64432. * Gets the context of the canvas used by the texture
  64433. * @returns the canvas context of the dynamic texture
  64434. */
  64435. DynamicTexture.prototype.getContext = function () {
  64436. return this._context;
  64437. };
  64438. /**
  64439. * Clears the texture
  64440. */
  64441. DynamicTexture.prototype.clear = function () {
  64442. var size = this.getSize();
  64443. this._context.fillRect(0, 0, size.width, size.height);
  64444. };
  64445. /**
  64446. * Updates the texture
  64447. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64448. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64449. */
  64450. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64451. if (premulAlpha === void 0) { premulAlpha = false; }
  64452. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64453. };
  64454. /**
  64455. * Draws text onto the texture
  64456. * @param text defines the text to be drawn
  64457. * @param x defines the placement of the text from the left
  64458. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64459. * @param font defines the font to be used with font-style, font-size, font-name
  64460. * @param color defines the color used for the text
  64461. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64462. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64463. * @param update defines whether texture is immediately update (default is true)
  64464. */
  64465. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64466. if (update === void 0) { update = true; }
  64467. var size = this.getSize();
  64468. if (clearColor) {
  64469. this._context.fillStyle = clearColor;
  64470. this._context.fillRect(0, 0, size.width, size.height);
  64471. }
  64472. this._context.font = font;
  64473. if (x === null || x === undefined) {
  64474. var textSize = this._context.measureText(text);
  64475. x = (size.width - textSize.width) / 2;
  64476. }
  64477. if (y === null || y === undefined) {
  64478. var fontSize = parseInt((font.replace(/\D/g, '')));
  64479. y = (size.height / 2) + (fontSize / 3.65);
  64480. }
  64481. this._context.fillStyle = color;
  64482. this._context.fillText(text, x, y);
  64483. if (update) {
  64484. this.update(invertY);
  64485. }
  64486. };
  64487. /**
  64488. * Clones the texture
  64489. * @returns the clone of the texture.
  64490. */
  64491. DynamicTexture.prototype.clone = function () {
  64492. var scene = this.getScene();
  64493. if (!scene) {
  64494. return this;
  64495. }
  64496. var textureSize = this.getSize();
  64497. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64498. // Base texture
  64499. newTexture.hasAlpha = this.hasAlpha;
  64500. newTexture.level = this.level;
  64501. // Dynamic Texture
  64502. newTexture.wrapU = this.wrapU;
  64503. newTexture.wrapV = this.wrapV;
  64504. return newTexture;
  64505. };
  64506. /** @hidden */
  64507. DynamicTexture.prototype._rebuild = function () {
  64508. this.update();
  64509. };
  64510. return DynamicTexture;
  64511. }(BABYLON.Texture));
  64512. BABYLON.DynamicTexture = DynamicTexture;
  64513. })(BABYLON || (BABYLON = {}));
  64514. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64515. var BABYLON;
  64516. (function (BABYLON) {
  64517. var VideoTexture = /** @class */ (function (_super) {
  64518. __extends(VideoTexture, _super);
  64519. /**
  64520. * Creates a video texture.
  64521. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64522. * @param {string | null} name optional name, will detect from video source, if not defined
  64523. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64524. * @param {BABYLON.Scene} scene is obviously the current scene.
  64525. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64526. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64527. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64528. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64529. */
  64530. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64531. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64532. if (invertY === void 0) { invertY = false; }
  64533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64534. if (settings === void 0) { settings = {
  64535. autoPlay: true,
  64536. loop: true,
  64537. autoUpdateTexture: true,
  64538. }; }
  64539. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64540. _this._onUserActionRequestedObservable = null;
  64541. _this._stillImageCaptured = false;
  64542. _this._createInternalTexture = function () {
  64543. if (_this._texture != null) {
  64544. return;
  64545. }
  64546. if (!_this._engine.needPOTTextures ||
  64547. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64548. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64549. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64550. }
  64551. else {
  64552. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64553. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64554. _this._generateMipMaps = false;
  64555. }
  64556. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64557. if (!_this.video.autoplay) {
  64558. var oldHandler_1 = _this.video.onplaying;
  64559. var error_1 = false;
  64560. _this.video.onplaying = function () {
  64561. _this.video.onplaying = oldHandler_1;
  64562. _this._texture.isReady = true;
  64563. _this._updateInternalTexture();
  64564. if (!error_1) {
  64565. _this.video.pause();
  64566. }
  64567. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64568. _this.onLoadObservable.notifyObservers(_this);
  64569. }
  64570. };
  64571. var playing = _this.video.play();
  64572. if (playing) {
  64573. playing.then(function () {
  64574. // Everything is good.
  64575. })
  64576. .catch(function () {
  64577. error_1 = true;
  64578. // On Chrome for instance, new policies might prevent playing without user interaction.
  64579. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64580. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64581. }
  64582. });
  64583. }
  64584. else {
  64585. _this.video.onplaying = oldHandler_1;
  64586. _this._texture.isReady = true;
  64587. _this._updateInternalTexture();
  64588. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64589. _this.onLoadObservable.notifyObservers(_this);
  64590. }
  64591. }
  64592. }
  64593. else {
  64594. _this._texture.isReady = true;
  64595. _this._updateInternalTexture();
  64596. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64597. _this.onLoadObservable.notifyObservers(_this);
  64598. }
  64599. }
  64600. };
  64601. _this.reset = function () {
  64602. if (_this._texture == null) {
  64603. return;
  64604. }
  64605. _this._texture.dispose();
  64606. _this._texture = null;
  64607. };
  64608. _this._updateInternalTexture = function (e) {
  64609. if (_this._texture == null || !_this._texture.isReady) {
  64610. return;
  64611. }
  64612. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64613. return;
  64614. }
  64615. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64616. };
  64617. _this._engine = _this.getScene().getEngine();
  64618. _this._generateMipMaps = generateMipMaps;
  64619. _this._samplingMode = samplingMode;
  64620. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64621. _this.name = name || _this._getName(src);
  64622. _this.video = _this._getVideo(src);
  64623. if (settings.poster) {
  64624. _this.video.poster = settings.poster;
  64625. }
  64626. if (settings.autoPlay !== undefined) {
  64627. _this.video.autoplay = settings.autoPlay;
  64628. }
  64629. if (settings.loop !== undefined) {
  64630. _this.video.loop = settings.loop;
  64631. }
  64632. _this.video.setAttribute("playsinline", "");
  64633. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64634. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64635. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64636. _this.video.addEventListener("emptied", _this.reset);
  64637. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64638. _this._createInternalTexture();
  64639. }
  64640. return _this;
  64641. }
  64642. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64643. get: function () {
  64644. if (!this._onUserActionRequestedObservable) {
  64645. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64646. }
  64647. return this._onUserActionRequestedObservable;
  64648. },
  64649. enumerable: true,
  64650. configurable: true
  64651. });
  64652. VideoTexture.prototype._getName = function (src) {
  64653. if (src instanceof HTMLVideoElement) {
  64654. return src.currentSrc;
  64655. }
  64656. if (typeof src === "object") {
  64657. return src.toString();
  64658. }
  64659. return src;
  64660. };
  64661. ;
  64662. VideoTexture.prototype._getVideo = function (src) {
  64663. if (src instanceof HTMLVideoElement) {
  64664. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64665. return src;
  64666. }
  64667. var video = document.createElement("video");
  64668. if (typeof src === "string") {
  64669. BABYLON.Tools.SetCorsBehavior(src, video);
  64670. video.src = src;
  64671. }
  64672. else {
  64673. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64674. src.forEach(function (url) {
  64675. var source = document.createElement("source");
  64676. source.src = url;
  64677. video.appendChild(source);
  64678. });
  64679. }
  64680. return video;
  64681. };
  64682. ;
  64683. /**
  64684. * Internal method to initiate `update`.
  64685. */
  64686. VideoTexture.prototype._rebuild = function () {
  64687. this.update();
  64688. };
  64689. /**
  64690. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64691. */
  64692. VideoTexture.prototype.update = function () {
  64693. if (!this.autoUpdateTexture) {
  64694. // Expecting user to call `updateTexture` manually
  64695. return;
  64696. }
  64697. this.updateTexture(true);
  64698. };
  64699. /**
  64700. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64701. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64702. */
  64703. VideoTexture.prototype.updateTexture = function (isVisible) {
  64704. if (!isVisible) {
  64705. return;
  64706. }
  64707. if (this.video.paused && this._stillImageCaptured) {
  64708. return;
  64709. }
  64710. this._stillImageCaptured = true;
  64711. this._updateInternalTexture();
  64712. };
  64713. /**
  64714. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64715. * @param url New url.
  64716. */
  64717. VideoTexture.prototype.updateURL = function (url) {
  64718. this.video.src = url;
  64719. };
  64720. VideoTexture.prototype.dispose = function () {
  64721. _super.prototype.dispose.call(this);
  64722. if (this._onUserActionRequestedObservable) {
  64723. this._onUserActionRequestedObservable.clear();
  64724. this._onUserActionRequestedObservable = null;
  64725. }
  64726. this.video.removeEventListener("canplay", this._createInternalTexture);
  64727. this.video.removeEventListener("paused", this._updateInternalTexture);
  64728. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64729. this.video.removeEventListener("emptied", this.reset);
  64730. this.video.pause();
  64731. };
  64732. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64733. var video = document.createElement("video");
  64734. video.setAttribute('autoplay', '');
  64735. video.setAttribute('muted', '');
  64736. video.setAttribute('playsinline', '');
  64737. var constraintsDeviceId;
  64738. if (constraints && constraints.deviceId) {
  64739. constraintsDeviceId = {
  64740. exact: constraints.deviceId,
  64741. };
  64742. }
  64743. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64744. if (navigator.mediaDevices) {
  64745. navigator.mediaDevices.getUserMedia({ video: constraints })
  64746. .then(function (stream) {
  64747. if (video.mozSrcObject !== undefined) {
  64748. // hack for Firefox < 19
  64749. video.mozSrcObject = stream;
  64750. }
  64751. else {
  64752. video.srcObject = stream;
  64753. }
  64754. var onPlaying = function () {
  64755. if (onReady) {
  64756. onReady(new VideoTexture("video", video, scene, true, true));
  64757. }
  64758. video.removeEventListener("playing", onPlaying);
  64759. };
  64760. video.addEventListener("playing", onPlaying);
  64761. video.play();
  64762. })
  64763. .catch(function (err) {
  64764. BABYLON.Tools.Error(err.name);
  64765. });
  64766. }
  64767. else {
  64768. navigator.getUserMedia =
  64769. navigator.getUserMedia ||
  64770. navigator.webkitGetUserMedia ||
  64771. navigator.mozGetUserMedia ||
  64772. navigator.msGetUserMedia;
  64773. if (navigator.getUserMedia) {
  64774. navigator.getUserMedia({
  64775. video: {
  64776. deviceId: constraintsDeviceId,
  64777. width: {
  64778. min: (constraints && constraints.minWidth) || 256,
  64779. max: (constraints && constraints.maxWidth) || 640,
  64780. },
  64781. height: {
  64782. min: (constraints && constraints.minHeight) || 256,
  64783. max: (constraints && constraints.maxHeight) || 480,
  64784. },
  64785. },
  64786. }, function (stream) {
  64787. if (video.mozSrcObject !== undefined) {
  64788. // hack for Firefox < 19
  64789. video.mozSrcObject = stream;
  64790. }
  64791. else {
  64792. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64793. }
  64794. video.play();
  64795. if (onReady) {
  64796. onReady(new VideoTexture("video", video, scene, true, true));
  64797. }
  64798. }, function (e) {
  64799. BABYLON.Tools.Error(e.name);
  64800. });
  64801. }
  64802. }
  64803. };
  64804. return VideoTexture;
  64805. }(BABYLON.Texture));
  64806. BABYLON.VideoTexture = VideoTexture;
  64807. })(BABYLON || (BABYLON = {}));
  64808. //# sourceMappingURL=babylon.videoTexture.js.map
  64809. var BABYLON;
  64810. (function (BABYLON) {
  64811. var RawTexture = /** @class */ (function (_super) {
  64812. __extends(RawTexture, _super);
  64813. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64814. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64815. if (invertY === void 0) { invertY = false; }
  64816. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64817. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64818. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64819. _this.format = format;
  64820. _this._engine = scene.getEngine();
  64821. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64822. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64823. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64824. return _this;
  64825. }
  64826. RawTexture.prototype.update = function (data) {
  64827. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64828. };
  64829. // Statics
  64830. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64831. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64832. if (invertY === void 0) { invertY = false; }
  64833. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64834. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64835. };
  64836. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64837. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64838. if (invertY === void 0) { invertY = false; }
  64839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64840. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64841. };
  64842. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64843. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64844. if (invertY === void 0) { invertY = false; }
  64845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64846. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64847. };
  64848. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64849. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64850. if (invertY === void 0) { invertY = false; }
  64851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64852. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64853. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64854. };
  64855. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64856. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64857. if (invertY === void 0) { invertY = false; }
  64858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64859. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64860. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64861. };
  64862. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64863. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64864. if (invertY === void 0) { invertY = false; }
  64865. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64866. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64867. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  64868. };
  64869. return RawTexture;
  64870. }(BABYLON.Texture));
  64871. BABYLON.RawTexture = RawTexture;
  64872. })(BABYLON || (BABYLON = {}));
  64873. //# sourceMappingURL=babylon.rawTexture.js.map
  64874. var BABYLON;
  64875. (function (BABYLON) {
  64876. /**
  64877. * Class used to store 3D textures containing user data
  64878. */
  64879. var RawTexture3D = /** @class */ (function (_super) {
  64880. __extends(RawTexture3D, _super);
  64881. /**
  64882. * Create a new RawTexture3D
  64883. * @param data defines the data of the texture
  64884. * @param width defines the width of the texture
  64885. * @param height defines the height of the texture
  64886. * @param depth defines the depth of the texture
  64887. * @param format defines the texture format to use
  64888. * @param scene defines the hosting scene
  64889. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64890. * @param invertY defines if texture must be stored with Y axis inverted
  64891. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64892. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64893. */
  64894. function RawTexture3D(data, width, height, depth,
  64895. /** Gets or sets the texture format to use */
  64896. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64897. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64898. if (invertY === void 0) { invertY = false; }
  64899. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64900. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64901. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64902. _this.format = format;
  64903. _this._engine = scene.getEngine();
  64904. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64905. _this.is3D = true;
  64906. return _this;
  64907. }
  64908. /**
  64909. * Update the texture with new data
  64910. * @param data defines the data to store in the texture
  64911. */
  64912. RawTexture3D.prototype.update = function (data) {
  64913. if (!this._texture) {
  64914. return;
  64915. }
  64916. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64917. };
  64918. return RawTexture3D;
  64919. }(BABYLON.Texture));
  64920. BABYLON.RawTexture3D = RawTexture3D;
  64921. })(BABYLON || (BABYLON = {}));
  64922. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64923. var BABYLON;
  64924. (function (BABYLON) {
  64925. /**
  64926. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64927. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64928. */
  64929. var PostProcessManager = /** @class */ (function () {
  64930. /**
  64931. * Creates a new instance PostProcess
  64932. * @param scene The scene that the post process is associated with.
  64933. */
  64934. function PostProcessManager(scene) {
  64935. this._vertexBuffers = {};
  64936. this._scene = scene;
  64937. }
  64938. PostProcessManager.prototype._prepareBuffers = function () {
  64939. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64940. return;
  64941. }
  64942. // VBO
  64943. var vertices = [];
  64944. vertices.push(1, 1);
  64945. vertices.push(-1, 1);
  64946. vertices.push(-1, -1);
  64947. vertices.push(1, -1);
  64948. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64949. this._buildIndexBuffer();
  64950. };
  64951. PostProcessManager.prototype._buildIndexBuffer = function () {
  64952. // Indices
  64953. var indices = [];
  64954. indices.push(0);
  64955. indices.push(1);
  64956. indices.push(2);
  64957. indices.push(0);
  64958. indices.push(2);
  64959. indices.push(3);
  64960. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64961. };
  64962. /**
  64963. * Rebuilds the vertex buffers of the manager.
  64964. */
  64965. PostProcessManager.prototype._rebuild = function () {
  64966. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64967. if (!vb) {
  64968. return;
  64969. }
  64970. vb._rebuild();
  64971. this._buildIndexBuffer();
  64972. };
  64973. // Methods
  64974. /**
  64975. * Prepares a frame to be run through a post process.
  64976. * @param sourceTexture The input texture to the post procesess. (default: null)
  64977. * @param postProcesses An array of post processes to be run. (default: null)
  64978. * @returns True if the post processes were able to be run.
  64979. */
  64980. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64981. if (sourceTexture === void 0) { sourceTexture = null; }
  64982. if (postProcesses === void 0) { postProcesses = null; }
  64983. var camera = this._scene.activeCamera;
  64984. if (!camera) {
  64985. return false;
  64986. }
  64987. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64988. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64989. return false;
  64990. }
  64991. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64992. return true;
  64993. };
  64994. /**
  64995. * Manually render a set of post processes to a texture.
  64996. * @param postProcesses An array of post processes to be run.
  64997. * @param targetTexture The target texture to render to.
  64998. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64999. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65000. * @param lodLevel defines which lod of the texture to render to
  65001. */
  65002. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65003. if (targetTexture === void 0) { targetTexture = null; }
  65004. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65005. if (faceIndex === void 0) { faceIndex = 0; }
  65006. if (lodLevel === void 0) { lodLevel = 0; }
  65007. var engine = this._scene.getEngine();
  65008. for (var index = 0; index < postProcesses.length; index++) {
  65009. if (index < postProcesses.length - 1) {
  65010. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65011. }
  65012. else {
  65013. if (targetTexture) {
  65014. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65015. }
  65016. else {
  65017. engine.restoreDefaultFramebuffer();
  65018. }
  65019. }
  65020. var pp = postProcesses[index];
  65021. var effect = pp.apply();
  65022. if (effect) {
  65023. pp.onBeforeRenderObservable.notifyObservers(effect);
  65024. // VBOs
  65025. this._prepareBuffers();
  65026. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65027. // Draw order
  65028. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65029. pp.onAfterRenderObservable.notifyObservers(effect);
  65030. }
  65031. }
  65032. // Restore depth buffer
  65033. engine.setDepthBuffer(true);
  65034. engine.setDepthWrite(true);
  65035. };
  65036. /**
  65037. * Finalize the result of the output of the postprocesses.
  65038. * @param doNotPresent If true the result will not be displayed to the screen.
  65039. * @param targetTexture The target texture to render to.
  65040. * @param faceIndex The index of the face to bind the target texture to.
  65041. * @param postProcesses The array of post processes to render.
  65042. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65043. */
  65044. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65045. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65046. var camera = this._scene.activeCamera;
  65047. if (!camera) {
  65048. return;
  65049. }
  65050. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65051. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65052. return;
  65053. }
  65054. var engine = this._scene.getEngine();
  65055. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65056. var pp = postProcesses[index];
  65057. if (index < len - 1) {
  65058. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65059. }
  65060. else {
  65061. if (targetTexture) {
  65062. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65063. pp._outputTexture = targetTexture;
  65064. }
  65065. else {
  65066. engine.restoreDefaultFramebuffer();
  65067. pp._outputTexture = null;
  65068. }
  65069. }
  65070. if (doNotPresent) {
  65071. break;
  65072. }
  65073. var effect = pp.apply();
  65074. if (effect) {
  65075. pp.onBeforeRenderObservable.notifyObservers(effect);
  65076. // VBOs
  65077. this._prepareBuffers();
  65078. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65079. // Draw order
  65080. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65081. pp.onAfterRenderObservable.notifyObservers(effect);
  65082. }
  65083. }
  65084. // Restore states
  65085. engine.setDepthBuffer(true);
  65086. engine.setDepthWrite(true);
  65087. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65088. };
  65089. /**
  65090. * Disposes of the post process manager.
  65091. */
  65092. PostProcessManager.prototype.dispose = function () {
  65093. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65094. if (buffer) {
  65095. buffer.dispose();
  65096. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65097. }
  65098. if (this._indexBuffer) {
  65099. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65100. this._indexBuffer = null;
  65101. }
  65102. };
  65103. return PostProcessManager;
  65104. }());
  65105. BABYLON.PostProcessManager = PostProcessManager;
  65106. })(BABYLON || (BABYLON = {}));
  65107. //# sourceMappingURL=babylon.postProcessManager.js.map
  65108. var BABYLON;
  65109. (function (BABYLON) {
  65110. /**
  65111. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65112. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65113. */
  65114. var PostProcess = /** @class */ (function () {
  65115. /**
  65116. * Creates a new instance PostProcess
  65117. * @param name The name of the PostProcess.
  65118. * @param fragmentUrl The url of the fragment shader to be used.
  65119. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65120. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65121. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65122. * @param camera The camera to apply the render pass to.
  65123. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65124. * @param engine The engine which the post process will be applied. (default: current engine)
  65125. * @param reusable If the post process can be reused on the same frame. (default: false)
  65126. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65127. * @param textureType Type of textures used when performing the post process. (default: 0)
  65128. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65129. * @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
  65130. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65131. */
  65132. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65134. if (defines === void 0) { defines = null; }
  65135. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65136. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65137. if (blockCompilation === void 0) { blockCompilation = false; }
  65138. this.name = name;
  65139. /**
  65140. * Width of the texture to apply the post process on
  65141. */
  65142. this.width = -1;
  65143. /**
  65144. * Height of the texture to apply the post process on
  65145. */
  65146. this.height = -1;
  65147. /**
  65148. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65149. */
  65150. this._outputTexture = null;
  65151. /**
  65152. * If the buffer needs to be cleared before applying the post process. (default: true)
  65153. * Should be set to false if shader will overwrite all previous pixels.
  65154. */
  65155. this.autoClear = true;
  65156. /**
  65157. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65158. */
  65159. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65160. /**
  65161. * Animations to be used for the post processing
  65162. */
  65163. this.animations = new Array();
  65164. /**
  65165. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65166. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65167. */
  65168. this.enablePixelPerfectMode = false;
  65169. /**
  65170. * Force the postprocess to be applied without taking in account viewport
  65171. */
  65172. this.forceFullscreenViewport = true;
  65173. /**
  65174. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65175. *
  65176. * | Value | Type | Description |
  65177. * | ----- | ----------------------------------- | ----------- |
  65178. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65179. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65180. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65181. *
  65182. */
  65183. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65184. /**
  65185. * Force textures to be a power of two (default: false)
  65186. */
  65187. this.alwaysForcePOT = false;
  65188. /**
  65189. * Number of sample textures (default: 1)
  65190. */
  65191. this.samples = 1;
  65192. /**
  65193. * Modify the scale of the post process to be the same as the viewport (default: false)
  65194. */
  65195. this.adaptScaleToCurrentViewport = false;
  65196. this._reusable = false;
  65197. /**
  65198. * Smart array of input and output textures for the post process.
  65199. */
  65200. this._textures = new BABYLON.SmartArray(2);
  65201. /**
  65202. * The index in _textures that corresponds to the output texture.
  65203. */
  65204. this._currentRenderTextureInd = 0;
  65205. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65206. this._texelSize = BABYLON.Vector2.Zero();
  65207. // Events
  65208. /**
  65209. * An event triggered when the postprocess is activated.
  65210. */
  65211. this.onActivateObservable = new BABYLON.Observable();
  65212. /**
  65213. * An event triggered when the postprocess changes its size.
  65214. */
  65215. this.onSizeChangedObservable = new BABYLON.Observable();
  65216. /**
  65217. * An event triggered when the postprocess applies its effect.
  65218. */
  65219. this.onApplyObservable = new BABYLON.Observable();
  65220. /**
  65221. * An event triggered before rendering the postprocess
  65222. */
  65223. this.onBeforeRenderObservable = new BABYLON.Observable();
  65224. /**
  65225. * An event triggered after rendering the postprocess
  65226. */
  65227. this.onAfterRenderObservable = new BABYLON.Observable();
  65228. if (camera != null) {
  65229. this._camera = camera;
  65230. this._scene = camera.getScene();
  65231. camera.attachPostProcess(this);
  65232. this._engine = this._scene.getEngine();
  65233. this._scene.postProcesses.push(this);
  65234. }
  65235. else if (engine) {
  65236. this._engine = engine;
  65237. this._engine.postProcesses.push(this);
  65238. }
  65239. this._options = options;
  65240. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65241. this._reusable = reusable || false;
  65242. this._textureType = textureType;
  65243. this._samplers = samplers || [];
  65244. this._samplers.push("textureSampler");
  65245. this._fragmentUrl = fragmentUrl;
  65246. this._vertexUrl = vertexUrl;
  65247. this._parameters = parameters || [];
  65248. this._parameters.push("scale");
  65249. this._indexParameters = indexParameters;
  65250. if (!blockCompilation) {
  65251. this.updateEffect(defines);
  65252. }
  65253. }
  65254. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65255. /**
  65256. * A function that is added to the onActivateObservable
  65257. */
  65258. set: function (callback) {
  65259. if (this._onActivateObserver) {
  65260. this.onActivateObservable.remove(this._onActivateObserver);
  65261. }
  65262. if (callback) {
  65263. this._onActivateObserver = this.onActivateObservable.add(callback);
  65264. }
  65265. },
  65266. enumerable: true,
  65267. configurable: true
  65268. });
  65269. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65270. /**
  65271. * A function that is added to the onSizeChangedObservable
  65272. */
  65273. set: function (callback) {
  65274. if (this._onSizeChangedObserver) {
  65275. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65276. }
  65277. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65278. },
  65279. enumerable: true,
  65280. configurable: true
  65281. });
  65282. Object.defineProperty(PostProcess.prototype, "onApply", {
  65283. /**
  65284. * A function that is added to the onApplyObservable
  65285. */
  65286. set: function (callback) {
  65287. if (this._onApplyObserver) {
  65288. this.onApplyObservable.remove(this._onApplyObserver);
  65289. }
  65290. this._onApplyObserver = this.onApplyObservable.add(callback);
  65291. },
  65292. enumerable: true,
  65293. configurable: true
  65294. });
  65295. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65296. /**
  65297. * A function that is added to the onBeforeRenderObservable
  65298. */
  65299. set: function (callback) {
  65300. if (this._onBeforeRenderObserver) {
  65301. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65302. }
  65303. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65304. },
  65305. enumerable: true,
  65306. configurable: true
  65307. });
  65308. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65309. /**
  65310. * A function that is added to the onAfterRenderObservable
  65311. */
  65312. set: function (callback) {
  65313. if (this._onAfterRenderObserver) {
  65314. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65315. }
  65316. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65317. },
  65318. enumerable: true,
  65319. configurable: true
  65320. });
  65321. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65322. /**
  65323. * 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
  65324. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65325. */
  65326. get: function () {
  65327. return this._textures.data[this._currentRenderTextureInd];
  65328. },
  65329. set: function (value) {
  65330. this._forcedOutputTexture = value;
  65331. },
  65332. enumerable: true,
  65333. configurable: true
  65334. });
  65335. /**
  65336. * Gets the camera which post process is applied to.
  65337. * @returns The camera the post process is applied to.
  65338. */
  65339. PostProcess.prototype.getCamera = function () {
  65340. return this._camera;
  65341. };
  65342. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65343. /**
  65344. * Gets the texel size of the postprocess.
  65345. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65346. */
  65347. get: function () {
  65348. if (this._shareOutputWithPostProcess) {
  65349. return this._shareOutputWithPostProcess.texelSize;
  65350. }
  65351. if (this._forcedOutputTexture) {
  65352. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65353. }
  65354. return this._texelSize;
  65355. },
  65356. enumerable: true,
  65357. configurable: true
  65358. });
  65359. /**
  65360. * Gets the engine which this post process belongs to.
  65361. * @returns The engine the post process was enabled with.
  65362. */
  65363. PostProcess.prototype.getEngine = function () {
  65364. return this._engine;
  65365. };
  65366. /**
  65367. * The effect that is created when initializing the post process.
  65368. * @returns The created effect corrisponding the the postprocess.
  65369. */
  65370. PostProcess.prototype.getEffect = function () {
  65371. return this._effect;
  65372. };
  65373. /**
  65374. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65375. * @param postProcess The post process to share the output with.
  65376. * @returns This post process.
  65377. */
  65378. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65379. this._disposeTextures();
  65380. this._shareOutputWithPostProcess = postProcess;
  65381. return this;
  65382. };
  65383. /**
  65384. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65385. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65386. */
  65387. PostProcess.prototype.useOwnOutput = function () {
  65388. if (this._textures.length == 0) {
  65389. this._textures = new BABYLON.SmartArray(2);
  65390. }
  65391. this._shareOutputWithPostProcess = null;
  65392. };
  65393. /**
  65394. * Updates the effect with the current post process compile time values and recompiles the shader.
  65395. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65396. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65397. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65398. * @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
  65399. * @param onCompiled Called when the shader has been compiled.
  65400. * @param onError Called if there is an error when compiling a shader.
  65401. */
  65402. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65403. if (defines === void 0) { defines = null; }
  65404. if (uniforms === void 0) { uniforms = null; }
  65405. if (samplers === void 0) { samplers = null; }
  65406. 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);
  65407. };
  65408. /**
  65409. * The post process is reusable if it can be used multiple times within one frame.
  65410. * @returns If the post process is reusable
  65411. */
  65412. PostProcess.prototype.isReusable = function () {
  65413. return this._reusable;
  65414. };
  65415. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65416. PostProcess.prototype.markTextureDirty = function () {
  65417. this.width = -1;
  65418. };
  65419. /**
  65420. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65421. * 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.
  65422. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65423. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65424. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65425. * @returns The target texture that was bound to be written to.
  65426. */
  65427. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65428. var _this = this;
  65429. if (sourceTexture === void 0) { sourceTexture = null; }
  65430. camera = camera || this._camera;
  65431. var scene = camera.getScene();
  65432. var engine = scene.getEngine();
  65433. var maxSize = engine.getCaps().maxTextureSize;
  65434. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65435. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65436. // 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
  65437. var webVRCamera = camera.parent;
  65438. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65439. requiredWidth /= 2;
  65440. }
  65441. var desiredWidth = (this._options.width || requiredWidth);
  65442. var desiredHeight = this._options.height || requiredHeight;
  65443. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65444. if (this.adaptScaleToCurrentViewport) {
  65445. var currentViewport = engine.currentViewport;
  65446. if (currentViewport) {
  65447. desiredWidth *= currentViewport.width;
  65448. desiredHeight *= currentViewport.height;
  65449. }
  65450. }
  65451. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65452. if (!this._options.width) {
  65453. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65454. }
  65455. if (!this._options.height) {
  65456. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65457. }
  65458. }
  65459. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65460. if (this._textures.length > 0) {
  65461. for (var i = 0; i < this._textures.length; i++) {
  65462. this._engine._releaseTexture(this._textures.data[i]);
  65463. }
  65464. this._textures.reset();
  65465. }
  65466. this.width = desiredWidth;
  65467. this.height = desiredHeight;
  65468. var textureSize = { width: this.width, height: this.height };
  65469. var textureOptions = {
  65470. generateMipMaps: false,
  65471. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65472. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65473. samplingMode: this.renderTargetSamplingMode,
  65474. type: this._textureType
  65475. };
  65476. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65477. if (this._reusable) {
  65478. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65479. }
  65480. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65481. this.onSizeChangedObservable.notifyObservers(this);
  65482. }
  65483. this._textures.forEach(function (texture) {
  65484. if (texture.samples !== _this.samples) {
  65485. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65486. }
  65487. });
  65488. }
  65489. var target;
  65490. if (this._shareOutputWithPostProcess) {
  65491. target = this._shareOutputWithPostProcess.inputTexture;
  65492. }
  65493. else if (this._forcedOutputTexture) {
  65494. target = this._forcedOutputTexture;
  65495. this.width = this._forcedOutputTexture.width;
  65496. this.height = this._forcedOutputTexture.height;
  65497. }
  65498. else {
  65499. target = this.inputTexture;
  65500. }
  65501. // Bind the input of this post process to be used as the output of the previous post process.
  65502. if (this.enablePixelPerfectMode) {
  65503. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65504. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65505. }
  65506. else {
  65507. this._scaleRatio.copyFromFloats(1, 1);
  65508. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65509. }
  65510. this.onActivateObservable.notifyObservers(camera);
  65511. // Clear
  65512. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65513. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65514. }
  65515. if (this._reusable) {
  65516. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65517. }
  65518. return target;
  65519. };
  65520. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65521. /**
  65522. * If the post process is supported.
  65523. */
  65524. get: function () {
  65525. return this._effect.isSupported;
  65526. },
  65527. enumerable: true,
  65528. configurable: true
  65529. });
  65530. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65531. /**
  65532. * The aspect ratio of the output texture.
  65533. */
  65534. get: function () {
  65535. if (this._shareOutputWithPostProcess) {
  65536. return this._shareOutputWithPostProcess.aspectRatio;
  65537. }
  65538. if (this._forcedOutputTexture) {
  65539. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65540. }
  65541. return this.width / this.height;
  65542. },
  65543. enumerable: true,
  65544. configurable: true
  65545. });
  65546. /**
  65547. * Get a value indicating if the post-process is ready to be used
  65548. * @returns true if the post-process is ready (shader is compiled)
  65549. */
  65550. PostProcess.prototype.isReady = function () {
  65551. return this._effect && this._effect.isReady();
  65552. };
  65553. /**
  65554. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65555. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65556. */
  65557. PostProcess.prototype.apply = function () {
  65558. // Check
  65559. if (!this._effect || !this._effect.isReady())
  65560. return null;
  65561. // States
  65562. this._engine.enableEffect(this._effect);
  65563. this._engine.setState(false);
  65564. this._engine.setDepthBuffer(false);
  65565. this._engine.setDepthWrite(false);
  65566. // Alpha
  65567. this._engine.setAlphaMode(this.alphaMode);
  65568. if (this.alphaConstants) {
  65569. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65570. }
  65571. // Bind the output texture of the preivous post process as the input to this post process.
  65572. var source;
  65573. if (this._shareOutputWithPostProcess) {
  65574. source = this._shareOutputWithPostProcess.inputTexture;
  65575. }
  65576. else if (this._forcedOutputTexture) {
  65577. source = this._forcedOutputTexture;
  65578. }
  65579. else {
  65580. source = this.inputTexture;
  65581. }
  65582. this._effect._bindTexture("textureSampler", source);
  65583. // Parameters
  65584. this._effect.setVector2("scale", this._scaleRatio);
  65585. this.onApplyObservable.notifyObservers(this._effect);
  65586. return this._effect;
  65587. };
  65588. PostProcess.prototype._disposeTextures = function () {
  65589. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65590. return;
  65591. }
  65592. if (this._textures.length > 0) {
  65593. for (var i = 0; i < this._textures.length; i++) {
  65594. this._engine._releaseTexture(this._textures.data[i]);
  65595. }
  65596. }
  65597. this._textures.dispose();
  65598. };
  65599. /**
  65600. * Disposes the post process.
  65601. * @param camera The camera to dispose the post process on.
  65602. */
  65603. PostProcess.prototype.dispose = function (camera) {
  65604. camera = camera || this._camera;
  65605. this._disposeTextures();
  65606. if (this._scene) {
  65607. var index_1 = this._scene.postProcesses.indexOf(this);
  65608. if (index_1 !== -1) {
  65609. this._scene.postProcesses.splice(index_1, 1);
  65610. }
  65611. }
  65612. else {
  65613. var index_2 = this._engine.postProcesses.indexOf(this);
  65614. if (index_2 !== -1) {
  65615. this._engine.postProcesses.splice(index_2, 1);
  65616. }
  65617. }
  65618. if (!camera) {
  65619. return;
  65620. }
  65621. camera.detachPostProcess(this);
  65622. var index = camera._postProcesses.indexOf(this);
  65623. if (index === 0 && camera._postProcesses.length > 0) {
  65624. var firstPostProcess = this._camera._getFirstPostProcess();
  65625. if (firstPostProcess) {
  65626. firstPostProcess.markTextureDirty();
  65627. }
  65628. }
  65629. this.onActivateObservable.clear();
  65630. this.onAfterRenderObservable.clear();
  65631. this.onApplyObservable.clear();
  65632. this.onBeforeRenderObservable.clear();
  65633. this.onSizeChangedObservable.clear();
  65634. };
  65635. return PostProcess;
  65636. }());
  65637. BABYLON.PostProcess = PostProcess;
  65638. })(BABYLON || (BABYLON = {}));
  65639. //# sourceMappingURL=babylon.postProcess.js.map
  65640. var BABYLON;
  65641. (function (BABYLON) {
  65642. var PassPostProcess = /** @class */ (function (_super) {
  65643. __extends(PassPostProcess, _super);
  65644. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65645. if (camera === void 0) { camera = null; }
  65646. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65647. if (blockCompilation === void 0) { blockCompilation = false; }
  65648. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65649. }
  65650. return PassPostProcess;
  65651. }(BABYLON.PostProcess));
  65652. BABYLON.PassPostProcess = PassPostProcess;
  65653. })(BABYLON || (BABYLON = {}));
  65654. //# sourceMappingURL=babylon.passPostProcess.js.map
  65655. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65656. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65657. s = arguments[i];
  65658. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65659. t[p] = s[p];
  65660. }
  65661. return t;
  65662. };
  65663. var BABYLON;
  65664. (function (BABYLON) {
  65665. /**
  65666. * Default implementation IShadowGenerator.
  65667. * This is the main object responsible of generating shadows in the framework.
  65668. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65669. */
  65670. var ShadowGenerator = /** @class */ (function () {
  65671. /**
  65672. * Creates a ShadowGenerator object.
  65673. * A ShadowGenerator is the required tool to use the shadows.
  65674. * Each light casting shadows needs to use its own ShadowGenerator.
  65675. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65676. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65677. * @param light The light object generating the shadows.
  65678. * @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.
  65679. */
  65680. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65681. this._bias = 0.00005;
  65682. this._normalBias = 0;
  65683. this._blurBoxOffset = 1;
  65684. this._blurScale = 2;
  65685. this._blurKernel = 1;
  65686. this._useKernelBlur = false;
  65687. this._filter = ShadowGenerator.FILTER_NONE;
  65688. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65689. this._contactHardeningLightSizeUVRatio = 0.1;
  65690. this._darkness = 0;
  65691. this._transparencyShadow = false;
  65692. /**
  65693. * Controls the extent to which the shadows fade out at the edge of the frustum
  65694. * Used only by directionals and spots
  65695. */
  65696. this.frustumEdgeFalloff = 0;
  65697. /**
  65698. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65699. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65700. * It might on the other hand introduce peter panning.
  65701. */
  65702. this.forceBackFacesOnly = false;
  65703. this._lightDirection = BABYLON.Vector3.Zero();
  65704. this._viewMatrix = BABYLON.Matrix.Zero();
  65705. this._projectionMatrix = BABYLON.Matrix.Zero();
  65706. this._transformMatrix = BABYLON.Matrix.Zero();
  65707. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65708. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65709. this._currentFaceIndex = 0;
  65710. this._currentFaceIndexCache = 0;
  65711. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65712. this._mapSize = mapSize;
  65713. this._light = light;
  65714. this._scene = light.getScene();
  65715. light._shadowGenerator = this;
  65716. // Texture type fallback from float to int if not supported.
  65717. var caps = this._scene.getEngine().getCaps();
  65718. if (!useFullFloatFirst) {
  65719. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65720. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65721. }
  65722. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65723. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65724. }
  65725. else {
  65726. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65727. }
  65728. }
  65729. else {
  65730. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65731. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65732. }
  65733. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65734. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65735. }
  65736. else {
  65737. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65738. }
  65739. }
  65740. this._initializeGenerator();
  65741. this._applyFilterValues();
  65742. }
  65743. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65744. /**
  65745. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65746. */
  65747. get: function () {
  65748. return this._bias;
  65749. },
  65750. /**
  65751. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65752. */
  65753. set: function (bias) {
  65754. this._bias = bias;
  65755. },
  65756. enumerable: true,
  65757. configurable: true
  65758. });
  65759. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65760. /**
  65761. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65762. */
  65763. get: function () {
  65764. return this._normalBias;
  65765. },
  65766. /**
  65767. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65768. */
  65769. set: function (normalBias) {
  65770. this._normalBias = normalBias;
  65771. },
  65772. enumerable: true,
  65773. configurable: true
  65774. });
  65775. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65776. /**
  65777. * Gets the blur box offset: offset applied during the blur pass.
  65778. * Only usefull if useKernelBlur = false
  65779. */
  65780. get: function () {
  65781. return this._blurBoxOffset;
  65782. },
  65783. /**
  65784. * Sets the blur box offset: offset applied during the blur pass.
  65785. * Only usefull if useKernelBlur = false
  65786. */
  65787. set: function (value) {
  65788. if (this._blurBoxOffset === value) {
  65789. return;
  65790. }
  65791. this._blurBoxOffset = value;
  65792. this._disposeBlurPostProcesses();
  65793. },
  65794. enumerable: true,
  65795. configurable: true
  65796. });
  65797. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65798. /**
  65799. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65800. * 2 means half of the size.
  65801. */
  65802. get: function () {
  65803. return this._blurScale;
  65804. },
  65805. /**
  65806. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65807. * 2 means half of the size.
  65808. */
  65809. set: function (value) {
  65810. if (this._blurScale === value) {
  65811. return;
  65812. }
  65813. this._blurScale = value;
  65814. this._disposeBlurPostProcesses();
  65815. },
  65816. enumerable: true,
  65817. configurable: true
  65818. });
  65819. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65820. /**
  65821. * Gets the blur kernel: kernel size of the blur pass.
  65822. * Only usefull if useKernelBlur = true
  65823. */
  65824. get: function () {
  65825. return this._blurKernel;
  65826. },
  65827. /**
  65828. * Sets the blur kernel: kernel size of the blur pass.
  65829. * Only usefull if useKernelBlur = true
  65830. */
  65831. set: function (value) {
  65832. if (this._blurKernel === value) {
  65833. return;
  65834. }
  65835. this._blurKernel = value;
  65836. this._disposeBlurPostProcesses();
  65837. },
  65838. enumerable: true,
  65839. configurable: true
  65840. });
  65841. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65842. /**
  65843. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65844. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65845. */
  65846. get: function () {
  65847. return this._useKernelBlur;
  65848. },
  65849. /**
  65850. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65851. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65852. */
  65853. set: function (value) {
  65854. if (this._useKernelBlur === value) {
  65855. return;
  65856. }
  65857. this._useKernelBlur = value;
  65858. this._disposeBlurPostProcesses();
  65859. },
  65860. enumerable: true,
  65861. configurable: true
  65862. });
  65863. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65864. /**
  65865. * Gets the depth scale used in ESM mode.
  65866. */
  65867. get: function () {
  65868. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65869. },
  65870. /**
  65871. * Sets the depth scale used in ESM mode.
  65872. * This can override the scale stored on the light.
  65873. */
  65874. set: function (value) {
  65875. this._depthScale = value;
  65876. },
  65877. enumerable: true,
  65878. configurable: true
  65879. });
  65880. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65881. /**
  65882. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65883. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65884. */
  65885. get: function () {
  65886. return this._filter;
  65887. },
  65888. /**
  65889. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65890. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65891. */
  65892. set: function (value) {
  65893. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65894. if (this._light.needCube()) {
  65895. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65896. this.useExponentialShadowMap = true;
  65897. return;
  65898. }
  65899. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65900. this.useCloseExponentialShadowMap = true;
  65901. return;
  65902. }
  65903. // PCF on cubemap would also be expensive
  65904. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65905. this.usePoissonSampling = true;
  65906. return;
  65907. }
  65908. }
  65909. // Weblg1 fallback for PCF.
  65910. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65911. if (this._scene.getEngine().webGLVersion === 1) {
  65912. this.usePoissonSampling = true;
  65913. return;
  65914. }
  65915. }
  65916. if (this._filter === value) {
  65917. return;
  65918. }
  65919. this._filter = value;
  65920. this._disposeBlurPostProcesses();
  65921. this._applyFilterValues();
  65922. this._light._markMeshesAsLightDirty();
  65923. },
  65924. enumerable: true,
  65925. configurable: true
  65926. });
  65927. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65928. /**
  65929. * Gets if the current filter is set to Poisson Sampling.
  65930. */
  65931. get: function () {
  65932. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65933. },
  65934. /**
  65935. * Sets the current filter to Poisson Sampling.
  65936. */
  65937. set: function (value) {
  65938. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65939. return;
  65940. }
  65941. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65942. },
  65943. enumerable: true,
  65944. configurable: true
  65945. });
  65946. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65947. /**
  65948. * Gets if the current filter is set to VSM.
  65949. * DEPRECATED. Should use useExponentialShadowMap instead.
  65950. */
  65951. get: function () {
  65952. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65953. return this.useExponentialShadowMap;
  65954. },
  65955. /**
  65956. * Sets the current filter is to VSM.
  65957. * DEPRECATED. Should use useExponentialShadowMap instead.
  65958. */
  65959. set: function (value) {
  65960. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65961. this.useExponentialShadowMap = value;
  65962. },
  65963. enumerable: true,
  65964. configurable: true
  65965. });
  65966. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65967. /**
  65968. * Gets if the current filter is set to blurred VSM.
  65969. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65970. */
  65971. get: function () {
  65972. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65973. return this.useBlurExponentialShadowMap;
  65974. },
  65975. /**
  65976. * Sets the current filter is to blurred VSM.
  65977. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65978. */
  65979. set: function (value) {
  65980. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65981. this.useBlurExponentialShadowMap = value;
  65982. },
  65983. enumerable: true,
  65984. configurable: true
  65985. });
  65986. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65987. /**
  65988. * Gets if the current filter is set to ESM.
  65989. */
  65990. get: function () {
  65991. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65992. },
  65993. /**
  65994. * Sets the current filter is to ESM.
  65995. */
  65996. set: function (value) {
  65997. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65998. return;
  65999. }
  66000. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66001. },
  66002. enumerable: true,
  66003. configurable: true
  66004. });
  66005. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66006. /**
  66007. * Gets if the current filter is set to filtered ESM.
  66008. */
  66009. get: function () {
  66010. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66011. },
  66012. /**
  66013. * Gets if the current filter is set to filtered ESM.
  66014. */
  66015. set: function (value) {
  66016. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66017. return;
  66018. }
  66019. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66020. },
  66021. enumerable: true,
  66022. configurable: true
  66023. });
  66024. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66025. /**
  66026. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66027. * exponential to prevent steep falloff artifacts).
  66028. */
  66029. get: function () {
  66030. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66031. },
  66032. /**
  66033. * Sets the current filter to "close ESM" (using the inverse of the
  66034. * exponential to prevent steep falloff artifacts).
  66035. */
  66036. set: function (value) {
  66037. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66038. return;
  66039. }
  66040. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66041. },
  66042. enumerable: true,
  66043. configurable: true
  66044. });
  66045. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66046. /**
  66047. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66048. * exponential to prevent steep falloff artifacts).
  66049. */
  66050. get: function () {
  66051. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66052. },
  66053. /**
  66054. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66055. * exponential to prevent steep falloff artifacts).
  66056. */
  66057. set: function (value) {
  66058. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66059. return;
  66060. }
  66061. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66062. },
  66063. enumerable: true,
  66064. configurable: true
  66065. });
  66066. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66067. /**
  66068. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66069. */
  66070. get: function () {
  66071. return this.filter === ShadowGenerator.FILTER_PCF;
  66072. },
  66073. /**
  66074. * Sets the current filter to "PCF" (percentage closer filtering).
  66075. */
  66076. set: function (value) {
  66077. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66078. return;
  66079. }
  66080. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66081. },
  66082. enumerable: true,
  66083. configurable: true
  66084. });
  66085. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66086. /**
  66087. * Gets the PCF or PCSS Quality.
  66088. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66089. */
  66090. get: function () {
  66091. return this._filteringQuality;
  66092. },
  66093. /**
  66094. * Sets the PCF or PCSS Quality.
  66095. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66096. */
  66097. set: function (filteringQuality) {
  66098. this._filteringQuality = filteringQuality;
  66099. },
  66100. enumerable: true,
  66101. configurable: true
  66102. });
  66103. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66104. /**
  66105. * Gets if the current filter is set to "PCSS" (contact hardening).
  66106. */
  66107. get: function () {
  66108. return this.filter === ShadowGenerator.FILTER_PCSS;
  66109. },
  66110. /**
  66111. * Sets the current filter to "PCSS" (contact hardening).
  66112. */
  66113. set: function (value) {
  66114. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66115. return;
  66116. }
  66117. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66118. },
  66119. enumerable: true,
  66120. configurable: true
  66121. });
  66122. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66123. /**
  66124. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66125. * Using a ratio helps keeping shape stability independently of the map size.
  66126. *
  66127. * It does not account for the light projection as it was having too much
  66128. * instability during the light setup or during light position changes.
  66129. *
  66130. * Only valid if useContactHardeningShadow is true.
  66131. */
  66132. get: function () {
  66133. return this._contactHardeningLightSizeUVRatio;
  66134. },
  66135. /**
  66136. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66137. * Using a ratio helps keeping shape stability independently of the map size.
  66138. *
  66139. * It does not account for the light projection as it was having too much
  66140. * instability during the light setup or during light position changes.
  66141. *
  66142. * Only valid if useContactHardeningShadow is true.
  66143. */
  66144. set: function (contactHardeningLightSizeUVRatio) {
  66145. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66146. },
  66147. enumerable: true,
  66148. configurable: true
  66149. });
  66150. /**
  66151. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66152. * 0 means strongest and 1 would means no shadow.
  66153. * @returns the darkness.
  66154. */
  66155. ShadowGenerator.prototype.getDarkness = function () {
  66156. return this._darkness;
  66157. };
  66158. /**
  66159. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66160. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66161. * @returns the shadow generator allowing fluent coding.
  66162. */
  66163. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66164. if (darkness >= 1.0)
  66165. this._darkness = 1.0;
  66166. else if (darkness <= 0.0)
  66167. this._darkness = 0.0;
  66168. else
  66169. this._darkness = darkness;
  66170. return this;
  66171. };
  66172. /**
  66173. * Sets the ability to have transparent shadow (boolean).
  66174. * @param transparent True if transparent else False
  66175. * @returns the shadow generator allowing fluent coding
  66176. */
  66177. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66178. this._transparencyShadow = transparent;
  66179. return this;
  66180. };
  66181. /**
  66182. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66183. * @returns The render target texture if present otherwise, null
  66184. */
  66185. ShadowGenerator.prototype.getShadowMap = function () {
  66186. return this._shadowMap;
  66187. };
  66188. /**
  66189. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66190. * @returns The render target texture if the shadow map is present otherwise, null
  66191. */
  66192. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66193. if (this._shadowMap2) {
  66194. return this._shadowMap2;
  66195. }
  66196. return this._shadowMap;
  66197. };
  66198. /**
  66199. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66200. * @param mesh Mesh to add
  66201. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66202. * @returns the Shadow Generator itself
  66203. */
  66204. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66205. if (includeDescendants === void 0) { includeDescendants = true; }
  66206. if (!this._shadowMap) {
  66207. return this;
  66208. }
  66209. if (!this._shadowMap.renderList) {
  66210. this._shadowMap.renderList = [];
  66211. }
  66212. this._shadowMap.renderList.push(mesh);
  66213. if (includeDescendants) {
  66214. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66215. }
  66216. return this;
  66217. var _a;
  66218. };
  66219. /**
  66220. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66221. * @param mesh Mesh to remove
  66222. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66223. * @returns the Shadow Generator itself
  66224. */
  66225. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66226. if (includeDescendants === void 0) { includeDescendants = true; }
  66227. if (!this._shadowMap || !this._shadowMap.renderList) {
  66228. return this;
  66229. }
  66230. var index = this._shadowMap.renderList.indexOf(mesh);
  66231. if (index !== -1) {
  66232. this._shadowMap.renderList.splice(index, 1);
  66233. }
  66234. if (includeDescendants) {
  66235. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66236. var child = _a[_i];
  66237. this.removeShadowCaster(child);
  66238. }
  66239. }
  66240. return this;
  66241. };
  66242. /**
  66243. * Returns the associated light object.
  66244. * @returns the light generating the shadow
  66245. */
  66246. ShadowGenerator.prototype.getLight = function () {
  66247. return this._light;
  66248. };
  66249. ShadowGenerator.prototype._initializeGenerator = function () {
  66250. this._light._markMeshesAsLightDirty();
  66251. this._initializeShadowMap();
  66252. };
  66253. ShadowGenerator.prototype._initializeShadowMap = function () {
  66254. var _this = this;
  66255. // Render target
  66256. var engine = this._scene.getEngine();
  66257. if (engine.webGLVersion > 1) {
  66258. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66259. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66260. }
  66261. else {
  66262. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66263. }
  66264. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66265. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66266. this._shadowMap.anisotropicFilteringLevel = 1;
  66267. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66268. this._shadowMap.renderParticles = false;
  66269. this._shadowMap.ignoreCameraViewport = true;
  66270. // Record Face Index before render.
  66271. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66272. _this._currentFaceIndex = faceIndex;
  66273. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66274. engine.setColorWrite(false);
  66275. }
  66276. });
  66277. // Custom render function.
  66278. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66279. // Blur if required afer render.
  66280. this._shadowMap.onAfterUnbindObservable.add(function () {
  66281. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66282. engine.setColorWrite(true);
  66283. }
  66284. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66285. return;
  66286. }
  66287. var shadowMap = _this.getShadowMapForRendering();
  66288. if (shadowMap) {
  66289. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66290. }
  66291. });
  66292. // Clear according to the chosen filter.
  66293. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66294. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66295. this._shadowMap.onClearObservable.add(function (engine) {
  66296. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66297. engine.clear(clearOne, false, true, false);
  66298. }
  66299. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66300. engine.clear(clearZero, true, true, false);
  66301. }
  66302. else {
  66303. engine.clear(clearOne, true, true, false);
  66304. }
  66305. });
  66306. };
  66307. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66308. var _this = this;
  66309. var engine = this._scene.getEngine();
  66310. var targetSize = this._mapSize / this.blurScale;
  66311. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66312. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66313. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66314. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66315. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66316. }
  66317. if (this.useKernelBlur) {
  66318. 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);
  66319. this._kernelBlurXPostprocess.width = targetSize;
  66320. this._kernelBlurXPostprocess.height = targetSize;
  66321. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66322. effect.setTexture("textureSampler", _this._shadowMap);
  66323. });
  66324. 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);
  66325. this._kernelBlurXPostprocess.autoClear = false;
  66326. this._kernelBlurYPostprocess.autoClear = false;
  66327. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66328. this._kernelBlurXPostprocess.packedFloat = true;
  66329. this._kernelBlurYPostprocess.packedFloat = true;
  66330. }
  66331. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66332. }
  66333. else {
  66334. 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);
  66335. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66336. effect.setFloat2("screenSize", targetSize, targetSize);
  66337. effect.setTexture("textureSampler", _this._shadowMap);
  66338. });
  66339. this._boxBlurPostprocess.autoClear = false;
  66340. this._blurPostProcesses = [this._boxBlurPostprocess];
  66341. }
  66342. };
  66343. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66344. var index;
  66345. var engine = this._scene.getEngine();
  66346. if (depthOnlySubMeshes.length) {
  66347. engine.setColorWrite(false);
  66348. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66349. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66350. }
  66351. engine.setColorWrite(true);
  66352. }
  66353. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66354. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66355. }
  66356. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66357. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66358. }
  66359. if (this._transparencyShadow) {
  66360. for (index = 0; index < transparentSubMeshes.length; index++) {
  66361. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66362. }
  66363. }
  66364. };
  66365. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66366. var _this = this;
  66367. var mesh = subMesh.getRenderingMesh();
  66368. var scene = this._scene;
  66369. var engine = scene.getEngine();
  66370. var material = subMesh.getMaterial();
  66371. if (!material) {
  66372. return;
  66373. }
  66374. // Culling
  66375. engine.setState(material.backFaceCulling);
  66376. // Managing instances
  66377. var batch = mesh._getInstancesRenderList(subMesh._id);
  66378. if (batch.mustReturn) {
  66379. return;
  66380. }
  66381. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66382. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66383. engine.enableEffect(this._effect);
  66384. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66385. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66386. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66387. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66388. this._effect.setVector3("lightData", this._cachedDirection);
  66389. }
  66390. else {
  66391. this._effect.setVector3("lightData", this._cachedPosition);
  66392. }
  66393. if (scene.activeCamera) {
  66394. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66395. }
  66396. // Alpha test
  66397. if (material && material.needAlphaTesting()) {
  66398. var alphaTexture = material.getAlphaTestTexture();
  66399. if (alphaTexture) {
  66400. this._effect.setTexture("diffuseSampler", alphaTexture);
  66401. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66402. }
  66403. }
  66404. // Bones
  66405. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66406. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66407. }
  66408. // Morph targets
  66409. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66410. if (this.forceBackFacesOnly) {
  66411. engine.setState(true, 0, false, true);
  66412. }
  66413. // Draw
  66414. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66415. if (this.forceBackFacesOnly) {
  66416. engine.setState(true, 0, false, false);
  66417. }
  66418. }
  66419. else {
  66420. // Need to reset refresh rate of the shadowMap
  66421. if (this._shadowMap) {
  66422. this._shadowMap.resetRefreshCounter();
  66423. }
  66424. }
  66425. };
  66426. ShadowGenerator.prototype._applyFilterValues = function () {
  66427. if (!this._shadowMap) {
  66428. return;
  66429. }
  66430. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66431. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66432. }
  66433. else {
  66434. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66435. }
  66436. };
  66437. /**
  66438. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66439. * @param onCompiled Callback triggered at the and of the effects compilation
  66440. * @param options Sets of optional options forcing the compilation with different modes
  66441. */
  66442. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66443. var _this = this;
  66444. var localOptions = __assign({ useInstances: false }, options);
  66445. var shadowMap = this.getShadowMap();
  66446. if (!shadowMap) {
  66447. if (onCompiled) {
  66448. onCompiled(this);
  66449. }
  66450. return;
  66451. }
  66452. var renderList = shadowMap.renderList;
  66453. if (!renderList) {
  66454. if (onCompiled) {
  66455. onCompiled(this);
  66456. }
  66457. return;
  66458. }
  66459. var subMeshes = new Array();
  66460. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66461. var mesh = renderList_1[_i];
  66462. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66463. }
  66464. if (subMeshes.length === 0) {
  66465. if (onCompiled) {
  66466. onCompiled(this);
  66467. }
  66468. return;
  66469. }
  66470. var currentIndex = 0;
  66471. var checkReady = function () {
  66472. if (!_this._scene || !_this._scene.getEngine()) {
  66473. return;
  66474. }
  66475. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66476. currentIndex++;
  66477. if (currentIndex >= subMeshes.length) {
  66478. if (onCompiled) {
  66479. onCompiled(_this);
  66480. }
  66481. return;
  66482. }
  66483. }
  66484. setTimeout(checkReady, 16);
  66485. };
  66486. checkReady();
  66487. };
  66488. /**
  66489. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66490. * @param options Sets of optional options forcing the compilation with different modes
  66491. * @returns A promise that resolves when the compilation completes
  66492. */
  66493. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66494. var _this = this;
  66495. return new Promise(function (resolve) {
  66496. _this.forceCompilation(function () {
  66497. resolve();
  66498. }, options);
  66499. });
  66500. };
  66501. /**
  66502. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66503. * @param subMesh The submesh we want to render in the shadow map
  66504. * @param useInstances Defines wether will draw in the map using instances
  66505. * @returns true if ready otherwise, false
  66506. */
  66507. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66508. var defines = [];
  66509. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66510. defines.push("#define FLOAT");
  66511. }
  66512. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66513. defines.push("#define ESM");
  66514. }
  66515. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66516. defines.push("#define DEPTHTEXTURE");
  66517. }
  66518. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66519. var mesh = subMesh.getMesh();
  66520. var material = subMesh.getMaterial();
  66521. // Normal bias.
  66522. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66523. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66524. defines.push("#define NORMAL");
  66525. if (mesh.nonUniformScaling) {
  66526. defines.push("#define NONUNIFORMSCALING");
  66527. }
  66528. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66529. defines.push("#define DIRECTIONINLIGHTDATA");
  66530. }
  66531. }
  66532. // Alpha test
  66533. if (material && material.needAlphaTesting()) {
  66534. var alphaTexture = material.getAlphaTestTexture();
  66535. if (alphaTexture) {
  66536. defines.push("#define ALPHATEST");
  66537. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66538. attribs.push(BABYLON.VertexBuffer.UVKind);
  66539. defines.push("#define UV1");
  66540. }
  66541. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66542. if (alphaTexture.coordinatesIndex === 1) {
  66543. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66544. defines.push("#define UV2");
  66545. }
  66546. }
  66547. }
  66548. }
  66549. // Bones
  66550. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66551. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66552. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66553. if (mesh.numBoneInfluencers > 4) {
  66554. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66555. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66556. }
  66557. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66558. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66559. }
  66560. else {
  66561. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66562. }
  66563. // Morph targets
  66564. var manager = mesh.morphTargetManager;
  66565. var morphInfluencers = 0;
  66566. if (manager) {
  66567. if (manager.numInfluencers > 0) {
  66568. defines.push("#define MORPHTARGETS");
  66569. morphInfluencers = manager.numInfluencers;
  66570. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66571. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66572. }
  66573. }
  66574. // Instances
  66575. if (useInstances) {
  66576. defines.push("#define INSTANCES");
  66577. attribs.push("world0");
  66578. attribs.push("world1");
  66579. attribs.push("world2");
  66580. attribs.push("world3");
  66581. }
  66582. // Get correct effect
  66583. var join = defines.join("\n");
  66584. if (this._cachedDefines !== join) {
  66585. this._cachedDefines = join;
  66586. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66587. }
  66588. if (!this._effect.isReady()) {
  66589. return false;
  66590. }
  66591. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66592. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66593. this._initializeBlurRTTAndPostProcesses();
  66594. }
  66595. }
  66596. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66597. return false;
  66598. }
  66599. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66600. return false;
  66601. }
  66602. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66603. return false;
  66604. }
  66605. return true;
  66606. };
  66607. /**
  66608. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66609. * @param defines Defines of the material we want to update
  66610. * @param lightIndex Index of the light in the enabled light list of the material
  66611. */
  66612. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66613. var scene = this._scene;
  66614. var light = this._light;
  66615. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66616. return;
  66617. }
  66618. defines["SHADOW" + lightIndex] = true;
  66619. if (this.useContactHardeningShadow) {
  66620. defines["SHADOWPCSS" + lightIndex] = true;
  66621. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66622. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66623. }
  66624. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66625. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66626. }
  66627. // else default to high.
  66628. }
  66629. if (this.usePercentageCloserFiltering) {
  66630. defines["SHADOWPCF" + lightIndex] = true;
  66631. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66632. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66633. }
  66634. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66635. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66636. }
  66637. // else default to high.
  66638. }
  66639. else if (this.usePoissonSampling) {
  66640. defines["SHADOWPOISSON" + lightIndex] = true;
  66641. }
  66642. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66643. defines["SHADOWESM" + lightIndex] = true;
  66644. }
  66645. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66646. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66647. }
  66648. if (light.needCube()) {
  66649. defines["SHADOWCUBE" + lightIndex] = true;
  66650. }
  66651. };
  66652. /**
  66653. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66654. * defined in the generator but impacting the effect).
  66655. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66656. * @param effect The effect we are binfing the information for
  66657. */
  66658. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66659. var light = this._light;
  66660. var scene = this._scene;
  66661. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66662. return;
  66663. }
  66664. var camera = scene.activeCamera;
  66665. if (!camera) {
  66666. return;
  66667. }
  66668. var shadowMap = this.getShadowMap();
  66669. if (!shadowMap) {
  66670. return;
  66671. }
  66672. if (!light.needCube()) {
  66673. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66674. }
  66675. // Only PCF uses depth stencil texture.
  66676. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66677. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66678. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66679. }
  66680. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66681. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66682. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66683. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66684. }
  66685. else {
  66686. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66687. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66688. }
  66689. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66690. };
  66691. /**
  66692. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66693. * (eq to shadow prjection matrix * light transform matrix)
  66694. * @returns The transform matrix used to create the shadow map
  66695. */
  66696. ShadowGenerator.prototype.getTransformMatrix = function () {
  66697. var scene = this._scene;
  66698. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66699. return this._transformMatrix;
  66700. }
  66701. this._currentRenderID = scene.getRenderId();
  66702. this._currentFaceIndexCache = this._currentFaceIndex;
  66703. var lightPosition = this._light.position;
  66704. if (this._light.computeTransformedInformation()) {
  66705. lightPosition = this._light.transformedPosition;
  66706. }
  66707. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66708. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66709. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66710. }
  66711. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66712. this._cachedPosition.copyFrom(lightPosition);
  66713. this._cachedDirection.copyFrom(this._lightDirection);
  66714. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66715. var shadowMap = this.getShadowMap();
  66716. if (shadowMap) {
  66717. var renderList = shadowMap.renderList;
  66718. if (renderList) {
  66719. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66720. }
  66721. }
  66722. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66723. }
  66724. return this._transformMatrix;
  66725. };
  66726. /**
  66727. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66728. * Cube and 2D textures for instance.
  66729. */
  66730. ShadowGenerator.prototype.recreateShadowMap = function () {
  66731. var shadowMap = this._shadowMap;
  66732. if (!shadowMap) {
  66733. return;
  66734. }
  66735. // Track render list.
  66736. var renderList = shadowMap.renderList;
  66737. // Clean up existing data.
  66738. this._disposeRTTandPostProcesses();
  66739. // Reinitializes.
  66740. this._initializeGenerator();
  66741. // Reaffect the filter to ensure a correct fallback if necessary.
  66742. this.filter = this.filter;
  66743. // Reaffect the filter.
  66744. this._applyFilterValues();
  66745. // Reaffect Render List.
  66746. this._shadowMap.renderList = renderList;
  66747. };
  66748. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66749. if (this._shadowMap2) {
  66750. this._shadowMap2.dispose();
  66751. this._shadowMap2 = null;
  66752. }
  66753. if (this._boxBlurPostprocess) {
  66754. this._boxBlurPostprocess.dispose();
  66755. this._boxBlurPostprocess = null;
  66756. }
  66757. if (this._kernelBlurXPostprocess) {
  66758. this._kernelBlurXPostprocess.dispose();
  66759. this._kernelBlurXPostprocess = null;
  66760. }
  66761. if (this._kernelBlurYPostprocess) {
  66762. this._kernelBlurYPostprocess.dispose();
  66763. this._kernelBlurYPostprocess = null;
  66764. }
  66765. this._blurPostProcesses = [];
  66766. };
  66767. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66768. if (this._shadowMap) {
  66769. this._shadowMap.dispose();
  66770. this._shadowMap = null;
  66771. }
  66772. this._disposeBlurPostProcesses();
  66773. };
  66774. /**
  66775. * Disposes the ShadowGenerator.
  66776. * Returns nothing.
  66777. */
  66778. ShadowGenerator.prototype.dispose = function () {
  66779. this._disposeRTTandPostProcesses();
  66780. if (this._light) {
  66781. this._light._shadowGenerator = null;
  66782. this._light._markMeshesAsLightDirty();
  66783. }
  66784. };
  66785. /**
  66786. * Serializes the shadow generator setup to a json object.
  66787. * @returns The serialized JSON object
  66788. */
  66789. ShadowGenerator.prototype.serialize = function () {
  66790. var serializationObject = {};
  66791. var shadowMap = this.getShadowMap();
  66792. if (!shadowMap) {
  66793. return serializationObject;
  66794. }
  66795. serializationObject.lightId = this._light.id;
  66796. serializationObject.mapSize = shadowMap.getRenderSize();
  66797. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66798. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66799. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66800. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66801. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66802. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66803. serializationObject.depthScale = this.depthScale;
  66804. serializationObject.darkness = this.getDarkness();
  66805. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66806. serializationObject.blurKernel = this.blurKernel;
  66807. serializationObject.blurScale = this.blurScale;
  66808. serializationObject.useKernelBlur = this.useKernelBlur;
  66809. serializationObject.transparencyShadow = this._transparencyShadow;
  66810. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66811. serializationObject.bias = this.bias;
  66812. serializationObject.normalBias = this.normalBias;
  66813. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66814. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66815. serializationObject.filteringQuality = this.filteringQuality;
  66816. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66817. serializationObject.renderList = [];
  66818. if (shadowMap.renderList) {
  66819. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66820. var mesh = shadowMap.renderList[meshIndex];
  66821. serializationObject.renderList.push(mesh.id);
  66822. }
  66823. }
  66824. return serializationObject;
  66825. };
  66826. /**
  66827. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66828. * @param parsedShadowGenerator The JSON object to parse
  66829. * @param scene The scene to create the shadow map for
  66830. * @returns The parsed shadow generator
  66831. */
  66832. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66833. //casting to point light, as light is missing the position attr and typescript complains.
  66834. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66835. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66836. var shadowMap = shadowGenerator.getShadowMap();
  66837. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66838. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66839. meshes.forEach(function (mesh) {
  66840. if (!shadowMap) {
  66841. return;
  66842. }
  66843. if (!shadowMap.renderList) {
  66844. shadowMap.renderList = [];
  66845. }
  66846. shadowMap.renderList.push(mesh);
  66847. });
  66848. }
  66849. if (parsedShadowGenerator.usePoissonSampling) {
  66850. shadowGenerator.usePoissonSampling = true;
  66851. }
  66852. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66853. shadowGenerator.useExponentialShadowMap = true;
  66854. }
  66855. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66856. shadowGenerator.useBlurExponentialShadowMap = true;
  66857. }
  66858. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66859. shadowGenerator.useCloseExponentialShadowMap = true;
  66860. }
  66861. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66862. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66863. }
  66864. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66865. shadowGenerator.usePercentageCloserFiltering = true;
  66866. }
  66867. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66868. shadowGenerator.useContactHardeningShadow = true;
  66869. }
  66870. if (parsedShadowGenerator.filteringQuality) {
  66871. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66872. }
  66873. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66874. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66875. }
  66876. // Backward compat
  66877. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66878. shadowGenerator.useExponentialShadowMap = true;
  66879. }
  66880. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66881. shadowGenerator.useBlurExponentialShadowMap = true;
  66882. }
  66883. if (parsedShadowGenerator.depthScale) {
  66884. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66885. }
  66886. if (parsedShadowGenerator.blurScale) {
  66887. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66888. }
  66889. if (parsedShadowGenerator.blurBoxOffset) {
  66890. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66891. }
  66892. if (parsedShadowGenerator.useKernelBlur) {
  66893. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66894. }
  66895. if (parsedShadowGenerator.blurKernel) {
  66896. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66897. }
  66898. if (parsedShadowGenerator.bias !== undefined) {
  66899. shadowGenerator.bias = parsedShadowGenerator.bias;
  66900. }
  66901. if (parsedShadowGenerator.normalBias !== undefined) {
  66902. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66903. }
  66904. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66905. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66906. }
  66907. if (parsedShadowGenerator.darkness) {
  66908. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66909. }
  66910. if (parsedShadowGenerator.transparencyShadow) {
  66911. shadowGenerator.setTransparencyShadow(true);
  66912. }
  66913. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66914. return shadowGenerator;
  66915. };
  66916. /**
  66917. * Shadow generator mode None: no filtering applied.
  66918. */
  66919. ShadowGenerator.FILTER_NONE = 0;
  66920. /**
  66921. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66922. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66923. */
  66924. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66925. /**
  66926. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66927. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66928. */
  66929. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66930. /**
  66931. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66932. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66933. */
  66934. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66935. /**
  66936. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66937. * edge artifacts on steep falloff.
  66938. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66939. */
  66940. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66941. /**
  66942. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66943. * edge artifacts on steep falloff.
  66944. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66945. */
  66946. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66947. /**
  66948. * Shadow generator mode PCF: Percentage Closer Filtering
  66949. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66950. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66951. */
  66952. ShadowGenerator.FILTER_PCF = 6;
  66953. /**
  66954. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66955. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66956. * Contact Hardening
  66957. */
  66958. ShadowGenerator.FILTER_PCSS = 7;
  66959. /**
  66960. * Reserved for PCF and PCSS
  66961. * Highest Quality.
  66962. *
  66963. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66964. *
  66965. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66966. */
  66967. ShadowGenerator.QUALITY_HIGH = 0;
  66968. /**
  66969. * Reserved for PCF and PCSS
  66970. * Good tradeoff for quality/perf cross devices
  66971. *
  66972. * Execute PCF on a 3*3 kernel.
  66973. *
  66974. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66975. */
  66976. ShadowGenerator.QUALITY_MEDIUM = 1;
  66977. /**
  66978. * Reserved for PCF and PCSS
  66979. * The lowest quality but the fastest.
  66980. *
  66981. * Execute PCF on a 1*1 kernel.
  66982. *
  66983. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66984. */
  66985. ShadowGenerator.QUALITY_LOW = 2;
  66986. return ShadowGenerator;
  66987. }());
  66988. BABYLON.ShadowGenerator = ShadowGenerator;
  66989. })(BABYLON || (BABYLON = {}));
  66990. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66991. var BABYLON;
  66992. (function (BABYLON) {
  66993. var DefaultLoadingScreen = /** @class */ (function () {
  66994. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66995. if (_loadingText === void 0) { _loadingText = ""; }
  66996. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66997. var _this = this;
  66998. this._renderingCanvas = _renderingCanvas;
  66999. this._loadingText = _loadingText;
  67000. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67001. // Resize
  67002. this._resizeLoadingUI = function () {
  67003. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67004. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67005. if (!_this._loadingDiv) {
  67006. return;
  67007. }
  67008. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67009. _this._loadingDiv.style.left = canvasRect.left + "px";
  67010. _this._loadingDiv.style.top = canvasRect.top + "px";
  67011. _this._loadingDiv.style.width = canvasRect.width + "px";
  67012. _this._loadingDiv.style.height = canvasRect.height + "px";
  67013. };
  67014. }
  67015. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67016. if (this._loadingDiv) {
  67017. // Do not add a loading screen if there is already one
  67018. return;
  67019. }
  67020. this._loadingDiv = document.createElement("div");
  67021. this._loadingDiv.id = "babylonjsLoadingDiv";
  67022. this._loadingDiv.style.opacity = "0";
  67023. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67024. this._loadingDiv.style.pointerEvents = "none";
  67025. // Loading text
  67026. this._loadingTextDiv = document.createElement("div");
  67027. this._loadingTextDiv.style.position = "absolute";
  67028. this._loadingTextDiv.style.left = "0";
  67029. this._loadingTextDiv.style.top = "50%";
  67030. this._loadingTextDiv.style.marginTop = "80px";
  67031. this._loadingTextDiv.style.width = "100%";
  67032. this._loadingTextDiv.style.height = "20px";
  67033. this._loadingTextDiv.style.fontFamily = "Arial";
  67034. this._loadingTextDiv.style.fontSize = "14px";
  67035. this._loadingTextDiv.style.color = "white";
  67036. this._loadingTextDiv.style.textAlign = "center";
  67037. this._loadingTextDiv.innerHTML = "Loading";
  67038. this._loadingDiv.appendChild(this._loadingTextDiv);
  67039. //set the predefined text
  67040. this._loadingTextDiv.innerHTML = this._loadingText;
  67041. // Generating keyframes
  67042. var style = document.createElement('style');
  67043. style.type = 'text/css';
  67044. 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 }";
  67045. style.innerHTML = keyFrames;
  67046. document.getElementsByTagName('head')[0].appendChild(style);
  67047. // Loading img
  67048. var imgBack = new Image();
  67049. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgA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s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  67050. imgBack.style.position = "absolute";
  67051. imgBack.style.left = "50%";
  67052. imgBack.style.top = "50%";
  67053. imgBack.style.marginLeft = "-60px";
  67054. imgBack.style.marginTop = "-60px";
  67055. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67056. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67057. imgBack.style.transformOrigin = "50% 50%";
  67058. imgBack.style.webkitTransformOrigin = "50% 50%";
  67059. this._loadingDiv.appendChild(imgBack);
  67060. this._resizeLoadingUI();
  67061. window.addEventListener("resize", this._resizeLoadingUI);
  67062. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67063. document.body.appendChild(this._loadingDiv);
  67064. this._loadingDiv.style.opacity = "1";
  67065. };
  67066. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67067. var _this = this;
  67068. if (!this._loadingDiv) {
  67069. return;
  67070. }
  67071. var onTransitionEnd = function () {
  67072. if (!_this._loadingDiv) {
  67073. return;
  67074. }
  67075. document.body.removeChild(_this._loadingDiv);
  67076. window.removeEventListener("resize", _this._resizeLoadingUI);
  67077. _this._loadingDiv = null;
  67078. };
  67079. this._loadingDiv.style.opacity = "0";
  67080. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67081. };
  67082. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67083. set: function (text) {
  67084. this._loadingText = text;
  67085. if (this._loadingTextDiv) {
  67086. this._loadingTextDiv.innerHTML = this._loadingText;
  67087. }
  67088. },
  67089. enumerable: true,
  67090. configurable: true
  67091. });
  67092. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67093. get: function () {
  67094. return this._loadingDivBackgroundColor;
  67095. },
  67096. set: function (color) {
  67097. this._loadingDivBackgroundColor = color;
  67098. if (!this._loadingDiv) {
  67099. return;
  67100. }
  67101. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67102. },
  67103. enumerable: true,
  67104. configurable: true
  67105. });
  67106. return DefaultLoadingScreen;
  67107. }());
  67108. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67109. })(BABYLON || (BABYLON = {}));
  67110. //# sourceMappingURL=babylon.loadingScreen.js.map
  67111. var BABYLON;
  67112. (function (BABYLON) {
  67113. var SceneLoaderProgressEvent = /** @class */ (function () {
  67114. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67115. this.lengthComputable = lengthComputable;
  67116. this.loaded = loaded;
  67117. this.total = total;
  67118. }
  67119. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67120. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67121. };
  67122. return SceneLoaderProgressEvent;
  67123. }());
  67124. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67125. var SceneLoader = /** @class */ (function () {
  67126. function SceneLoader() {
  67127. }
  67128. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67129. get: function () {
  67130. return 0;
  67131. },
  67132. enumerable: true,
  67133. configurable: true
  67134. });
  67135. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67136. get: function () {
  67137. return 1;
  67138. },
  67139. enumerable: true,
  67140. configurable: true
  67141. });
  67142. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67143. get: function () {
  67144. return 2;
  67145. },
  67146. enumerable: true,
  67147. configurable: true
  67148. });
  67149. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67150. get: function () {
  67151. return 3;
  67152. },
  67153. enumerable: true,
  67154. configurable: true
  67155. });
  67156. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67157. get: function () {
  67158. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67159. },
  67160. set: function (value) {
  67161. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67162. },
  67163. enumerable: true,
  67164. configurable: true
  67165. });
  67166. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67167. get: function () {
  67168. return SceneLoader._ShowLoadingScreen;
  67169. },
  67170. set: function (value) {
  67171. SceneLoader._ShowLoadingScreen = value;
  67172. },
  67173. enumerable: true,
  67174. configurable: true
  67175. });
  67176. Object.defineProperty(SceneLoader, "loggingLevel", {
  67177. get: function () {
  67178. return SceneLoader._loggingLevel;
  67179. },
  67180. set: function (value) {
  67181. SceneLoader._loggingLevel = value;
  67182. },
  67183. enumerable: true,
  67184. configurable: true
  67185. });
  67186. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67187. get: function () {
  67188. return SceneLoader._CleanBoneMatrixWeights;
  67189. },
  67190. set: function (value) {
  67191. SceneLoader._CleanBoneMatrixWeights = value;
  67192. },
  67193. enumerable: true,
  67194. configurable: true
  67195. });
  67196. SceneLoader._getDefaultPlugin = function () {
  67197. return SceneLoader._registeredPlugins[".babylon"];
  67198. };
  67199. SceneLoader._getPluginForExtension = function (extension) {
  67200. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67201. if (registeredPlugin) {
  67202. return registeredPlugin;
  67203. }
  67204. 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");
  67205. return SceneLoader._getDefaultPlugin();
  67206. };
  67207. SceneLoader._getPluginForDirectLoad = function (data) {
  67208. for (var extension in SceneLoader._registeredPlugins) {
  67209. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67210. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67211. return SceneLoader._registeredPlugins[extension];
  67212. }
  67213. }
  67214. return SceneLoader._getDefaultPlugin();
  67215. };
  67216. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67217. if (sceneFilename.name) {
  67218. sceneFilename = sceneFilename.name;
  67219. }
  67220. var queryStringPosition = sceneFilename.indexOf("?");
  67221. if (queryStringPosition !== -1) {
  67222. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67223. }
  67224. var dotPosition = sceneFilename.lastIndexOf(".");
  67225. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67226. return SceneLoader._getPluginForExtension(extension);
  67227. };
  67228. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67229. SceneLoader._getDirectLoad = function (sceneFilename) {
  67230. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67231. return sceneFilename.substr(5);
  67232. }
  67233. return null;
  67234. };
  67235. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67236. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67237. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67238. var plugin;
  67239. if (registeredPlugin.plugin.createPlugin) {
  67240. plugin = registeredPlugin.plugin.createPlugin();
  67241. }
  67242. else {
  67243. plugin = registeredPlugin.plugin;
  67244. }
  67245. var useArrayBuffer = registeredPlugin.isBinary;
  67246. var database;
  67247. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67248. var dataCallback = function (data, responseURL) {
  67249. if (scene.isDisposed) {
  67250. onError("Scene has been disposed");
  67251. return;
  67252. }
  67253. scene.database = database;
  67254. onSuccess(plugin, data, responseURL);
  67255. };
  67256. var request = null;
  67257. var pluginDisposed = false;
  67258. var onDisposeObservable = plugin.onDisposeObservable;
  67259. if (onDisposeObservable) {
  67260. onDisposeObservable.add(function () {
  67261. pluginDisposed = true;
  67262. if (request) {
  67263. request.abort();
  67264. request = null;
  67265. }
  67266. onDispose();
  67267. });
  67268. }
  67269. var manifestChecked = function () {
  67270. if (pluginDisposed) {
  67271. return;
  67272. }
  67273. var url = rootUrl + sceneFilename;
  67274. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67275. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67276. } : undefined, database, useArrayBuffer, function (request, exception) {
  67277. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67278. });
  67279. };
  67280. if (directLoad) {
  67281. dataCallback(directLoad);
  67282. return plugin;
  67283. }
  67284. if (rootUrl.indexOf("file:") === -1) {
  67285. var engine = scene.getEngine();
  67286. var canUseOfflineSupport = engine.enableOfflineSupport;
  67287. if (canUseOfflineSupport) {
  67288. // Also check for exceptions
  67289. var exceptionFound = false;
  67290. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67291. var regex = _a[_i];
  67292. if (regex.test(rootUrl + sceneFilename)) {
  67293. exceptionFound = true;
  67294. break;
  67295. }
  67296. }
  67297. canUseOfflineSupport = !exceptionFound;
  67298. }
  67299. if (canUseOfflineSupport) {
  67300. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67301. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67302. }
  67303. else {
  67304. manifestChecked();
  67305. }
  67306. }
  67307. // Loading file from disk via input file or drag'n'drop
  67308. else {
  67309. var fileOrString = sceneFilename;
  67310. if (fileOrString.name) { // File
  67311. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67312. }
  67313. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67314. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67315. }
  67316. else {
  67317. onError("Unable to find file named " + sceneFilename);
  67318. }
  67319. }
  67320. return plugin;
  67321. };
  67322. // Public functions
  67323. SceneLoader.GetPluginForExtension = function (extension) {
  67324. return SceneLoader._getPluginForExtension(extension).plugin;
  67325. };
  67326. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67327. return !!SceneLoader._registeredPlugins[extension];
  67328. };
  67329. SceneLoader.RegisterPlugin = function (plugin) {
  67330. if (typeof plugin.extensions === "string") {
  67331. var extension = plugin.extensions;
  67332. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67333. plugin: plugin,
  67334. isBinary: false
  67335. };
  67336. }
  67337. else {
  67338. var extensions = plugin.extensions;
  67339. Object.keys(extensions).forEach(function (extension) {
  67340. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67341. plugin: plugin,
  67342. isBinary: extensions[extension].isBinary
  67343. };
  67344. });
  67345. }
  67346. };
  67347. /**
  67348. * Import meshes into a scene
  67349. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67350. * @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)
  67351. * @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)
  67352. * @param scene the instance of BABYLON.Scene to append to
  67353. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67354. * @param onProgress a callback with a progress event for each file being loaded
  67355. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67356. * @param pluginExtension the extension used to determine the plugin
  67357. * @returns The loaded plugin
  67358. */
  67359. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67360. if (sceneFilename === void 0) { sceneFilename = ""; }
  67361. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67362. if (onSuccess === void 0) { onSuccess = null; }
  67363. if (onProgress === void 0) { onProgress = null; }
  67364. if (onError === void 0) { onError = null; }
  67365. if (pluginExtension === void 0) { pluginExtension = null; }
  67366. if (!scene) {
  67367. BABYLON.Tools.Error("No scene available to import mesh to");
  67368. return null;
  67369. }
  67370. if (!sceneFilename) {
  67371. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67372. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67373. }
  67374. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67375. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67376. return null;
  67377. }
  67378. var loadingToken = {};
  67379. scene._addPendingData(loadingToken);
  67380. var disposeHandler = function () {
  67381. scene._removePendingData(loadingToken);
  67382. };
  67383. var errorHandler = function (message, exception) {
  67384. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67385. if (onError) {
  67386. onError(scene, errorMessage, exception);
  67387. }
  67388. else {
  67389. BABYLON.Tools.Error(errorMessage);
  67390. // should the exception be thrown?
  67391. }
  67392. disposeHandler();
  67393. };
  67394. var progressHandler = onProgress ? function (event) {
  67395. try {
  67396. onProgress(event);
  67397. }
  67398. catch (e) {
  67399. errorHandler("Error in onProgress callback", e);
  67400. }
  67401. } : undefined;
  67402. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67403. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67404. if (onSuccess) {
  67405. try {
  67406. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67407. }
  67408. catch (e) {
  67409. errorHandler("Error in onSuccess callback", e);
  67410. }
  67411. }
  67412. scene._removePendingData(loadingToken);
  67413. };
  67414. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67415. if (plugin.rewriteRootURL) {
  67416. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67417. }
  67418. if (sceneFilename === "") {
  67419. if (sceneFilename === "") {
  67420. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67421. }
  67422. }
  67423. if (plugin.importMesh) {
  67424. var syncedPlugin = plugin;
  67425. var meshes = new Array();
  67426. var particleSystems = new Array();
  67427. var skeletons = new Array();
  67428. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67429. return;
  67430. }
  67431. scene.loadingPluginName = plugin.name;
  67432. successHandler(meshes, particleSystems, skeletons, []);
  67433. }
  67434. else {
  67435. var asyncedPlugin = plugin;
  67436. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67437. scene.loadingPluginName = plugin.name;
  67438. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67439. }).catch(function (error) {
  67440. errorHandler(error.message, error);
  67441. });
  67442. }
  67443. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67444. };
  67445. /**
  67446. * Import meshes into a scene
  67447. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67448. * @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)
  67449. * @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)
  67450. * @param scene the instance of BABYLON.Scene to append to
  67451. * @param onProgress a callback with a progress event for each file being loaded
  67452. * @param pluginExtension the extension used to determine the plugin
  67453. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67454. */
  67455. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67456. if (sceneFilename === void 0) { sceneFilename = ""; }
  67457. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67458. if (onProgress === void 0) { onProgress = null; }
  67459. if (pluginExtension === void 0) { pluginExtension = null; }
  67460. return new Promise(function (resolve, reject) {
  67461. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67462. resolve({
  67463. meshes: meshes,
  67464. particleSystems: particleSystems,
  67465. skeletons: skeletons,
  67466. animationGroups: animationGroups
  67467. });
  67468. }, onProgress, function (scene, message, exception) {
  67469. reject(exception || new Error(message));
  67470. }, pluginExtension);
  67471. });
  67472. };
  67473. /**
  67474. * Load a scene
  67475. * @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)
  67476. * @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)
  67477. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67478. * @param onSuccess a callback with the scene when import succeeds
  67479. * @param onProgress a callback with a progress event for each file being loaded
  67480. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67481. * @param pluginExtension the extension used to determine the plugin
  67482. * @returns The loaded plugin
  67483. */
  67484. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67485. if (onSuccess === void 0) { onSuccess = null; }
  67486. if (onProgress === void 0) { onProgress = null; }
  67487. if (onError === void 0) { onError = null; }
  67488. if (pluginExtension === void 0) { pluginExtension = null; }
  67489. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67490. };
  67491. /**
  67492. * Load a scene
  67493. * @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)
  67494. * @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)
  67495. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67496. * @param onProgress a callback with a progress event for each file being loaded
  67497. * @param pluginExtension the extension used to determine the plugin
  67498. * @returns The loaded scene
  67499. */
  67500. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67501. if (onProgress === void 0) { onProgress = null; }
  67502. if (pluginExtension === void 0) { pluginExtension = null; }
  67503. return new Promise(function (resolve, reject) {
  67504. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67505. resolve(scene);
  67506. }, onProgress, function (scene, message, exception) {
  67507. reject(exception || new Error(message));
  67508. }, pluginExtension);
  67509. });
  67510. };
  67511. /**
  67512. * Append a scene
  67513. * @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)
  67514. * @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)
  67515. * @param scene is the instance of BABYLON.Scene to append to
  67516. * @param onSuccess a callback with the scene when import succeeds
  67517. * @param onProgress a callback with a progress event for each file being loaded
  67518. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67519. * @param pluginExtension the extension used to determine the plugin
  67520. * @returns The loaded plugin
  67521. */
  67522. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67523. if (sceneFilename === void 0) { sceneFilename = ""; }
  67524. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67525. if (onSuccess === void 0) { onSuccess = null; }
  67526. if (onProgress === void 0) { onProgress = null; }
  67527. if (onError === void 0) { onError = null; }
  67528. if (pluginExtension === void 0) { pluginExtension = null; }
  67529. if (!scene) {
  67530. BABYLON.Tools.Error("No scene available to append to");
  67531. return null;
  67532. }
  67533. if (!sceneFilename) {
  67534. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67535. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67536. }
  67537. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67538. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67539. return null;
  67540. }
  67541. if (SceneLoader.ShowLoadingScreen) {
  67542. scene.getEngine().displayLoadingUI();
  67543. }
  67544. var loadingToken = {};
  67545. scene._addPendingData(loadingToken);
  67546. var disposeHandler = function () {
  67547. scene._removePendingData(loadingToken);
  67548. scene.getEngine().hideLoadingUI();
  67549. };
  67550. var errorHandler = function (message, exception) {
  67551. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67552. if (onError) {
  67553. onError(scene, errorMessage, exception);
  67554. }
  67555. else {
  67556. BABYLON.Tools.Error(errorMessage);
  67557. // should the exception be thrown?
  67558. }
  67559. disposeHandler();
  67560. };
  67561. var progressHandler = onProgress ? function (event) {
  67562. try {
  67563. onProgress(event);
  67564. }
  67565. catch (e) {
  67566. errorHandler("Error in onProgress callback", e);
  67567. }
  67568. } : undefined;
  67569. var successHandler = function () {
  67570. if (onSuccess) {
  67571. try {
  67572. onSuccess(scene);
  67573. }
  67574. catch (e) {
  67575. errorHandler("Error in onSuccess callback", e);
  67576. }
  67577. }
  67578. scene._removePendingData(loadingToken);
  67579. };
  67580. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67581. if (sceneFilename === "") {
  67582. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67583. }
  67584. if (plugin.load) {
  67585. var syncedPlugin = plugin;
  67586. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67587. return;
  67588. }
  67589. scene.loadingPluginName = plugin.name;
  67590. successHandler();
  67591. }
  67592. else {
  67593. var asyncedPlugin = plugin;
  67594. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67595. scene.loadingPluginName = plugin.name;
  67596. successHandler();
  67597. }).catch(function (error) {
  67598. errorHandler(error.message, error);
  67599. });
  67600. }
  67601. if (SceneLoader.ShowLoadingScreen) {
  67602. scene.executeWhenReady(function () {
  67603. scene.getEngine().hideLoadingUI();
  67604. });
  67605. }
  67606. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67607. };
  67608. /**
  67609. * Append a scene
  67610. * @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)
  67611. * @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)
  67612. * @param scene is the instance of BABYLON.Scene to append to
  67613. * @param onProgress a callback with a progress event for each file being loaded
  67614. * @param pluginExtension the extension used to determine the plugin
  67615. * @returns The given scene
  67616. */
  67617. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67618. if (sceneFilename === void 0) { sceneFilename = ""; }
  67619. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67620. if (onProgress === void 0) { onProgress = null; }
  67621. if (pluginExtension === void 0) { pluginExtension = null; }
  67622. return new Promise(function (resolve, reject) {
  67623. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67624. resolve(scene);
  67625. }, onProgress, function (scene, message, exception) {
  67626. reject(exception || new Error(message));
  67627. }, pluginExtension);
  67628. });
  67629. };
  67630. /**
  67631. * Load a scene into an asset container
  67632. * @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)
  67633. * @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)
  67634. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67635. * @param onSuccess a callback with the scene when import succeeds
  67636. * @param onProgress a callback with a progress event for each file being loaded
  67637. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67638. * @param pluginExtension the extension used to determine the plugin
  67639. * @returns The loaded plugin
  67640. */
  67641. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67642. if (sceneFilename === void 0) { sceneFilename = ""; }
  67643. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67644. if (onSuccess === void 0) { onSuccess = null; }
  67645. if (onProgress === void 0) { onProgress = null; }
  67646. if (onError === void 0) { onError = null; }
  67647. if (pluginExtension === void 0) { pluginExtension = null; }
  67648. if (!scene) {
  67649. BABYLON.Tools.Error("No scene available to load asset container to");
  67650. return null;
  67651. }
  67652. if (!sceneFilename) {
  67653. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67654. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67655. }
  67656. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67657. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67658. return null;
  67659. }
  67660. var loadingToken = {};
  67661. scene._addPendingData(loadingToken);
  67662. var disposeHandler = function () {
  67663. scene._removePendingData(loadingToken);
  67664. };
  67665. var errorHandler = function (message, exception) {
  67666. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67667. if (onError) {
  67668. onError(scene, errorMessage, exception);
  67669. }
  67670. else {
  67671. BABYLON.Tools.Error(errorMessage);
  67672. // should the exception be thrown?
  67673. }
  67674. disposeHandler();
  67675. };
  67676. var progressHandler = onProgress ? function (event) {
  67677. try {
  67678. onProgress(event);
  67679. }
  67680. catch (e) {
  67681. errorHandler("Error in onProgress callback", e);
  67682. }
  67683. } : undefined;
  67684. var successHandler = function (assets) {
  67685. if (onSuccess) {
  67686. try {
  67687. onSuccess(assets);
  67688. }
  67689. catch (e) {
  67690. errorHandler("Error in onSuccess callback", e);
  67691. }
  67692. }
  67693. scene._removePendingData(loadingToken);
  67694. };
  67695. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67696. if (plugin.loadAssetContainer) {
  67697. var syncedPlugin = plugin;
  67698. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67699. if (!assetContainer) {
  67700. return;
  67701. }
  67702. scene.loadingPluginName = plugin.name;
  67703. successHandler(assetContainer);
  67704. }
  67705. else if (plugin.loadAssetContainerAsync) {
  67706. var asyncedPlugin = plugin;
  67707. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67708. scene.loadingPluginName = plugin.name;
  67709. successHandler(assetContainer);
  67710. }).catch(function (error) {
  67711. errorHandler(error.message, error);
  67712. });
  67713. }
  67714. else {
  67715. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67716. }
  67717. if (SceneLoader.ShowLoadingScreen) {
  67718. scene.executeWhenReady(function () {
  67719. scene.getEngine().hideLoadingUI();
  67720. });
  67721. }
  67722. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67723. };
  67724. /**
  67725. * Load a scene into an asset container
  67726. * @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)
  67727. * @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)
  67728. * @param scene is the instance of BABYLON.Scene to append to
  67729. * @param onProgress a callback with a progress event for each file being loaded
  67730. * @param pluginExtension the extension used to determine the plugin
  67731. * @returns The loaded asset container
  67732. */
  67733. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67734. if (sceneFilename === void 0) { sceneFilename = ""; }
  67735. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67736. if (onProgress === void 0) { onProgress = null; }
  67737. if (pluginExtension === void 0) { pluginExtension = null; }
  67738. return new Promise(function (resolve, reject) {
  67739. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67740. resolve(assetContainer);
  67741. }, onProgress, function (scene, message, exception) {
  67742. reject(exception || new Error(message));
  67743. }, pluginExtension);
  67744. });
  67745. };
  67746. // Flags
  67747. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67748. SceneLoader._ShowLoadingScreen = true;
  67749. SceneLoader._CleanBoneMatrixWeights = false;
  67750. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67751. // Members
  67752. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67753. SceneLoader._registeredPlugins = {};
  67754. return SceneLoader;
  67755. }());
  67756. BABYLON.SceneLoader = SceneLoader;
  67757. ;
  67758. })(BABYLON || (BABYLON = {}));
  67759. //# sourceMappingURL=babylon.sceneLoader.js.map
  67760. var BABYLON;
  67761. (function (BABYLON) {
  67762. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67763. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67764. var parsedMaterial = parsedData.materials[index];
  67765. if (parsedMaterial.id === id) {
  67766. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67767. }
  67768. }
  67769. return null;
  67770. };
  67771. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67772. for (var i in names) {
  67773. if (mesh.name === names[i]) {
  67774. hierarchyIds.push(mesh.id);
  67775. return true;
  67776. }
  67777. }
  67778. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67779. hierarchyIds.push(mesh.id);
  67780. return true;
  67781. }
  67782. return false;
  67783. };
  67784. var logOperation = function (operation, producer) {
  67785. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67786. };
  67787. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67788. if (addToScene === void 0) { addToScene = false; }
  67789. var container = new BABYLON.AssetContainer(scene);
  67790. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67791. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67792. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67793. // and avoid problems with multiple concurrent .babylon loads.
  67794. var log = "importScene has failed JSON parse";
  67795. try {
  67796. var parsedData = JSON.parse(data);
  67797. log = "";
  67798. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67799. var index;
  67800. var cache;
  67801. // Lights
  67802. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67803. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67804. var parsedLight = parsedData.lights[index];
  67805. var light = BABYLON.Light.Parse(parsedLight, scene);
  67806. if (light) {
  67807. container.lights.push(light);
  67808. log += (index === 0 ? "\n\tLights:" : "");
  67809. log += "\n\t\t" + light.toString(fullDetails);
  67810. }
  67811. }
  67812. }
  67813. // Animations
  67814. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67815. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67816. var parsedAnimation = parsedData.animations[index];
  67817. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67818. scene.animations.push(animation);
  67819. container.animations.push(animation);
  67820. log += (index === 0 ? "\n\tAnimations:" : "");
  67821. log += "\n\t\t" + animation.toString(fullDetails);
  67822. }
  67823. }
  67824. // Materials
  67825. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67826. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67827. var parsedMaterial = parsedData.materials[index];
  67828. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67829. container.materials.push(mat);
  67830. log += (index === 0 ? "\n\tMaterials:" : "");
  67831. log += "\n\t\t" + mat.toString(fullDetails);
  67832. }
  67833. }
  67834. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67835. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67836. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67837. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67838. container.multiMaterials.push(mmat);
  67839. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67840. log += "\n\t\t" + mmat.toString(fullDetails);
  67841. }
  67842. }
  67843. // Morph targets
  67844. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67845. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67846. var managerData = _a[_i];
  67847. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67848. }
  67849. }
  67850. // Skeletons
  67851. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67852. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67853. var parsedSkeleton = parsedData.skeletons[index];
  67854. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67855. container.skeletons.push(skeleton);
  67856. log += (index === 0 ? "\n\tSkeletons:" : "");
  67857. log += "\n\t\t" + skeleton.toString(fullDetails);
  67858. }
  67859. }
  67860. // Geometries
  67861. var geometries = parsedData.geometries;
  67862. if (geometries !== undefined && geometries !== null) {
  67863. var addedGeometry = new Array();
  67864. // Boxes
  67865. var boxes = geometries.boxes;
  67866. if (boxes !== undefined && boxes !== null) {
  67867. for (index = 0, cache = boxes.length; index < cache; index++) {
  67868. var parsedBox = boxes[index];
  67869. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67870. }
  67871. }
  67872. // Spheres
  67873. var spheres = geometries.spheres;
  67874. if (spheres !== undefined && spheres !== null) {
  67875. for (index = 0, cache = spheres.length; index < cache; index++) {
  67876. var parsedSphere = spheres[index];
  67877. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67878. }
  67879. }
  67880. // Cylinders
  67881. var cylinders = geometries.cylinders;
  67882. if (cylinders !== undefined && cylinders !== null) {
  67883. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67884. var parsedCylinder = cylinders[index];
  67885. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67886. }
  67887. }
  67888. // Toruses
  67889. var toruses = geometries.toruses;
  67890. if (toruses !== undefined && toruses !== null) {
  67891. for (index = 0, cache = toruses.length; index < cache; index++) {
  67892. var parsedTorus = toruses[index];
  67893. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67894. }
  67895. }
  67896. // Grounds
  67897. var grounds = geometries.grounds;
  67898. if (grounds !== undefined && grounds !== null) {
  67899. for (index = 0, cache = grounds.length; index < cache; index++) {
  67900. var parsedGround = grounds[index];
  67901. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67902. }
  67903. }
  67904. // Planes
  67905. var planes = geometries.planes;
  67906. if (planes !== undefined && planes !== null) {
  67907. for (index = 0, cache = planes.length; index < cache; index++) {
  67908. var parsedPlane = planes[index];
  67909. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67910. }
  67911. }
  67912. // TorusKnots
  67913. var torusKnots = geometries.torusKnots;
  67914. if (torusKnots !== undefined && torusKnots !== null) {
  67915. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67916. var parsedTorusKnot = torusKnots[index];
  67917. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67918. }
  67919. }
  67920. // VertexData
  67921. var vertexData = geometries.vertexData;
  67922. if (vertexData !== undefined && vertexData !== null) {
  67923. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67924. var parsedVertexData = vertexData[index];
  67925. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67926. }
  67927. }
  67928. addedGeometry.forEach(function (g) {
  67929. if (g) {
  67930. container.geometries.push(g);
  67931. }
  67932. });
  67933. }
  67934. // Transform nodes
  67935. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67936. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67937. var parsedTransformNode = parsedData.transformNodes[index];
  67938. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67939. container.transformNodes.push(node);
  67940. }
  67941. }
  67942. // Meshes
  67943. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67944. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67945. var parsedMesh = parsedData.meshes[index];
  67946. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67947. container.meshes.push(mesh);
  67948. log += (index === 0 ? "\n\tMeshes:" : "");
  67949. log += "\n\t\t" + mesh.toString(fullDetails);
  67950. }
  67951. }
  67952. // Cameras
  67953. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67954. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67955. var parsedCamera = parsedData.cameras[index];
  67956. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67957. container.cameras.push(camera);
  67958. log += (index === 0 ? "\n\tCameras:" : "");
  67959. log += "\n\t\t" + camera.toString(fullDetails);
  67960. }
  67961. }
  67962. // Browsing all the graph to connect the dots
  67963. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67964. var camera = scene.cameras[index];
  67965. if (camera._waitingParentId) {
  67966. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67967. camera._waitingParentId = null;
  67968. }
  67969. }
  67970. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67971. var light_1 = scene.lights[index];
  67972. if (light_1 && light_1._waitingParentId) {
  67973. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67974. light_1._waitingParentId = null;
  67975. }
  67976. }
  67977. // Sounds
  67978. // TODO: add sound
  67979. var loadedSounds = [];
  67980. var loadedSound;
  67981. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67982. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67983. var parsedSound = parsedData.sounds[index];
  67984. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67985. if (!parsedSound.url)
  67986. parsedSound.url = parsedSound.name;
  67987. if (!loadedSounds[parsedSound.url]) {
  67988. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67989. loadedSounds[parsedSound.url] = loadedSound;
  67990. container.sounds.push(loadedSound);
  67991. }
  67992. else {
  67993. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67994. }
  67995. }
  67996. else {
  67997. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67998. }
  67999. }
  68000. }
  68001. loadedSounds = [];
  68002. // Connect parents & children and parse actions
  68003. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68004. var transformNode = scene.transformNodes[index];
  68005. if (transformNode._waitingParentId) {
  68006. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68007. transformNode._waitingParentId = null;
  68008. }
  68009. }
  68010. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68011. var mesh = scene.meshes[index];
  68012. if (mesh._waitingParentId) {
  68013. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68014. mesh._waitingParentId = null;
  68015. }
  68016. if (mesh._waitingActions) {
  68017. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68018. mesh._waitingActions = null;
  68019. }
  68020. }
  68021. // freeze world matrix application
  68022. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68023. var currentMesh = scene.meshes[index];
  68024. if (currentMesh._waitingFreezeWorldMatrix) {
  68025. currentMesh.freezeWorldMatrix();
  68026. currentMesh._waitingFreezeWorldMatrix = null;
  68027. }
  68028. else {
  68029. currentMesh.computeWorldMatrix(true);
  68030. }
  68031. }
  68032. // Particles Systems
  68033. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68034. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68035. var parsedParticleSystem = parsedData.particleSystems[index];
  68036. if (parsedParticleSystem.activeParticleCount) {
  68037. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68038. container.particleSystems.push(ps);
  68039. }
  68040. else {
  68041. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68042. container.particleSystems.push(ps);
  68043. }
  68044. }
  68045. }
  68046. // Lens flares
  68047. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68048. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68049. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68050. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68051. container.lensFlareSystems.push(lf);
  68052. }
  68053. }
  68054. // Shadows
  68055. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68056. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68057. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68058. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68059. container.shadowGenerators.push(sg);
  68060. }
  68061. }
  68062. // Lights exclusions / inclusions
  68063. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68064. var light_2 = scene.lights[index];
  68065. // Excluded check
  68066. if (light_2._excludedMeshesIds.length > 0) {
  68067. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68068. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68069. if (excludedMesh) {
  68070. light_2.excludedMeshes.push(excludedMesh);
  68071. }
  68072. }
  68073. light_2._excludedMeshesIds = [];
  68074. }
  68075. // Included check
  68076. if (light_2._includedOnlyMeshesIds.length > 0) {
  68077. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68078. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68079. if (includedOnlyMesh) {
  68080. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68081. }
  68082. }
  68083. light_2._includedOnlyMeshesIds = [];
  68084. }
  68085. }
  68086. // Effect layers
  68087. if (parsedData.effectLayers) {
  68088. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68089. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68090. container.effectLayers.push(effectLayer);
  68091. }
  68092. }
  68093. // Actions (scene)
  68094. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68095. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68096. }
  68097. if (!addToScene) {
  68098. container.removeAllFromScene();
  68099. }
  68100. }
  68101. catch (err) {
  68102. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68103. if (onError) {
  68104. onError(msg, err);
  68105. }
  68106. else {
  68107. BABYLON.Tools.Log(msg);
  68108. throw err;
  68109. }
  68110. }
  68111. finally {
  68112. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68113. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68114. }
  68115. }
  68116. return container;
  68117. };
  68118. BABYLON.SceneLoader.RegisterPlugin({
  68119. name: "babylon.js",
  68120. extensions: ".babylon",
  68121. canDirectLoad: function (data) {
  68122. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68123. return true;
  68124. }
  68125. return false;
  68126. },
  68127. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68128. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68129. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68130. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68131. // and avoid problems with multiple concurrent .babylon loads.
  68132. var log = "importMesh has failed JSON parse";
  68133. try {
  68134. var parsedData = JSON.parse(data);
  68135. log = "";
  68136. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68137. if (!meshesNames) {
  68138. meshesNames = null;
  68139. }
  68140. else if (!Array.isArray(meshesNames)) {
  68141. meshesNames = [meshesNames];
  68142. }
  68143. var hierarchyIds = new Array();
  68144. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68145. var loadedSkeletonsIds = [];
  68146. var loadedMaterialsIds = [];
  68147. var index;
  68148. var cache;
  68149. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68150. var parsedMesh = parsedData.meshes[index];
  68151. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68152. if (meshesNames !== null) {
  68153. // Remove found mesh name from list.
  68154. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68155. }
  68156. //Geometry?
  68157. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68158. //does the file contain geometries?
  68159. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68160. //find the correct geometry and add it to the scene
  68161. var found = false;
  68162. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68163. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68164. return;
  68165. }
  68166. else {
  68167. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68168. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68169. switch (geometryType) {
  68170. case "boxes":
  68171. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68172. break;
  68173. case "spheres":
  68174. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68175. break;
  68176. case "cylinders":
  68177. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68178. break;
  68179. case "toruses":
  68180. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68181. break;
  68182. case "grounds":
  68183. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68184. break;
  68185. case "planes":
  68186. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68187. break;
  68188. case "torusKnots":
  68189. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68190. break;
  68191. case "vertexData":
  68192. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68193. break;
  68194. }
  68195. found = true;
  68196. }
  68197. });
  68198. }
  68199. });
  68200. if (found === false) {
  68201. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68202. }
  68203. }
  68204. }
  68205. // Material ?
  68206. if (parsedMesh.materialId) {
  68207. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68208. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68209. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68210. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68211. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68212. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68213. var subMatId = parsedMultiMaterial.materials[matIndex];
  68214. loadedMaterialsIds.push(subMatId);
  68215. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68216. if (mat) {
  68217. log += "\n\tMaterial " + mat.toString(fullDetails);
  68218. }
  68219. }
  68220. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68221. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68222. if (mmat) {
  68223. materialFound = true;
  68224. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68225. }
  68226. break;
  68227. }
  68228. }
  68229. }
  68230. if (materialFound === false) {
  68231. loadedMaterialsIds.push(parsedMesh.materialId);
  68232. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68233. if (!mat) {
  68234. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68235. }
  68236. else {
  68237. log += "\n\tMaterial " + mat.toString(fullDetails);
  68238. }
  68239. }
  68240. }
  68241. // Skeleton ?
  68242. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68243. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68244. if (skeletonAlreadyLoaded === false) {
  68245. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68246. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68247. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68248. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68249. skeletons.push(skeleton);
  68250. loadedSkeletonsIds.push(parsedSkeleton.id);
  68251. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68252. }
  68253. }
  68254. }
  68255. }
  68256. // Morph targets ?
  68257. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68258. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68259. var managerData = _a[_i];
  68260. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68261. }
  68262. }
  68263. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68264. meshes.push(mesh);
  68265. log += "\n\tMesh " + mesh.toString(fullDetails);
  68266. }
  68267. }
  68268. // Connecting parents
  68269. var currentMesh;
  68270. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68271. currentMesh = scene.meshes[index];
  68272. if (currentMesh._waitingParentId) {
  68273. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68274. currentMesh._waitingParentId = null;
  68275. }
  68276. }
  68277. // freeze and compute world matrix application
  68278. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68279. currentMesh = scene.meshes[index];
  68280. if (currentMesh._waitingFreezeWorldMatrix) {
  68281. currentMesh.freezeWorldMatrix();
  68282. currentMesh._waitingFreezeWorldMatrix = null;
  68283. }
  68284. else {
  68285. currentMesh.computeWorldMatrix(true);
  68286. }
  68287. }
  68288. }
  68289. // Particles
  68290. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68291. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68292. var parsedParticleSystem = parsedData.particleSystems[index];
  68293. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68294. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68295. }
  68296. }
  68297. }
  68298. return true;
  68299. }
  68300. catch (err) {
  68301. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68302. if (onError) {
  68303. onError(msg, err);
  68304. }
  68305. else {
  68306. BABYLON.Tools.Log(msg);
  68307. throw err;
  68308. }
  68309. }
  68310. finally {
  68311. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68312. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68313. }
  68314. }
  68315. return false;
  68316. },
  68317. load: function (scene, data, rootUrl, onError) {
  68318. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68319. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68320. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68321. // and avoid problems with multiple concurrent .babylon loads.
  68322. var log = "importScene has failed JSON parse";
  68323. try {
  68324. var parsedData = JSON.parse(data);
  68325. log = "";
  68326. // Scene
  68327. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68328. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68329. }
  68330. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68331. scene.autoClear = parsedData.autoClear;
  68332. }
  68333. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68334. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68335. }
  68336. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68337. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68338. }
  68339. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68340. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68341. }
  68342. // Fog
  68343. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68344. scene.fogMode = parsedData.fogMode;
  68345. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68346. scene.fogStart = parsedData.fogStart;
  68347. scene.fogEnd = parsedData.fogEnd;
  68348. scene.fogDensity = parsedData.fogDensity;
  68349. log += "\tFog mode for scene: ";
  68350. switch (scene.fogMode) {
  68351. // getters not compiling, so using hardcoded
  68352. case 1:
  68353. log += "exp\n";
  68354. break;
  68355. case 2:
  68356. log += "exp2\n";
  68357. break;
  68358. case 3:
  68359. log += "linear\n";
  68360. break;
  68361. }
  68362. }
  68363. //Physics
  68364. if (parsedData.physicsEnabled) {
  68365. var physicsPlugin;
  68366. if (parsedData.physicsEngine === "cannon") {
  68367. physicsPlugin = new BABYLON.CannonJSPlugin();
  68368. }
  68369. else if (parsedData.physicsEngine === "oimo") {
  68370. physicsPlugin = new BABYLON.OimoJSPlugin();
  68371. }
  68372. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68373. //else - default engine, which is currently oimo
  68374. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68375. scene.enablePhysics(physicsGravity, physicsPlugin);
  68376. }
  68377. // Metadata
  68378. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68379. scene.metadata = parsedData.metadata;
  68380. }
  68381. //collisions, if defined. otherwise, default is true
  68382. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68383. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68384. }
  68385. scene.workerCollisions = !!parsedData.workerCollisions;
  68386. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68387. if (!container) {
  68388. return false;
  68389. }
  68390. if (parsedData.autoAnimate) {
  68391. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68392. }
  68393. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68394. scene.setActiveCameraByID(parsedData.activeCameraID);
  68395. }
  68396. // Environment texture
  68397. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68398. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68399. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68400. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68401. if (parsedData.environmentTextureRotationY) {
  68402. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68403. }
  68404. scene.environmentTexture = hdrTexture;
  68405. }
  68406. else {
  68407. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68408. if (parsedData.environmentTextureRotationY) {
  68409. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68410. }
  68411. scene.environmentTexture = cubeTexture;
  68412. }
  68413. if (parsedData.createDefaultSkybox === true) {
  68414. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68415. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68416. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68417. }
  68418. }
  68419. // Finish
  68420. return true;
  68421. }
  68422. catch (err) {
  68423. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68424. if (onError) {
  68425. onError(msg, err);
  68426. }
  68427. else {
  68428. BABYLON.Tools.Log(msg);
  68429. throw err;
  68430. }
  68431. }
  68432. finally {
  68433. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68434. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68435. }
  68436. }
  68437. return false;
  68438. },
  68439. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68440. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68441. return container;
  68442. }
  68443. });
  68444. })(BABYLON || (BABYLON = {}));
  68445. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68446. var BABYLON;
  68447. (function (BABYLON) {
  68448. var FilesInput = /** @class */ (function () {
  68449. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68450. this.onProcessFileCallback = function () { return true; };
  68451. this._engine = engine;
  68452. this._currentScene = scene;
  68453. this._sceneLoadedCallback = sceneLoadedCallback;
  68454. this._progressCallback = progressCallback;
  68455. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68456. this._textureLoadingCallback = textureLoadingCallback;
  68457. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68458. this._onReloadCallback = onReloadCallback;
  68459. this._errorCallback = errorCallback;
  68460. }
  68461. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68462. var _this = this;
  68463. if (elementToMonitor) {
  68464. this._elementToMonitor = elementToMonitor;
  68465. this._dragEnterHandler = function (e) { _this.drag(e); };
  68466. this._dragOverHandler = function (e) { _this.drag(e); };
  68467. this._dropHandler = function (e) { _this.drop(e); };
  68468. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68469. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68470. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68471. }
  68472. };
  68473. FilesInput.prototype.dispose = function () {
  68474. if (!this._elementToMonitor) {
  68475. return;
  68476. }
  68477. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68478. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68479. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68480. };
  68481. FilesInput.prototype.renderFunction = function () {
  68482. if (this._additionalRenderLoopLogicCallback) {
  68483. this._additionalRenderLoopLogicCallback();
  68484. }
  68485. if (this._currentScene) {
  68486. if (this._textureLoadingCallback) {
  68487. var remaining = this._currentScene.getWaitingItemsCount();
  68488. if (remaining > 0) {
  68489. this._textureLoadingCallback(remaining);
  68490. }
  68491. }
  68492. this._currentScene.render();
  68493. }
  68494. };
  68495. FilesInput.prototype.drag = function (e) {
  68496. e.stopPropagation();
  68497. e.preventDefault();
  68498. };
  68499. FilesInput.prototype.drop = function (eventDrop) {
  68500. eventDrop.stopPropagation();
  68501. eventDrop.preventDefault();
  68502. this.loadFiles(eventDrop);
  68503. };
  68504. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68505. var _this = this;
  68506. var reader = folder.createReader();
  68507. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68508. reader.readEntries(function (entries) {
  68509. remaining.count += entries.length;
  68510. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68511. var entry = entries_1[_i];
  68512. if (entry.isFile) {
  68513. entry.file(function (file) {
  68514. file.correctName = relativePath + file.name;
  68515. files.push(file);
  68516. if (--remaining.count === 0) {
  68517. callback();
  68518. }
  68519. });
  68520. }
  68521. else if (entry.isDirectory) {
  68522. _this._traverseFolder(entry, files, remaining, callback);
  68523. }
  68524. }
  68525. if (--remaining.count) {
  68526. callback();
  68527. }
  68528. });
  68529. };
  68530. FilesInput.prototype._processFiles = function (files) {
  68531. for (var i = 0; i < files.length; i++) {
  68532. var name = files[i].correctName.toLowerCase();
  68533. var extension = name.split('.').pop();
  68534. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68535. continue;
  68536. }
  68537. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68538. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68539. this._sceneFileToLoad = files[i];
  68540. }
  68541. else {
  68542. FilesInput.FilesToLoad[name] = files[i];
  68543. }
  68544. }
  68545. };
  68546. FilesInput.prototype.loadFiles = function (event) {
  68547. var _this = this;
  68548. if (this._startingProcessingFilesCallback)
  68549. this._startingProcessingFilesCallback();
  68550. // Handling data transfer via drag'n'drop
  68551. if (event && event.dataTransfer && event.dataTransfer.files) {
  68552. this._filesToLoad = event.dataTransfer.files;
  68553. }
  68554. // Handling files from input files
  68555. if (event && event.target && event.target.files) {
  68556. this._filesToLoad = event.target.files;
  68557. }
  68558. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68559. var files_1 = new Array();
  68560. var folders = [];
  68561. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68562. for (var i = 0; i < this._filesToLoad.length; i++) {
  68563. var fileToLoad = this._filesToLoad[i];
  68564. var name_1 = fileToLoad.name.toLowerCase();
  68565. var entry = void 0;
  68566. fileToLoad.correctName = name_1;
  68567. if (items) {
  68568. var item = items[i];
  68569. if (item.getAsEntry) {
  68570. entry = item.getAsEntry();
  68571. }
  68572. else if (item.webkitGetAsEntry) {
  68573. entry = item.webkitGetAsEntry();
  68574. }
  68575. }
  68576. if (!entry) {
  68577. files_1.push(fileToLoad);
  68578. }
  68579. else {
  68580. if (entry.isDirectory) {
  68581. folders.push(entry);
  68582. }
  68583. else {
  68584. files_1.push(fileToLoad);
  68585. }
  68586. }
  68587. }
  68588. if (folders.length === 0) {
  68589. this._processFiles(files_1);
  68590. this._processReload();
  68591. }
  68592. else {
  68593. var remaining = { count: folders.length };
  68594. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68595. var folder = folders_1[_i];
  68596. this._traverseFolder(folder, files_1, remaining, function () {
  68597. _this._processFiles(files_1);
  68598. if (remaining.count === 0) {
  68599. _this._processReload();
  68600. }
  68601. });
  68602. }
  68603. }
  68604. }
  68605. };
  68606. FilesInput.prototype._processReload = function () {
  68607. if (this._onReloadCallback) {
  68608. this._onReloadCallback(this._sceneFileToLoad);
  68609. }
  68610. else {
  68611. this.reload();
  68612. }
  68613. };
  68614. FilesInput.prototype.reload = function () {
  68615. var _this = this;
  68616. // If a scene file has been provided
  68617. if (this._sceneFileToLoad) {
  68618. if (this._currentScene) {
  68619. if (BABYLON.Tools.errorsCount > 0) {
  68620. BABYLON.Tools.ClearLogCache();
  68621. }
  68622. this._engine.stopRenderLoop();
  68623. }
  68624. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68625. if (_this._progressCallback) {
  68626. _this._progressCallback(progress);
  68627. }
  68628. }).then(function (scene) {
  68629. if (_this._currentScene) {
  68630. _this._currentScene.dispose();
  68631. }
  68632. _this._currentScene = scene;
  68633. if (_this._sceneLoadedCallback) {
  68634. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68635. }
  68636. // Wait for textures and shaders to be ready
  68637. _this._currentScene.executeWhenReady(function () {
  68638. _this._engine.runRenderLoop(function () {
  68639. _this.renderFunction();
  68640. });
  68641. });
  68642. }).catch(function (error) {
  68643. if (_this._errorCallback) {
  68644. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68645. }
  68646. });
  68647. }
  68648. else {
  68649. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68650. }
  68651. };
  68652. FilesInput.FilesToLoad = {};
  68653. return FilesInput;
  68654. }());
  68655. BABYLON.FilesInput = FilesInput;
  68656. })(BABYLON || (BABYLON = {}));
  68657. //# sourceMappingURL=babylon.filesInput.js.map
  68658. var BABYLON;
  68659. (function (BABYLON) {
  68660. /**
  68661. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68662. * The underlying implementation relies on an associative array to ensure the best performances.
  68663. * The value can be anything including 'null' but except 'undefined'
  68664. */
  68665. var StringDictionary = /** @class */ (function () {
  68666. function StringDictionary() {
  68667. this._count = 0;
  68668. this._data = {};
  68669. }
  68670. /**
  68671. * This will clear this dictionary and copy the content from the 'source' one.
  68672. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68673. * @param source the dictionary to take the content from and copy to this dictionary
  68674. */
  68675. StringDictionary.prototype.copyFrom = function (source) {
  68676. var _this = this;
  68677. this.clear();
  68678. source.forEach(function (t, v) { return _this.add(t, v); });
  68679. };
  68680. /**
  68681. * Get a value based from its key
  68682. * @param key the given key to get the matching value from
  68683. * @return the value if found, otherwise undefined is returned
  68684. */
  68685. StringDictionary.prototype.get = function (key) {
  68686. var val = this._data[key];
  68687. if (val !== undefined) {
  68688. return val;
  68689. }
  68690. return undefined;
  68691. };
  68692. /**
  68693. * Get a value from its key or add it if it doesn't exist.
  68694. * This method will ensure you that a given key/data will be present in the dictionary.
  68695. * @param key the given key to get the matching value from
  68696. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68697. * The factory will only be invoked if there's no data for the given key.
  68698. * @return the value corresponding to the key.
  68699. */
  68700. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68701. var val = this.get(key);
  68702. if (val !== undefined) {
  68703. return val;
  68704. }
  68705. val = factory(key);
  68706. if (val) {
  68707. this.add(key, val);
  68708. }
  68709. return val;
  68710. };
  68711. /**
  68712. * Get a value from its key if present in the dictionary otherwise add it
  68713. * @param key the key to get the value from
  68714. * @param val if there's no such key/value pair in the dictionary add it with this value
  68715. * @return the value corresponding to the key
  68716. */
  68717. StringDictionary.prototype.getOrAdd = function (key, val) {
  68718. var curVal = this.get(key);
  68719. if (curVal !== undefined) {
  68720. return curVal;
  68721. }
  68722. this.add(key, val);
  68723. return val;
  68724. };
  68725. /**
  68726. * Check if there's a given key in the dictionary
  68727. * @param key the key to check for
  68728. * @return true if the key is present, false otherwise
  68729. */
  68730. StringDictionary.prototype.contains = function (key) {
  68731. return this._data[key] !== undefined;
  68732. };
  68733. /**
  68734. * Add a new key and its corresponding value
  68735. * @param key the key to add
  68736. * @param value the value corresponding to the key
  68737. * @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
  68738. */
  68739. StringDictionary.prototype.add = function (key, value) {
  68740. if (this._data[key] !== undefined) {
  68741. return false;
  68742. }
  68743. this._data[key] = value;
  68744. ++this._count;
  68745. return true;
  68746. };
  68747. StringDictionary.prototype.set = function (key, value) {
  68748. if (this._data[key] === undefined) {
  68749. return false;
  68750. }
  68751. this._data[key] = value;
  68752. return true;
  68753. };
  68754. /**
  68755. * Get the element of the given key and remove it from the dictionary
  68756. * @param key
  68757. */
  68758. StringDictionary.prototype.getAndRemove = function (key) {
  68759. var val = this.get(key);
  68760. if (val !== undefined) {
  68761. delete this._data[key];
  68762. --this._count;
  68763. return val;
  68764. }
  68765. return null;
  68766. };
  68767. /**
  68768. * Remove a key/value from the dictionary.
  68769. * @param key the key to remove
  68770. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68771. */
  68772. StringDictionary.prototype.remove = function (key) {
  68773. if (this.contains(key)) {
  68774. delete this._data[key];
  68775. --this._count;
  68776. return true;
  68777. }
  68778. return false;
  68779. };
  68780. /**
  68781. * Clear the whole content of the dictionary
  68782. */
  68783. StringDictionary.prototype.clear = function () {
  68784. this._data = {};
  68785. this._count = 0;
  68786. };
  68787. Object.defineProperty(StringDictionary.prototype, "count", {
  68788. get: function () {
  68789. return this._count;
  68790. },
  68791. enumerable: true,
  68792. configurable: true
  68793. });
  68794. /**
  68795. * Execute a callback on each key/val of the dictionary.
  68796. * Note that you can remove any element in this dictionary in the callback implementation
  68797. * @param callback the callback to execute on a given key/value pair
  68798. */
  68799. StringDictionary.prototype.forEach = function (callback) {
  68800. for (var cur in this._data) {
  68801. var val = this._data[cur];
  68802. callback(cur, val);
  68803. }
  68804. };
  68805. /**
  68806. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68807. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68808. * Note that you can remove any element in this dictionary in the callback implementation
  68809. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68810. */
  68811. StringDictionary.prototype.first = function (callback) {
  68812. for (var cur in this._data) {
  68813. var val = this._data[cur];
  68814. var res = callback(cur, val);
  68815. if (res) {
  68816. return res;
  68817. }
  68818. }
  68819. return null;
  68820. };
  68821. return StringDictionary;
  68822. }());
  68823. BABYLON.StringDictionary = StringDictionary;
  68824. })(BABYLON || (BABYLON = {}));
  68825. //# sourceMappingURL=babylon.stringDictionary.js.map
  68826. var BABYLON;
  68827. (function (BABYLON) {
  68828. var Tags = /** @class */ (function () {
  68829. function Tags() {
  68830. }
  68831. Tags.EnableFor = function (obj) {
  68832. obj._tags = obj._tags || {};
  68833. obj.hasTags = function () {
  68834. return Tags.HasTags(obj);
  68835. };
  68836. obj.addTags = function (tagsString) {
  68837. return Tags.AddTagsTo(obj, tagsString);
  68838. };
  68839. obj.removeTags = function (tagsString) {
  68840. return Tags.RemoveTagsFrom(obj, tagsString);
  68841. };
  68842. obj.matchesTagsQuery = function (tagsQuery) {
  68843. return Tags.MatchesQuery(obj, tagsQuery);
  68844. };
  68845. };
  68846. Tags.DisableFor = function (obj) {
  68847. delete obj._tags;
  68848. delete obj.hasTags;
  68849. delete obj.addTags;
  68850. delete obj.removeTags;
  68851. delete obj.matchesTagsQuery;
  68852. };
  68853. Tags.HasTags = function (obj) {
  68854. if (!obj._tags) {
  68855. return false;
  68856. }
  68857. return !BABYLON.Tools.IsEmpty(obj._tags);
  68858. };
  68859. Tags.GetTags = function (obj, asString) {
  68860. if (asString === void 0) { asString = true; }
  68861. if (!obj._tags) {
  68862. return null;
  68863. }
  68864. if (asString) {
  68865. var tagsArray = [];
  68866. for (var tag in obj._tags) {
  68867. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68868. tagsArray.push(tag);
  68869. }
  68870. }
  68871. return tagsArray.join(" ");
  68872. }
  68873. else {
  68874. return obj._tags;
  68875. }
  68876. };
  68877. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68878. // a tag cannot start with '||', '&&', and '!'
  68879. // it cannot contain whitespaces
  68880. Tags.AddTagsTo = function (obj, tagsString) {
  68881. if (!tagsString) {
  68882. return;
  68883. }
  68884. if (typeof tagsString !== "string") {
  68885. return;
  68886. }
  68887. var tags = tagsString.split(" ");
  68888. tags.forEach(function (tag, index, array) {
  68889. Tags._AddTagTo(obj, tag);
  68890. });
  68891. };
  68892. Tags._AddTagTo = function (obj, tag) {
  68893. tag = tag.trim();
  68894. if (tag === "" || tag === "true" || tag === "false") {
  68895. return;
  68896. }
  68897. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68898. return;
  68899. }
  68900. Tags.EnableFor(obj);
  68901. obj._tags[tag] = true;
  68902. };
  68903. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68904. if (!Tags.HasTags(obj)) {
  68905. return;
  68906. }
  68907. var tags = tagsString.split(" ");
  68908. for (var t in tags) {
  68909. Tags._RemoveTagFrom(obj, tags[t]);
  68910. }
  68911. };
  68912. Tags._RemoveTagFrom = function (obj, tag) {
  68913. delete obj._tags[tag];
  68914. };
  68915. Tags.MatchesQuery = function (obj, tagsQuery) {
  68916. if (tagsQuery === undefined) {
  68917. return true;
  68918. }
  68919. if (tagsQuery === "") {
  68920. return Tags.HasTags(obj);
  68921. }
  68922. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68923. };
  68924. return Tags;
  68925. }());
  68926. BABYLON.Tags = Tags;
  68927. })(BABYLON || (BABYLON = {}));
  68928. //# sourceMappingURL=babylon.tags.js.map
  68929. var BABYLON;
  68930. (function (BABYLON) {
  68931. /**
  68932. * Class used to evalaute queries containing `and` and `or` operators
  68933. */
  68934. var AndOrNotEvaluator = /** @class */ (function () {
  68935. function AndOrNotEvaluator() {
  68936. }
  68937. /**
  68938. * Evaluate a query
  68939. * @param query defines the query to evaluate
  68940. * @param evaluateCallback defines the callback used to filter result
  68941. * @returns true if the query matches
  68942. */
  68943. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68944. if (!query.match(/\([^\(\)]*\)/g)) {
  68945. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68946. }
  68947. else {
  68948. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68949. // remove parenthesis
  68950. r = r.slice(1, r.length - 1);
  68951. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68952. });
  68953. }
  68954. if (query === "true") {
  68955. return true;
  68956. }
  68957. if (query === "false") {
  68958. return false;
  68959. }
  68960. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68961. };
  68962. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68963. evaluateCallback = evaluateCallback || (function (r) {
  68964. return r === "true" ? true : false;
  68965. });
  68966. var result;
  68967. var or = parenthesisContent.split("||");
  68968. for (var i in or) {
  68969. if (or.hasOwnProperty(i)) {
  68970. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68971. var and = ori.split("&&");
  68972. if (and.length > 1) {
  68973. for (var j = 0; j < and.length; ++j) {
  68974. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68975. if (andj !== "true" && andj !== "false") {
  68976. if (andj[0] === "!") {
  68977. result = !evaluateCallback(andj.substring(1));
  68978. }
  68979. else {
  68980. result = evaluateCallback(andj);
  68981. }
  68982. }
  68983. else {
  68984. result = andj === "true" ? true : false;
  68985. }
  68986. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68987. ori = "false";
  68988. break;
  68989. }
  68990. }
  68991. }
  68992. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68993. result = true;
  68994. break;
  68995. }
  68996. // result equals false (or undefined)
  68997. if (ori !== "true" && ori !== "false") {
  68998. if (ori[0] === "!") {
  68999. result = !evaluateCallback(ori.substring(1));
  69000. }
  69001. else {
  69002. result = evaluateCallback(ori);
  69003. }
  69004. }
  69005. else {
  69006. result = ori === "true" ? true : false;
  69007. }
  69008. }
  69009. }
  69010. // the whole parenthesis scope is replaced by 'true' or 'false'
  69011. return result ? "true" : "false";
  69012. };
  69013. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69014. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69015. // remove whitespaces
  69016. r = r.replace(/[\s]/g, function () { return ""; });
  69017. return r.length % 2 ? "!" : "";
  69018. });
  69019. booleanString = booleanString.trim();
  69020. if (booleanString === "!true") {
  69021. booleanString = "false";
  69022. }
  69023. else if (booleanString === "!false") {
  69024. booleanString = "true";
  69025. }
  69026. return booleanString;
  69027. };
  69028. return AndOrNotEvaluator;
  69029. }());
  69030. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69031. })(BABYLON || (BABYLON = {}));
  69032. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69033. var BABYLON;
  69034. (function (BABYLON) {
  69035. /**
  69036. * Class used to enable access to IndexedDB
  69037. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69038. */
  69039. var Database = /** @class */ (function () {
  69040. /**
  69041. * Creates a new Database
  69042. * @param urlToScene defines the url to load the scene
  69043. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69044. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69045. */
  69046. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69047. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69048. var _this = this;
  69049. // Handling various flavors of prefixed version of IndexedDB
  69050. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69051. this.callbackManifestChecked = callbackManifestChecked;
  69052. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69053. this.db = null;
  69054. this._enableSceneOffline = false;
  69055. this._enableTexturesOffline = false;
  69056. this.manifestVersionFound = 0;
  69057. this.mustUpdateRessources = false;
  69058. this.hasReachedQuota = false;
  69059. if (!Database.IDBStorageEnabled) {
  69060. this.callbackManifestChecked(true);
  69061. }
  69062. else {
  69063. if (disableManifestCheck) {
  69064. this._enableSceneOffline = true;
  69065. this._enableTexturesOffline = true;
  69066. this.manifestVersionFound = 1;
  69067. BABYLON.Tools.SetImmediate(function () {
  69068. _this.callbackManifestChecked(true);
  69069. });
  69070. }
  69071. else {
  69072. this._checkManifestFile();
  69073. }
  69074. }
  69075. }
  69076. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69077. /**
  69078. * Gets a boolean indicating if scene must be saved in the database
  69079. */
  69080. get: function () {
  69081. return this._enableSceneOffline;
  69082. },
  69083. enumerable: true,
  69084. configurable: true
  69085. });
  69086. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69087. /**
  69088. * Gets a boolean indicating if textures must be saved in the database
  69089. */
  69090. get: function () {
  69091. return this._enableTexturesOffline;
  69092. },
  69093. enumerable: true,
  69094. configurable: true
  69095. });
  69096. Database.prototype._checkManifestFile = function () {
  69097. var _this = this;
  69098. var noManifestFile = function () {
  69099. _this._enableSceneOffline = false;
  69100. _this._enableTexturesOffline = false;
  69101. _this.callbackManifestChecked(false);
  69102. };
  69103. var timeStampUsed = false;
  69104. var manifestURL = this.currentSceneUrl + ".manifest";
  69105. var xhr = new XMLHttpRequest();
  69106. if (navigator.onLine) {
  69107. // Adding a timestamp to by-pass browsers' cache
  69108. timeStampUsed = true;
  69109. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69110. }
  69111. xhr.open("GET", manifestURL, true);
  69112. xhr.addEventListener("load", function () {
  69113. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69114. try {
  69115. var manifestFile = JSON.parse(xhr.response);
  69116. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69117. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69118. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69119. _this.manifestVersionFound = manifestFile.version;
  69120. }
  69121. if (_this.callbackManifestChecked) {
  69122. _this.callbackManifestChecked(true);
  69123. }
  69124. }
  69125. catch (ex) {
  69126. noManifestFile();
  69127. }
  69128. }
  69129. else {
  69130. noManifestFile();
  69131. }
  69132. }, false);
  69133. xhr.addEventListener("error", function (event) {
  69134. if (timeStampUsed) {
  69135. timeStampUsed = false;
  69136. // Let's retry without the timeStamp
  69137. // It could fail when coupled with HTML5 Offline API
  69138. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69139. xhr.open("GET", retryManifestURL, true);
  69140. xhr.send();
  69141. }
  69142. else {
  69143. noManifestFile();
  69144. }
  69145. }, false);
  69146. try {
  69147. xhr.send();
  69148. }
  69149. catch (ex) {
  69150. BABYLON.Tools.Error("Error on XHR send request.");
  69151. this.callbackManifestChecked(false);
  69152. }
  69153. };
  69154. /**
  69155. * Open the database and make it available
  69156. * @param successCallback defines the callback to call on success
  69157. * @param errorCallback defines the callback to call on error
  69158. */
  69159. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69160. var _this = this;
  69161. var handleError = function () {
  69162. _this.isSupported = false;
  69163. if (errorCallback)
  69164. errorCallback();
  69165. };
  69166. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69167. // Your browser doesn't support IndexedDB
  69168. this.isSupported = false;
  69169. if (errorCallback)
  69170. errorCallback();
  69171. }
  69172. else {
  69173. // If the DB hasn't been opened or created yet
  69174. if (!this.db) {
  69175. this.hasReachedQuota = false;
  69176. this.isSupported = true;
  69177. var request = this.idbFactory.open("babylonjs", 1);
  69178. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69179. request.onerror = function (event) {
  69180. handleError();
  69181. };
  69182. // executes when a version change transaction cannot complete due to other active transactions
  69183. request.onblocked = function (event) {
  69184. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69185. handleError();
  69186. };
  69187. // DB has been opened successfully
  69188. request.onsuccess = function (event) {
  69189. _this.db = request.result;
  69190. successCallback();
  69191. };
  69192. // Initialization of the DB. Creating Scenes & Textures stores
  69193. request.onupgradeneeded = function (event) {
  69194. _this.db = (event.target).result;
  69195. if (_this.db) {
  69196. try {
  69197. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69198. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69199. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69200. }
  69201. catch (ex) {
  69202. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69203. handleError();
  69204. }
  69205. }
  69206. };
  69207. }
  69208. // DB has already been created and opened
  69209. else {
  69210. if (successCallback)
  69211. successCallback();
  69212. }
  69213. }
  69214. };
  69215. /**
  69216. * Loads an image from the database
  69217. * @param url defines the url to load from
  69218. * @param image defines the target DOM image
  69219. */
  69220. Database.prototype.loadImageFromDB = function (url, image) {
  69221. var _this = this;
  69222. var completeURL = Database._ReturnFullUrlLocation(url);
  69223. var saveAndLoadImage = function () {
  69224. if (!_this.hasReachedQuota && _this.db !== null) {
  69225. // the texture is not yet in the DB, let's try to save it
  69226. _this._saveImageIntoDBAsync(completeURL, image);
  69227. }
  69228. // If the texture is not in the DB and we've reached the DB quota limit
  69229. // let's load it directly from the web
  69230. else {
  69231. image.src = url;
  69232. }
  69233. };
  69234. if (!this.mustUpdateRessources) {
  69235. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69236. }
  69237. // First time we're download the images or update requested in the manifest file by a version change
  69238. else {
  69239. saveAndLoadImage();
  69240. }
  69241. };
  69242. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69243. if (this.isSupported && this.db !== null) {
  69244. var texture;
  69245. var transaction = this.db.transaction(["textures"]);
  69246. transaction.onabort = function (event) {
  69247. image.src = url;
  69248. };
  69249. transaction.oncomplete = function (event) {
  69250. var blobTextureURL;
  69251. if (texture) {
  69252. var URL = window.URL || window.webkitURL;
  69253. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69254. image.onerror = function () {
  69255. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69256. image.src = url;
  69257. };
  69258. image.src = blobTextureURL;
  69259. }
  69260. else {
  69261. notInDBCallback();
  69262. }
  69263. };
  69264. var getRequest = transaction.objectStore("textures").get(url);
  69265. getRequest.onsuccess = function (event) {
  69266. texture = (event.target).result;
  69267. };
  69268. getRequest.onerror = function (event) {
  69269. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69270. image.src = url;
  69271. };
  69272. }
  69273. else {
  69274. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69275. image.src = url;
  69276. }
  69277. };
  69278. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69279. var _this = this;
  69280. if (this.isSupported) {
  69281. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69282. var generateBlobUrl = function () {
  69283. var blobTextureURL;
  69284. if (blob) {
  69285. var URL = window.URL || window.webkitURL;
  69286. try {
  69287. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69288. }
  69289. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69290. catch (ex) {
  69291. blobTextureURL = URL.createObjectURL(blob);
  69292. }
  69293. }
  69294. if (blobTextureURL) {
  69295. image.src = blobTextureURL;
  69296. }
  69297. };
  69298. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69299. var xhr = new XMLHttpRequest(), blob;
  69300. xhr.open("GET", url, true);
  69301. xhr.responseType = "blob";
  69302. xhr.addEventListener("load", function () {
  69303. if (xhr.status === 200 && _this.db) {
  69304. // Blob as response (XHR2)
  69305. blob = xhr.response;
  69306. var transaction = _this.db.transaction(["textures"], "readwrite");
  69307. // the transaction could abort because of a QuotaExceededError error
  69308. transaction.onabort = function (event) {
  69309. try {
  69310. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69311. var srcElement = (event.srcElement || event.target);
  69312. var error = srcElement.error;
  69313. if (error && error.name === "QuotaExceededError") {
  69314. _this.hasReachedQuota = true;
  69315. }
  69316. }
  69317. catch (ex) { }
  69318. generateBlobUrl();
  69319. };
  69320. transaction.oncomplete = function (event) {
  69321. generateBlobUrl();
  69322. };
  69323. var newTexture = { textureUrl: url, data: blob };
  69324. try {
  69325. // Put the blob into the dabase
  69326. var addRequest = transaction.objectStore("textures").put(newTexture);
  69327. addRequest.onsuccess = function (event) {
  69328. };
  69329. addRequest.onerror = function (event) {
  69330. generateBlobUrl();
  69331. };
  69332. }
  69333. catch (ex) {
  69334. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69335. if (ex.code === 25) {
  69336. Database.IsUASupportingBlobStorage = false;
  69337. }
  69338. image.src = url;
  69339. }
  69340. }
  69341. else {
  69342. image.src = url;
  69343. }
  69344. }, false);
  69345. xhr.addEventListener("error", function (event) {
  69346. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69347. image.src = url;
  69348. }, false);
  69349. xhr.send();
  69350. }
  69351. else {
  69352. image.src = url;
  69353. }
  69354. }
  69355. else {
  69356. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69357. image.src = url;
  69358. }
  69359. };
  69360. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69361. var _this = this;
  69362. var updateVersion = function () {
  69363. // the version is not yet in the DB or we need to update it
  69364. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69365. };
  69366. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69367. };
  69368. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69369. var _this = this;
  69370. if (this.isSupported && this.db) {
  69371. var version;
  69372. try {
  69373. var transaction = this.db.transaction(["versions"]);
  69374. transaction.oncomplete = function (event) {
  69375. if (version) {
  69376. // If the version in the JSON file is different from the version in DB
  69377. if (_this.manifestVersionFound !== version.data) {
  69378. _this.mustUpdateRessources = true;
  69379. updateInDBCallback();
  69380. }
  69381. else {
  69382. callback(version.data);
  69383. }
  69384. }
  69385. // version was not found in DB
  69386. else {
  69387. _this.mustUpdateRessources = true;
  69388. updateInDBCallback();
  69389. }
  69390. };
  69391. transaction.onabort = function (event) {
  69392. callback(-1);
  69393. };
  69394. var getRequest = transaction.objectStore("versions").get(url);
  69395. getRequest.onsuccess = function (event) {
  69396. version = (event.target).result;
  69397. };
  69398. getRequest.onerror = function (event) {
  69399. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69400. callback(-1);
  69401. };
  69402. }
  69403. catch (ex) {
  69404. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69405. callback(-1);
  69406. }
  69407. }
  69408. else {
  69409. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69410. callback(-1);
  69411. }
  69412. };
  69413. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69414. var _this = this;
  69415. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69416. try {
  69417. // Open a transaction to the database
  69418. var transaction = this.db.transaction(["versions"], "readwrite");
  69419. // the transaction could abort because of a QuotaExceededError error
  69420. transaction.onabort = function (event) {
  69421. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69422. var error = event.srcElement['error'];
  69423. if (error && error.name === "QuotaExceededError") {
  69424. _this.hasReachedQuota = true;
  69425. }
  69426. }
  69427. catch (ex) { }
  69428. callback(-1);
  69429. };
  69430. transaction.oncomplete = function (event) {
  69431. callback(_this.manifestVersionFound);
  69432. };
  69433. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69434. // Put the scene into the database
  69435. var addRequest = transaction.objectStore("versions").put(newVersion);
  69436. addRequest.onsuccess = function (event) {
  69437. };
  69438. addRequest.onerror = function (event) {
  69439. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69440. };
  69441. }
  69442. catch (ex) {
  69443. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69444. callback(-1);
  69445. }
  69446. }
  69447. else {
  69448. callback(-1);
  69449. }
  69450. };
  69451. /**
  69452. * Loads a file from database
  69453. * @param url defines the URL to load from
  69454. * @param sceneLoaded defines a callback to call on success
  69455. * @param progressCallBack defines a callback to call when progress changed
  69456. * @param errorCallback defines a callback to call on error
  69457. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69458. */
  69459. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69460. var _this = this;
  69461. var completeUrl = Database._ReturnFullUrlLocation(url);
  69462. var saveAndLoadFile = function () {
  69463. // the scene is not yet in the DB, let's try to save it
  69464. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69465. };
  69466. this._checkVersionFromDB(completeUrl, function (version) {
  69467. if (version !== -1) {
  69468. if (!_this.mustUpdateRessources) {
  69469. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69470. }
  69471. else {
  69472. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69473. }
  69474. }
  69475. else {
  69476. if (errorCallback) {
  69477. errorCallback();
  69478. }
  69479. }
  69480. });
  69481. };
  69482. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69483. if (this.isSupported && this.db) {
  69484. var targetStore;
  69485. if (url.indexOf(".babylon") !== -1) {
  69486. targetStore = "scenes";
  69487. }
  69488. else {
  69489. targetStore = "textures";
  69490. }
  69491. var file;
  69492. var transaction = this.db.transaction([targetStore]);
  69493. transaction.oncomplete = function (event) {
  69494. if (file) {
  69495. callback(file.data);
  69496. }
  69497. // file was not found in DB
  69498. else {
  69499. notInDBCallback();
  69500. }
  69501. };
  69502. transaction.onabort = function (event) {
  69503. notInDBCallback();
  69504. };
  69505. var getRequest = transaction.objectStore(targetStore).get(url);
  69506. getRequest.onsuccess = function (event) {
  69507. file = (event.target).result;
  69508. };
  69509. getRequest.onerror = function (event) {
  69510. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69511. notInDBCallback();
  69512. };
  69513. }
  69514. else {
  69515. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69516. callback();
  69517. }
  69518. };
  69519. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69520. var _this = this;
  69521. if (this.isSupported) {
  69522. var targetStore;
  69523. if (url.indexOf(".babylon") !== -1) {
  69524. targetStore = "scenes";
  69525. }
  69526. else {
  69527. targetStore = "textures";
  69528. }
  69529. // Create XHR
  69530. var xhr = new XMLHttpRequest();
  69531. var fileData;
  69532. xhr.open("GET", url, true);
  69533. if (useArrayBuffer) {
  69534. xhr.responseType = "arraybuffer";
  69535. }
  69536. if (progressCallback) {
  69537. xhr.onprogress = progressCallback;
  69538. }
  69539. xhr.addEventListener("load", function () {
  69540. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69541. // Blob as response (XHR2)
  69542. //fileData = xhr.responseText;
  69543. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69544. if (!_this.hasReachedQuota && _this.db) {
  69545. // Open a transaction to the database
  69546. var transaction = _this.db.transaction([targetStore], "readwrite");
  69547. // the transaction could abort because of a QuotaExceededError error
  69548. transaction.onabort = function (event) {
  69549. try {
  69550. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69551. var error = event.srcElement['error'];
  69552. if (error && error.name === "QuotaExceededError") {
  69553. _this.hasReachedQuota = true;
  69554. }
  69555. }
  69556. catch (ex) { }
  69557. callback(fileData);
  69558. };
  69559. transaction.oncomplete = function (event) {
  69560. callback(fileData);
  69561. };
  69562. var newFile;
  69563. if (targetStore === "scenes") {
  69564. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69565. }
  69566. else {
  69567. newFile = { textureUrl: url, data: fileData };
  69568. }
  69569. try {
  69570. // Put the scene into the database
  69571. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69572. addRequest.onsuccess = function (event) {
  69573. };
  69574. addRequest.onerror = function (event) {
  69575. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69576. };
  69577. }
  69578. catch (ex) {
  69579. callback(fileData);
  69580. }
  69581. }
  69582. else {
  69583. callback(fileData);
  69584. }
  69585. }
  69586. else {
  69587. callback();
  69588. }
  69589. }, false);
  69590. xhr.addEventListener("error", function (event) {
  69591. BABYLON.Tools.Error("error on XHR request.");
  69592. callback();
  69593. }, false);
  69594. xhr.send();
  69595. }
  69596. else {
  69597. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69598. callback();
  69599. }
  69600. };
  69601. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69602. Database.IsUASupportingBlobStorage = true;
  69603. /** Gets a boolean indicating if Database storate is enabled */
  69604. Database.IDBStorageEnabled = true;
  69605. Database._ParseURL = function (url) {
  69606. var a = document.createElement('a');
  69607. a.href = url;
  69608. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69609. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69610. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69611. return absLocation;
  69612. };
  69613. Database._ReturnFullUrlLocation = function (url) {
  69614. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69615. return (Database._ParseURL(window.location.href) + url);
  69616. }
  69617. else {
  69618. return url;
  69619. }
  69620. };
  69621. return Database;
  69622. }());
  69623. BABYLON.Database = Database;
  69624. })(BABYLON || (BABYLON = {}));
  69625. //# sourceMappingURL=babylon.database.js.map
  69626. var BABYLON;
  69627. (function (BABYLON) {
  69628. var FresnelParameters = /** @class */ (function () {
  69629. function FresnelParameters() {
  69630. this._isEnabled = true;
  69631. this.leftColor = BABYLON.Color3.White();
  69632. this.rightColor = BABYLON.Color3.Black();
  69633. this.bias = 0;
  69634. this.power = 1;
  69635. }
  69636. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69637. get: function () {
  69638. return this._isEnabled;
  69639. },
  69640. set: function (value) {
  69641. if (this._isEnabled === value) {
  69642. return;
  69643. }
  69644. this._isEnabled = value;
  69645. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69646. },
  69647. enumerable: true,
  69648. configurable: true
  69649. });
  69650. FresnelParameters.prototype.clone = function () {
  69651. var newFresnelParameters = new FresnelParameters();
  69652. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69653. return newFresnelParameters;
  69654. };
  69655. FresnelParameters.prototype.serialize = function () {
  69656. var serializationObject = {};
  69657. serializationObject.isEnabled = this.isEnabled;
  69658. serializationObject.leftColor = this.leftColor.asArray();
  69659. serializationObject.rightColor = this.rightColor.asArray();
  69660. serializationObject.bias = this.bias;
  69661. serializationObject.power = this.power;
  69662. return serializationObject;
  69663. };
  69664. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69665. var fresnelParameters = new FresnelParameters();
  69666. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69667. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69668. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69669. fresnelParameters.bias = parsedFresnelParameters.bias;
  69670. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69671. return fresnelParameters;
  69672. };
  69673. return FresnelParameters;
  69674. }());
  69675. BABYLON.FresnelParameters = FresnelParameters;
  69676. })(BABYLON || (BABYLON = {}));
  69677. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69678. var BABYLON;
  69679. (function (BABYLON) {
  69680. var MultiMaterial = /** @class */ (function (_super) {
  69681. __extends(MultiMaterial, _super);
  69682. function MultiMaterial(name, scene) {
  69683. var _this = _super.call(this, name, scene, true) || this;
  69684. scene.multiMaterials.push(_this);
  69685. _this.subMaterials = new Array();
  69686. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69687. return _this;
  69688. }
  69689. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69690. get: function () {
  69691. return this._subMaterials;
  69692. },
  69693. set: function (value) {
  69694. this._subMaterials = value;
  69695. this._hookArray(value);
  69696. },
  69697. enumerable: true,
  69698. configurable: true
  69699. });
  69700. MultiMaterial.prototype._hookArray = function (array) {
  69701. var _this = this;
  69702. var oldPush = array.push;
  69703. array.push = function () {
  69704. var items = [];
  69705. for (var _i = 0; _i < arguments.length; _i++) {
  69706. items[_i] = arguments[_i];
  69707. }
  69708. var result = oldPush.apply(array, items);
  69709. _this._markAllSubMeshesAsTexturesDirty();
  69710. return result;
  69711. };
  69712. var oldSplice = array.splice;
  69713. array.splice = function (index, deleteCount) {
  69714. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69715. _this._markAllSubMeshesAsTexturesDirty();
  69716. return deleted;
  69717. };
  69718. };
  69719. // Properties
  69720. MultiMaterial.prototype.getSubMaterial = function (index) {
  69721. if (index < 0 || index >= this.subMaterials.length) {
  69722. return this.getScene().defaultMaterial;
  69723. }
  69724. return this.subMaterials[index];
  69725. };
  69726. MultiMaterial.prototype.getActiveTextures = function () {
  69727. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69728. if (subMaterial) {
  69729. return subMaterial.getActiveTextures();
  69730. }
  69731. else {
  69732. return [];
  69733. }
  69734. }));
  69735. var _a;
  69736. };
  69737. // Methods
  69738. MultiMaterial.prototype.getClassName = function () {
  69739. return "MultiMaterial";
  69740. };
  69741. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69742. for (var index = 0; index < this.subMaterials.length; index++) {
  69743. var subMaterial = this.subMaterials[index];
  69744. if (subMaterial) {
  69745. if (subMaterial.storeEffectOnSubMeshes) {
  69746. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69747. return false;
  69748. }
  69749. continue;
  69750. }
  69751. if (!subMaterial.isReady(mesh)) {
  69752. return false;
  69753. }
  69754. }
  69755. }
  69756. return true;
  69757. };
  69758. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69759. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69760. for (var index = 0; index < this.subMaterials.length; index++) {
  69761. var subMaterial = null;
  69762. var current = this.subMaterials[index];
  69763. if (cloneChildren && current) {
  69764. subMaterial = current.clone(name + "-" + current.name);
  69765. }
  69766. else {
  69767. subMaterial = this.subMaterials[index];
  69768. }
  69769. newMultiMaterial.subMaterials.push(subMaterial);
  69770. }
  69771. return newMultiMaterial;
  69772. };
  69773. MultiMaterial.prototype.serialize = function () {
  69774. var serializationObject = {};
  69775. serializationObject.name = this.name;
  69776. serializationObject.id = this.id;
  69777. if (BABYLON.Tags) {
  69778. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69779. }
  69780. serializationObject.materials = [];
  69781. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69782. var subMat = this.subMaterials[matIndex];
  69783. if (subMat) {
  69784. serializationObject.materials.push(subMat.id);
  69785. }
  69786. else {
  69787. serializationObject.materials.push(null);
  69788. }
  69789. }
  69790. return serializationObject;
  69791. };
  69792. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69793. var scene = this.getScene();
  69794. if (!scene) {
  69795. return;
  69796. }
  69797. var index = scene.multiMaterials.indexOf(this);
  69798. if (index >= 0) {
  69799. scene.multiMaterials.splice(index, 1);
  69800. }
  69801. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69802. };
  69803. return MultiMaterial;
  69804. }(BABYLON.Material));
  69805. BABYLON.MultiMaterial = MultiMaterial;
  69806. })(BABYLON || (BABYLON = {}));
  69807. //# sourceMappingURL=babylon.multiMaterial.js.map
  69808. var BABYLON;
  69809. (function (BABYLON) {
  69810. var FreeCameraTouchInput = /** @class */ (function () {
  69811. function FreeCameraTouchInput() {
  69812. this._offsetX = null;
  69813. this._offsetY = null;
  69814. this._pointerPressed = new Array();
  69815. this.touchAngularSensibility = 200000.0;
  69816. this.touchMoveSensibility = 250.0;
  69817. }
  69818. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69819. var _this = this;
  69820. var previousPosition = null;
  69821. if (this._pointerInput === undefined) {
  69822. this._onLostFocus = function (evt) {
  69823. _this._offsetX = null;
  69824. _this._offsetY = null;
  69825. };
  69826. this._pointerInput = function (p, s) {
  69827. var evt = p.event;
  69828. if (evt.pointerType === "mouse") {
  69829. return;
  69830. }
  69831. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69832. if (!noPreventDefault) {
  69833. evt.preventDefault();
  69834. }
  69835. _this._pointerPressed.push(evt.pointerId);
  69836. if (_this._pointerPressed.length !== 1) {
  69837. return;
  69838. }
  69839. previousPosition = {
  69840. x: evt.clientX,
  69841. y: evt.clientY
  69842. };
  69843. }
  69844. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69845. if (!noPreventDefault) {
  69846. evt.preventDefault();
  69847. }
  69848. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69849. if (index === -1) {
  69850. return;
  69851. }
  69852. _this._pointerPressed.splice(index, 1);
  69853. if (index != 0) {
  69854. return;
  69855. }
  69856. previousPosition = null;
  69857. _this._offsetX = null;
  69858. _this._offsetY = null;
  69859. }
  69860. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69861. if (!noPreventDefault) {
  69862. evt.preventDefault();
  69863. }
  69864. if (!previousPosition) {
  69865. return;
  69866. }
  69867. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69868. if (index != 0) {
  69869. return;
  69870. }
  69871. _this._offsetX = evt.clientX - previousPosition.x;
  69872. _this._offsetY = -(evt.clientY - previousPosition.y);
  69873. }
  69874. };
  69875. }
  69876. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69877. if (this._onLostFocus) {
  69878. element.addEventListener("blur", this._onLostFocus);
  69879. }
  69880. };
  69881. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69882. if (this._pointerInput && element) {
  69883. if (this._observer) {
  69884. this.camera.getScene().onPointerObservable.remove(this._observer);
  69885. this._observer = null;
  69886. }
  69887. if (this._onLostFocus) {
  69888. element.removeEventListener("blur", this._onLostFocus);
  69889. this._onLostFocus = null;
  69890. }
  69891. this._pointerPressed = [];
  69892. this._offsetX = null;
  69893. this._offsetY = null;
  69894. }
  69895. };
  69896. FreeCameraTouchInput.prototype.checkInputs = function () {
  69897. if (this._offsetX && this._offsetY) {
  69898. var camera = this.camera;
  69899. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69900. if (this._pointerPressed.length > 1) {
  69901. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69902. }
  69903. else {
  69904. var speed = camera._computeLocalCameraSpeed();
  69905. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69906. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69907. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69908. }
  69909. }
  69910. };
  69911. FreeCameraTouchInput.prototype.getClassName = function () {
  69912. return "FreeCameraTouchInput";
  69913. };
  69914. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69915. return "touch";
  69916. };
  69917. __decorate([
  69918. BABYLON.serialize()
  69919. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69920. __decorate([
  69921. BABYLON.serialize()
  69922. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69923. return FreeCameraTouchInput;
  69924. }());
  69925. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69926. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69927. })(BABYLON || (BABYLON = {}));
  69928. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69929. var BABYLON;
  69930. (function (BABYLON) {
  69931. // We're mainly based on the logic defined into the FreeCamera code
  69932. var TouchCamera = /** @class */ (function (_super) {
  69933. __extends(TouchCamera, _super);
  69934. //-- end properties for backward compatibility for inputs
  69935. function TouchCamera(name, position, scene) {
  69936. var _this = _super.call(this, name, position, scene) || this;
  69937. _this.inputs.addTouch();
  69938. _this._setupInputs();
  69939. return _this;
  69940. }
  69941. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69942. //-- Begin properties for backward compatibility for inputs
  69943. get: function () {
  69944. var touch = this.inputs.attached["touch"];
  69945. if (touch)
  69946. return touch.touchAngularSensibility;
  69947. return 0;
  69948. },
  69949. set: function (value) {
  69950. var touch = this.inputs.attached["touch"];
  69951. if (touch)
  69952. touch.touchAngularSensibility = value;
  69953. },
  69954. enumerable: true,
  69955. configurable: true
  69956. });
  69957. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69958. get: function () {
  69959. var touch = this.inputs.attached["touch"];
  69960. if (touch)
  69961. return touch.touchMoveSensibility;
  69962. return 0;
  69963. },
  69964. set: function (value) {
  69965. var touch = this.inputs.attached["touch"];
  69966. if (touch)
  69967. touch.touchMoveSensibility = value;
  69968. },
  69969. enumerable: true,
  69970. configurable: true
  69971. });
  69972. TouchCamera.prototype.getClassName = function () {
  69973. return "TouchCamera";
  69974. };
  69975. TouchCamera.prototype._setupInputs = function () {
  69976. var mouse = this.inputs.attached["mouse"];
  69977. if (mouse) {
  69978. mouse.touchEnabled = false;
  69979. }
  69980. };
  69981. return TouchCamera;
  69982. }(BABYLON.FreeCamera));
  69983. BABYLON.TouchCamera = TouchCamera;
  69984. })(BABYLON || (BABYLON = {}));
  69985. //# sourceMappingURL=babylon.touchCamera.js.map
  69986. var BABYLON;
  69987. (function (BABYLON) {
  69988. var ProceduralTexture = /** @class */ (function (_super) {
  69989. __extends(ProceduralTexture, _super);
  69990. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69991. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69992. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69993. if (isCube === void 0) { isCube = false; }
  69994. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69995. _this.isCube = isCube;
  69996. _this.isEnabled = true;
  69997. _this._currentRefreshId = -1;
  69998. _this._refreshRate = 1;
  69999. _this._vertexBuffers = {};
  70000. _this._uniforms = new Array();
  70001. _this._samplers = new Array();
  70002. _this._textures = {};
  70003. _this._floats = {};
  70004. _this._floatsArrays = {};
  70005. _this._colors3 = {};
  70006. _this._colors4 = {};
  70007. _this._vectors2 = {};
  70008. _this._vectors3 = {};
  70009. _this._matrices = {};
  70010. _this._fallbackTextureUsed = false;
  70011. scene.proceduralTextures.push(_this);
  70012. _this._engine = scene.getEngine();
  70013. _this.name = name;
  70014. _this.isRenderTarget = true;
  70015. _this._size = size;
  70016. _this._generateMipMaps = generateMipMaps;
  70017. _this.setFragment(fragment);
  70018. _this._fallbackTexture = fallbackTexture;
  70019. if (isCube) {
  70020. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70021. _this.setFloat("face", 0);
  70022. }
  70023. else {
  70024. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70025. }
  70026. // VBO
  70027. var vertices = [];
  70028. vertices.push(1, 1);
  70029. vertices.push(-1, 1);
  70030. vertices.push(-1, -1);
  70031. vertices.push(1, -1);
  70032. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70033. _this._createIndexBuffer();
  70034. return _this;
  70035. }
  70036. ProceduralTexture.prototype._createIndexBuffer = function () {
  70037. var engine = this._engine;
  70038. // Indices
  70039. var indices = [];
  70040. indices.push(0);
  70041. indices.push(1);
  70042. indices.push(2);
  70043. indices.push(0);
  70044. indices.push(2);
  70045. indices.push(3);
  70046. this._indexBuffer = engine.createIndexBuffer(indices);
  70047. };
  70048. ProceduralTexture.prototype._rebuild = function () {
  70049. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70050. if (vb) {
  70051. vb._rebuild();
  70052. }
  70053. this._createIndexBuffer();
  70054. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70055. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70056. }
  70057. };
  70058. ProceduralTexture.prototype.reset = function () {
  70059. if (this._effect === undefined) {
  70060. return;
  70061. }
  70062. var engine = this._engine;
  70063. engine._releaseEffect(this._effect);
  70064. };
  70065. ProceduralTexture.prototype.isReady = function () {
  70066. var _this = this;
  70067. var engine = this._engine;
  70068. var shaders;
  70069. if (!this._fragment) {
  70070. return false;
  70071. }
  70072. if (this._fallbackTextureUsed) {
  70073. return true;
  70074. }
  70075. if (this._fragment.fragmentElement !== undefined) {
  70076. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70077. }
  70078. else {
  70079. shaders = { vertex: "procedural", fragment: this._fragment };
  70080. }
  70081. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70082. _this.releaseInternalTexture();
  70083. if (_this._fallbackTexture) {
  70084. _this._texture = _this._fallbackTexture._texture;
  70085. if (_this._texture) {
  70086. _this._texture.incrementReferences();
  70087. }
  70088. }
  70089. _this._fallbackTextureUsed = true;
  70090. });
  70091. return this._effect.isReady();
  70092. };
  70093. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70094. this._currentRefreshId = -1;
  70095. };
  70096. ProceduralTexture.prototype.setFragment = function (fragment) {
  70097. this._fragment = fragment;
  70098. };
  70099. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70100. get: function () {
  70101. return this._refreshRate;
  70102. },
  70103. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70104. set: function (value) {
  70105. this._refreshRate = value;
  70106. this.resetRefreshCounter();
  70107. },
  70108. enumerable: true,
  70109. configurable: true
  70110. });
  70111. ProceduralTexture.prototype._shouldRender = function () {
  70112. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70113. return false;
  70114. }
  70115. if (this._fallbackTextureUsed) {
  70116. return false;
  70117. }
  70118. if (this._currentRefreshId === -1) { // At least render once
  70119. this._currentRefreshId = 1;
  70120. return true;
  70121. }
  70122. if (this.refreshRate === this._currentRefreshId) {
  70123. this._currentRefreshId = 1;
  70124. return true;
  70125. }
  70126. this._currentRefreshId++;
  70127. return false;
  70128. };
  70129. ProceduralTexture.prototype.getRenderSize = function () {
  70130. return this._size;
  70131. };
  70132. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70133. if (this._fallbackTextureUsed) {
  70134. return;
  70135. }
  70136. this.releaseInternalTexture();
  70137. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70138. // Update properties
  70139. this._size = size;
  70140. this._generateMipMaps = generateMipMaps;
  70141. };
  70142. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70143. if (this._uniforms.indexOf(uniformName) === -1) {
  70144. this._uniforms.push(uniformName);
  70145. }
  70146. };
  70147. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70148. if (this._samplers.indexOf(name) === -1) {
  70149. this._samplers.push(name);
  70150. }
  70151. this._textures[name] = texture;
  70152. return this;
  70153. };
  70154. ProceduralTexture.prototype.setFloat = function (name, value) {
  70155. this._checkUniform(name);
  70156. this._floats[name] = value;
  70157. return this;
  70158. };
  70159. ProceduralTexture.prototype.setFloats = function (name, value) {
  70160. this._checkUniform(name);
  70161. this._floatsArrays[name] = value;
  70162. return this;
  70163. };
  70164. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70165. this._checkUniform(name);
  70166. this._colors3[name] = value;
  70167. return this;
  70168. };
  70169. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70170. this._checkUniform(name);
  70171. this._colors4[name] = value;
  70172. return this;
  70173. };
  70174. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70175. this._checkUniform(name);
  70176. this._vectors2[name] = value;
  70177. return this;
  70178. };
  70179. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70180. this._checkUniform(name);
  70181. this._vectors3[name] = value;
  70182. return this;
  70183. };
  70184. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70185. this._checkUniform(name);
  70186. this._matrices[name] = value;
  70187. return this;
  70188. };
  70189. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70190. var scene = this.getScene();
  70191. if (!scene) {
  70192. return;
  70193. }
  70194. var engine = this._engine;
  70195. // Render
  70196. engine.enableEffect(this._effect);
  70197. engine.setState(false);
  70198. // Texture
  70199. for (var name in this._textures) {
  70200. this._effect.setTexture(name, this._textures[name]);
  70201. }
  70202. // Float
  70203. for (name in this._floats) {
  70204. this._effect.setFloat(name, this._floats[name]);
  70205. }
  70206. // Floats
  70207. for (name in this._floatsArrays) {
  70208. this._effect.setArray(name, this._floatsArrays[name]);
  70209. }
  70210. // Color3
  70211. for (name in this._colors3) {
  70212. this._effect.setColor3(name, this._colors3[name]);
  70213. }
  70214. // Color4
  70215. for (name in this._colors4) {
  70216. var color = this._colors4[name];
  70217. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70218. }
  70219. // Vector2
  70220. for (name in this._vectors2) {
  70221. this._effect.setVector2(name, this._vectors2[name]);
  70222. }
  70223. // Vector3
  70224. for (name in this._vectors3) {
  70225. this._effect.setVector3(name, this._vectors3[name]);
  70226. }
  70227. // Matrix
  70228. for (name in this._matrices) {
  70229. this._effect.setMatrix(name, this._matrices[name]);
  70230. }
  70231. if (!this._texture) {
  70232. return;
  70233. }
  70234. if (this.isCube) {
  70235. for (var face = 0; face < 6; face++) {
  70236. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70237. // VBOs
  70238. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70239. this._effect.setFloat("face", face);
  70240. // Clear
  70241. engine.clear(scene.clearColor, true, true, true);
  70242. // Draw order
  70243. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70244. // Mipmaps
  70245. if (face === 5) {
  70246. engine.generateMipMapsForCubemap(this._texture);
  70247. }
  70248. }
  70249. }
  70250. else {
  70251. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70252. // VBOs
  70253. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70254. // Clear
  70255. engine.clear(scene.clearColor, true, true, true);
  70256. // Draw order
  70257. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70258. }
  70259. // Unbind
  70260. engine.unBindFramebuffer(this._texture, this.isCube);
  70261. if (this.onGenerated) {
  70262. this.onGenerated();
  70263. }
  70264. };
  70265. ProceduralTexture.prototype.clone = function () {
  70266. var textureSize = this.getSize();
  70267. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70268. // Base texture
  70269. newTexture.hasAlpha = this.hasAlpha;
  70270. newTexture.level = this.level;
  70271. // RenderTarget Texture
  70272. newTexture.coordinatesMode = this.coordinatesMode;
  70273. return newTexture;
  70274. };
  70275. ProceduralTexture.prototype.dispose = function () {
  70276. var scene = this.getScene();
  70277. if (!scene) {
  70278. return;
  70279. }
  70280. var index = scene.proceduralTextures.indexOf(this);
  70281. if (index >= 0) {
  70282. scene.proceduralTextures.splice(index, 1);
  70283. }
  70284. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70285. if (vertexBuffer) {
  70286. vertexBuffer.dispose();
  70287. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70288. }
  70289. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70290. this._indexBuffer = null;
  70291. }
  70292. _super.prototype.dispose.call(this);
  70293. };
  70294. __decorate([
  70295. BABYLON.serialize()
  70296. ], ProceduralTexture.prototype, "_size", void 0);
  70297. __decorate([
  70298. BABYLON.serialize()
  70299. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70300. __decorate([
  70301. BABYLON.serialize()
  70302. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70303. __decorate([
  70304. BABYLON.serialize()
  70305. ], ProceduralTexture.prototype, "refreshRate", null);
  70306. return ProceduralTexture;
  70307. }(BABYLON.Texture));
  70308. BABYLON.ProceduralTexture = ProceduralTexture;
  70309. })(BABYLON || (BABYLON = {}));
  70310. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70311. var BABYLON;
  70312. (function (BABYLON) {
  70313. var CustomProceduralTexture = /** @class */ (function (_super) {
  70314. __extends(CustomProceduralTexture, _super);
  70315. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70316. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70317. _this._animate = true;
  70318. _this._time = 0;
  70319. _this._texturePath = texturePath;
  70320. //Try to load json
  70321. _this.loadJson(texturePath);
  70322. _this.refreshRate = 1;
  70323. return _this;
  70324. }
  70325. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70326. var _this = this;
  70327. var noConfigFile = function () {
  70328. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70329. try {
  70330. _this.setFragment(_this._texturePath);
  70331. }
  70332. catch (ex) {
  70333. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70334. }
  70335. };
  70336. var configFileUrl = jsonUrl + "/config.json";
  70337. var xhr = new XMLHttpRequest();
  70338. xhr.open("GET", configFileUrl, true);
  70339. xhr.addEventListener("load", function () {
  70340. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70341. try {
  70342. _this._config = JSON.parse(xhr.response);
  70343. _this.updateShaderUniforms();
  70344. _this.updateTextures();
  70345. _this.setFragment(_this._texturePath + "/custom");
  70346. _this._animate = _this._config.animate;
  70347. _this.refreshRate = _this._config.refreshrate;
  70348. }
  70349. catch (ex) {
  70350. noConfigFile();
  70351. }
  70352. }
  70353. else {
  70354. noConfigFile();
  70355. }
  70356. }, false);
  70357. xhr.addEventListener("error", function () {
  70358. noConfigFile();
  70359. }, false);
  70360. try {
  70361. xhr.send();
  70362. }
  70363. catch (ex) {
  70364. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70365. }
  70366. };
  70367. CustomProceduralTexture.prototype.isReady = function () {
  70368. if (!_super.prototype.isReady.call(this)) {
  70369. return false;
  70370. }
  70371. for (var name in this._textures) {
  70372. var texture = this._textures[name];
  70373. if (!texture.isReady()) {
  70374. return false;
  70375. }
  70376. }
  70377. return true;
  70378. };
  70379. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70380. var scene = this.getScene();
  70381. if (this._animate && scene) {
  70382. this._time += scene.getAnimationRatio() * 0.03;
  70383. this.updateShaderUniforms();
  70384. }
  70385. _super.prototype.render.call(this, useCameraPostProcess);
  70386. };
  70387. CustomProceduralTexture.prototype.updateTextures = function () {
  70388. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70389. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70390. }
  70391. };
  70392. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70393. if (this._config) {
  70394. for (var j = 0; j < this._config.uniforms.length; j++) {
  70395. var uniform = this._config.uniforms[j];
  70396. switch (uniform.type) {
  70397. case "float":
  70398. this.setFloat(uniform.name, uniform.value);
  70399. break;
  70400. case "color3":
  70401. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70402. break;
  70403. case "color4":
  70404. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70405. break;
  70406. case "vector2":
  70407. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70408. break;
  70409. case "vector3":
  70410. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70411. break;
  70412. }
  70413. }
  70414. }
  70415. this.setFloat("time", this._time);
  70416. };
  70417. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70418. get: function () {
  70419. return this._animate;
  70420. },
  70421. set: function (value) {
  70422. this._animate = value;
  70423. },
  70424. enumerable: true,
  70425. configurable: true
  70426. });
  70427. return CustomProceduralTexture;
  70428. }(BABYLON.ProceduralTexture));
  70429. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70430. })(BABYLON || (BABYLON = {}));
  70431. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70432. var BABYLON;
  70433. (function (BABYLON) {
  70434. var FreeCameraGamepadInput = /** @class */ (function () {
  70435. function FreeCameraGamepadInput() {
  70436. this.gamepadAngularSensibility = 200;
  70437. this.gamepadMoveSensibility = 40;
  70438. // private members
  70439. this._cameraTransform = BABYLON.Matrix.Identity();
  70440. this._deltaTransform = BABYLON.Vector3.Zero();
  70441. this._vector3 = BABYLON.Vector3.Zero();
  70442. this._vector2 = BABYLON.Vector2.Zero();
  70443. }
  70444. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70445. var _this = this;
  70446. var manager = this.camera.getScene().gamepadManager;
  70447. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70448. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70449. // prioritize XBOX gamepads.
  70450. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70451. _this.gamepad = gamepad;
  70452. }
  70453. }
  70454. });
  70455. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70456. if (_this.gamepad === gamepad) {
  70457. _this.gamepad = null;
  70458. }
  70459. });
  70460. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70461. };
  70462. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70463. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70464. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70465. this.gamepad = null;
  70466. };
  70467. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70468. if (this.gamepad && this.gamepad.leftStick) {
  70469. var camera = this.camera;
  70470. var LSValues = this.gamepad.leftStick;
  70471. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70472. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70473. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70474. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70475. var RSValues = this.gamepad.rightStick;
  70476. if (RSValues) {
  70477. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70478. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70479. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70480. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70481. }
  70482. else {
  70483. RSValues = { x: 0, y: 0 };
  70484. }
  70485. if (!camera.rotationQuaternion) {
  70486. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70487. }
  70488. else {
  70489. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70490. }
  70491. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70492. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70493. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70494. camera.cameraDirection.addInPlace(this._deltaTransform);
  70495. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70496. camera.cameraRotation.addInPlace(this._vector2);
  70497. }
  70498. };
  70499. FreeCameraGamepadInput.prototype.getClassName = function () {
  70500. return "FreeCameraGamepadInput";
  70501. };
  70502. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70503. return "gamepad";
  70504. };
  70505. __decorate([
  70506. BABYLON.serialize()
  70507. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70508. __decorate([
  70509. BABYLON.serialize()
  70510. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70511. return FreeCameraGamepadInput;
  70512. }());
  70513. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70514. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70515. })(BABYLON || (BABYLON = {}));
  70516. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70517. var BABYLON;
  70518. (function (BABYLON) {
  70519. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70520. function ArcRotateCameraGamepadInput() {
  70521. this.gamepadRotationSensibility = 80;
  70522. this.gamepadMoveSensibility = 40;
  70523. }
  70524. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70525. var _this = this;
  70526. var manager = this.camera.getScene().gamepadManager;
  70527. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70528. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70529. // prioritize XBOX gamepads.
  70530. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70531. _this.gamepad = gamepad;
  70532. }
  70533. }
  70534. });
  70535. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70536. if (_this.gamepad === gamepad) {
  70537. _this.gamepad = null;
  70538. }
  70539. });
  70540. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70541. };
  70542. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70543. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70544. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70545. this.gamepad = null;
  70546. };
  70547. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70548. if (this.gamepad) {
  70549. var camera = this.camera;
  70550. var RSValues = this.gamepad.rightStick;
  70551. if (RSValues) {
  70552. if (RSValues.x != 0) {
  70553. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70554. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70555. camera.inertialAlphaOffset += normalizedRX;
  70556. }
  70557. }
  70558. if (RSValues.y != 0) {
  70559. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70560. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70561. camera.inertialBetaOffset += normalizedRY;
  70562. }
  70563. }
  70564. }
  70565. var LSValues = this.gamepad.leftStick;
  70566. if (LSValues && LSValues.y != 0) {
  70567. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70568. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70569. this.camera.inertialRadiusOffset -= normalizedLY;
  70570. }
  70571. }
  70572. }
  70573. };
  70574. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70575. return "ArcRotateCameraGamepadInput";
  70576. };
  70577. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70578. return "gamepad";
  70579. };
  70580. __decorate([
  70581. BABYLON.serialize()
  70582. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70583. __decorate([
  70584. BABYLON.serialize()
  70585. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70586. return ArcRotateCameraGamepadInput;
  70587. }());
  70588. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70589. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70590. })(BABYLON || (BABYLON = {}));
  70591. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70592. var BABYLON;
  70593. (function (BABYLON) {
  70594. var GamepadManager = /** @class */ (function () {
  70595. function GamepadManager(_scene) {
  70596. var _this = this;
  70597. this._scene = _scene;
  70598. this._babylonGamepads = [];
  70599. this._oneGamepadConnected = false;
  70600. this._isMonitoring = false;
  70601. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70602. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70603. this._gamepadEventSupported = false;
  70604. }
  70605. else {
  70606. this._gamepadEventSupported = 'GamepadEvent' in window;
  70607. this._gamepadSupport = (navigator.getGamepads ||
  70608. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70609. }
  70610. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70611. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70612. for (var i in _this._babylonGamepads) {
  70613. var gamepad = _this._babylonGamepads[i];
  70614. if (gamepad && gamepad._isConnected) {
  70615. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70616. }
  70617. }
  70618. });
  70619. this._onGamepadConnectedEvent = function (evt) {
  70620. var gamepad = evt.gamepad;
  70621. if (gamepad.index in _this._babylonGamepads) {
  70622. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70623. return;
  70624. }
  70625. }
  70626. var newGamepad;
  70627. if (_this._babylonGamepads[gamepad.index]) {
  70628. newGamepad = _this._babylonGamepads[gamepad.index];
  70629. newGamepad.browserGamepad = gamepad;
  70630. newGamepad._isConnected = true;
  70631. }
  70632. else {
  70633. newGamepad = _this._addNewGamepad(gamepad);
  70634. }
  70635. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70636. _this._startMonitoringGamepads();
  70637. };
  70638. this._onGamepadDisconnectedEvent = function (evt) {
  70639. var gamepad = evt.gamepad;
  70640. // Remove the gamepad from the list of gamepads to monitor.
  70641. for (var i in _this._babylonGamepads) {
  70642. if (_this._babylonGamepads[i].index === gamepad.index) {
  70643. var disconnectedGamepad = _this._babylonGamepads[i];
  70644. disconnectedGamepad._isConnected = false;
  70645. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70646. break;
  70647. }
  70648. }
  70649. };
  70650. if (this._gamepadSupport) {
  70651. //first add already-connected gamepads
  70652. this._updateGamepadObjects();
  70653. if (this._babylonGamepads.length) {
  70654. this._startMonitoringGamepads();
  70655. }
  70656. // Checking if the gamepad connected event is supported (like in Firefox)
  70657. if (this._gamepadEventSupported) {
  70658. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70659. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70660. }
  70661. else {
  70662. this._startMonitoringGamepads();
  70663. }
  70664. }
  70665. }
  70666. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70667. get: function () {
  70668. return this._babylonGamepads;
  70669. },
  70670. enumerable: true,
  70671. configurable: true
  70672. });
  70673. GamepadManager.prototype.getGamepadByType = function (type) {
  70674. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70675. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70676. var gamepad = _a[_i];
  70677. if (gamepad && gamepad.type === type) {
  70678. return gamepad;
  70679. }
  70680. }
  70681. return null;
  70682. };
  70683. GamepadManager.prototype.dispose = function () {
  70684. if (this._gamepadEventSupported) {
  70685. if (this._onGamepadConnectedEvent) {
  70686. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70687. }
  70688. if (this._onGamepadDisconnectedEvent) {
  70689. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70690. }
  70691. this._onGamepadConnectedEvent = null;
  70692. this._onGamepadDisconnectedEvent = null;
  70693. }
  70694. this._babylonGamepads.forEach(function (gamepad) {
  70695. gamepad.dispose();
  70696. });
  70697. this.onGamepadConnectedObservable.clear();
  70698. this.onGamepadDisconnectedObservable.clear();
  70699. this._oneGamepadConnected = false;
  70700. this._stopMonitoringGamepads();
  70701. this._babylonGamepads = [];
  70702. };
  70703. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70704. if (!this._oneGamepadConnected) {
  70705. this._oneGamepadConnected = true;
  70706. }
  70707. var newGamepad;
  70708. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70709. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70710. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70711. }
  70712. // if pose is supported, use the (WebVR) pose enabled controller
  70713. else if (gamepad.pose) {
  70714. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70715. }
  70716. else {
  70717. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70718. }
  70719. this._babylonGamepads[newGamepad.index] = newGamepad;
  70720. return newGamepad;
  70721. };
  70722. GamepadManager.prototype._startMonitoringGamepads = function () {
  70723. if (!this._isMonitoring) {
  70724. this._isMonitoring = true;
  70725. //back-comp
  70726. if (!this._scene) {
  70727. this._checkGamepadsStatus();
  70728. }
  70729. }
  70730. };
  70731. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70732. this._isMonitoring = false;
  70733. };
  70734. GamepadManager.prototype._checkGamepadsStatus = function () {
  70735. var _this = this;
  70736. // Hack to be compatible Chrome
  70737. this._updateGamepadObjects();
  70738. for (var i in this._babylonGamepads) {
  70739. var gamepad = this._babylonGamepads[i];
  70740. if (!gamepad || !gamepad.isConnected) {
  70741. continue;
  70742. }
  70743. gamepad.update();
  70744. }
  70745. if (this._isMonitoring && !this._scene) {
  70746. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70747. }
  70748. };
  70749. // This function is called only on Chrome, which does not properly support
  70750. // connection/disconnection events and forces you to recopy again the gamepad object
  70751. GamepadManager.prototype._updateGamepadObjects = function () {
  70752. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70753. for (var i = 0; i < gamepads.length; i++) {
  70754. var gamepad = gamepads[i];
  70755. if (gamepad) {
  70756. if (!this._babylonGamepads[gamepad.index]) {
  70757. var newGamepad = this._addNewGamepad(gamepad);
  70758. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70759. }
  70760. else {
  70761. // Forced to copy again this object for Chrome for unknown reason
  70762. this._babylonGamepads[i].browserGamepad = gamepad;
  70763. if (!this._babylonGamepads[i].isConnected) {
  70764. this._babylonGamepads[i]._isConnected = true;
  70765. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70766. }
  70767. }
  70768. }
  70769. }
  70770. };
  70771. return GamepadManager;
  70772. }());
  70773. BABYLON.GamepadManager = GamepadManager;
  70774. })(BABYLON || (BABYLON = {}));
  70775. //# sourceMappingURL=babylon.gamepadManager.js.map
  70776. var BABYLON;
  70777. (function (BABYLON) {
  70778. var StickValues = /** @class */ (function () {
  70779. function StickValues(x, y) {
  70780. this.x = x;
  70781. this.y = y;
  70782. }
  70783. return StickValues;
  70784. }());
  70785. BABYLON.StickValues = StickValues;
  70786. var Gamepad = /** @class */ (function () {
  70787. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70788. if (leftStickX === void 0) { leftStickX = 0; }
  70789. if (leftStickY === void 0) { leftStickY = 1; }
  70790. if (rightStickX === void 0) { rightStickX = 2; }
  70791. if (rightStickY === void 0) { rightStickY = 3; }
  70792. this.id = id;
  70793. this.index = index;
  70794. this.browserGamepad = browserGamepad;
  70795. this._isConnected = true;
  70796. this._invertLeftStickY = false;
  70797. this.type = Gamepad.GAMEPAD;
  70798. this._leftStickAxisX = leftStickX;
  70799. this._leftStickAxisY = leftStickY;
  70800. this._rightStickAxisX = rightStickX;
  70801. this._rightStickAxisY = rightStickY;
  70802. if (this.browserGamepad.axes.length >= 2) {
  70803. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70804. }
  70805. if (this.browserGamepad.axes.length >= 4) {
  70806. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70807. }
  70808. }
  70809. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70810. get: function () {
  70811. return this._isConnected;
  70812. },
  70813. enumerable: true,
  70814. configurable: true
  70815. });
  70816. Gamepad.prototype.onleftstickchanged = function (callback) {
  70817. this._onleftstickchanged = callback;
  70818. };
  70819. Gamepad.prototype.onrightstickchanged = function (callback) {
  70820. this._onrightstickchanged = callback;
  70821. };
  70822. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70823. get: function () {
  70824. return this._leftStick;
  70825. },
  70826. set: function (newValues) {
  70827. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70828. this._onleftstickchanged(newValues);
  70829. }
  70830. this._leftStick = newValues;
  70831. },
  70832. enumerable: true,
  70833. configurable: true
  70834. });
  70835. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70836. get: function () {
  70837. return this._rightStick;
  70838. },
  70839. set: function (newValues) {
  70840. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70841. this._onrightstickchanged(newValues);
  70842. }
  70843. this._rightStick = newValues;
  70844. },
  70845. enumerable: true,
  70846. configurable: true
  70847. });
  70848. Gamepad.prototype.update = function () {
  70849. if (this._leftStick) {
  70850. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70851. if (this._invertLeftStickY) {
  70852. this.leftStick.y *= -1;
  70853. }
  70854. }
  70855. if (this._rightStick) {
  70856. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70857. }
  70858. };
  70859. Gamepad.prototype.dispose = function () {
  70860. };
  70861. Gamepad.GAMEPAD = 0;
  70862. Gamepad.GENERIC = 1;
  70863. Gamepad.XBOX = 2;
  70864. Gamepad.POSE_ENABLED = 3;
  70865. return Gamepad;
  70866. }());
  70867. BABYLON.Gamepad = Gamepad;
  70868. var GenericPad = /** @class */ (function (_super) {
  70869. __extends(GenericPad, _super);
  70870. function GenericPad(id, index, browserGamepad) {
  70871. var _this = _super.call(this, id, index, browserGamepad) || this;
  70872. _this.onButtonDownObservable = new BABYLON.Observable();
  70873. _this.onButtonUpObservable = new BABYLON.Observable();
  70874. _this.type = Gamepad.GENERIC;
  70875. _this._buttons = new Array(browserGamepad.buttons.length);
  70876. return _this;
  70877. }
  70878. GenericPad.prototype.onbuttondown = function (callback) {
  70879. this._onbuttondown = callback;
  70880. };
  70881. GenericPad.prototype.onbuttonup = function (callback) {
  70882. this._onbuttonup = callback;
  70883. };
  70884. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70885. if (newValue !== currentValue) {
  70886. if (newValue === 1) {
  70887. if (this._onbuttondown) {
  70888. this._onbuttondown(buttonIndex);
  70889. }
  70890. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70891. }
  70892. if (newValue === 0) {
  70893. if (this._onbuttonup) {
  70894. this._onbuttonup(buttonIndex);
  70895. }
  70896. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70897. }
  70898. }
  70899. return newValue;
  70900. };
  70901. GenericPad.prototype.update = function () {
  70902. _super.prototype.update.call(this);
  70903. for (var index = 0; index < this._buttons.length; index++) {
  70904. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70905. }
  70906. };
  70907. GenericPad.prototype.dispose = function () {
  70908. _super.prototype.dispose.call(this);
  70909. this.onButtonDownObservable.clear();
  70910. this.onButtonUpObservable.clear();
  70911. };
  70912. return GenericPad;
  70913. }(Gamepad));
  70914. BABYLON.GenericPad = GenericPad;
  70915. })(BABYLON || (BABYLON = {}));
  70916. //# sourceMappingURL=babylon.gamepad.js.map
  70917. var BABYLON;
  70918. (function (BABYLON) {
  70919. /**
  70920. * Defines supported buttons for XBox360 compatible gamepads
  70921. */
  70922. var Xbox360Button;
  70923. (function (Xbox360Button) {
  70924. /** A */
  70925. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70926. /** B */
  70927. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70928. /** X */
  70929. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70930. /** Y */
  70931. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70932. /** Start */
  70933. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70934. /** Back */
  70935. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70936. /** Left button */
  70937. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70938. /** Right button */
  70939. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70940. /** Left stick */
  70941. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70942. /** Right stick */
  70943. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70944. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70945. /** Defines values for XBox360 DPad */
  70946. var Xbox360Dpad;
  70947. (function (Xbox360Dpad) {
  70948. /** Up */
  70949. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70950. /** Down */
  70951. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70952. /** Left */
  70953. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70954. /** Right */
  70955. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70956. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70957. /**
  70958. * Defines a XBox360 gamepad
  70959. */
  70960. var Xbox360Pad = /** @class */ (function (_super) {
  70961. __extends(Xbox360Pad, _super);
  70962. /**
  70963. * Creates a new XBox360 gamepad object
  70964. * @param id defines the id of this gamepad
  70965. * @param index defines its index
  70966. * @param gamepad defines the internal HTML gamepad object
  70967. * @param xboxOne defines if it is a XBox One gamepad
  70968. */
  70969. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70970. if (xboxOne === void 0) { xboxOne = false; }
  70971. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70972. _this._leftTrigger = 0;
  70973. _this._rightTrigger = 0;
  70974. /** Observable raised when a button is pressed */
  70975. _this.onButtonDownObservable = new BABYLON.Observable();
  70976. /** Observable raised when a button is released */
  70977. _this.onButtonUpObservable = new BABYLON.Observable();
  70978. /** Observable raised when a pad is pressed */
  70979. _this.onPadDownObservable = new BABYLON.Observable();
  70980. /** Observable raised when a pad is released */
  70981. _this.onPadUpObservable = new BABYLON.Observable();
  70982. _this._buttonA = 0;
  70983. _this._buttonB = 0;
  70984. _this._buttonX = 0;
  70985. _this._buttonY = 0;
  70986. _this._buttonBack = 0;
  70987. _this._buttonStart = 0;
  70988. _this._buttonLB = 0;
  70989. _this._buttonRB = 0;
  70990. _this._buttonLeftStick = 0;
  70991. _this._buttonRightStick = 0;
  70992. _this._dPadUp = 0;
  70993. _this._dPadDown = 0;
  70994. _this._dPadLeft = 0;
  70995. _this._dPadRight = 0;
  70996. _this._isXboxOnePad = false;
  70997. _this.type = BABYLON.Gamepad.XBOX;
  70998. _this._isXboxOnePad = xboxOne;
  70999. return _this;
  71000. }
  71001. /**
  71002. * Defines the callback to call when left trigger is pressed
  71003. * @param callback defines the callback to use
  71004. */
  71005. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71006. this._onlefttriggerchanged = callback;
  71007. };
  71008. /**
  71009. * Defines the callback to call when right trigger is pressed
  71010. * @param callback defines the callback to use
  71011. */
  71012. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71013. this._onrighttriggerchanged = callback;
  71014. };
  71015. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71016. /**
  71017. * Gets or sets left trigger value
  71018. */
  71019. get: function () {
  71020. return this._leftTrigger;
  71021. },
  71022. set: function (newValue) {
  71023. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71024. this._onlefttriggerchanged(newValue);
  71025. }
  71026. this._leftTrigger = newValue;
  71027. },
  71028. enumerable: true,
  71029. configurable: true
  71030. });
  71031. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71032. /**
  71033. * Gets or sets right trigger value
  71034. */
  71035. get: function () {
  71036. return this._rightTrigger;
  71037. },
  71038. set: function (newValue) {
  71039. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71040. this._onrighttriggerchanged(newValue);
  71041. }
  71042. this._rightTrigger = newValue;
  71043. },
  71044. enumerable: true,
  71045. configurable: true
  71046. });
  71047. /**
  71048. * Defines the callback to call when a button is pressed
  71049. * @param callback defines the callback to use
  71050. */
  71051. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71052. this._onbuttondown = callback;
  71053. };
  71054. /**
  71055. * Defines the callback to call when a button is released
  71056. * @param callback defines the callback to use
  71057. */
  71058. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71059. this._onbuttonup = callback;
  71060. };
  71061. /**
  71062. * Defines the callback to call when a pad is pressed
  71063. * @param callback defines the callback to use
  71064. */
  71065. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71066. this._ondpaddown = callback;
  71067. };
  71068. /**
  71069. * Defines the callback to call when a pad is released
  71070. * @param callback defines the callback to use
  71071. */
  71072. Xbox360Pad.prototype.ondpadup = function (callback) {
  71073. this._ondpadup = callback;
  71074. };
  71075. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71076. if (newValue !== currentValue) {
  71077. if (newValue === 1) {
  71078. if (this._onbuttondown) {
  71079. this._onbuttondown(buttonType);
  71080. }
  71081. this.onButtonDownObservable.notifyObservers(buttonType);
  71082. }
  71083. if (newValue === 0) {
  71084. if (this._onbuttonup) {
  71085. this._onbuttonup(buttonType);
  71086. }
  71087. this.onButtonUpObservable.notifyObservers(buttonType);
  71088. }
  71089. }
  71090. return newValue;
  71091. };
  71092. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71093. if (newValue !== currentValue) {
  71094. if (newValue === 1) {
  71095. if (this._ondpaddown) {
  71096. this._ondpaddown(buttonType);
  71097. }
  71098. this.onPadDownObservable.notifyObservers(buttonType);
  71099. }
  71100. if (newValue === 0) {
  71101. if (this._ondpadup) {
  71102. this._ondpadup(buttonType);
  71103. }
  71104. this.onPadUpObservable.notifyObservers(buttonType);
  71105. }
  71106. }
  71107. return newValue;
  71108. };
  71109. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71110. /** Gets or sets value of A button */
  71111. get: function () {
  71112. return this._buttonA;
  71113. },
  71114. set: function (value) {
  71115. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71116. },
  71117. enumerable: true,
  71118. configurable: true
  71119. });
  71120. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71121. /** Gets or sets value of B button */
  71122. get: function () {
  71123. return this._buttonB;
  71124. },
  71125. set: function (value) {
  71126. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71127. },
  71128. enumerable: true,
  71129. configurable: true
  71130. });
  71131. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71132. /** Gets or sets value of X button */
  71133. get: function () {
  71134. return this._buttonX;
  71135. },
  71136. set: function (value) {
  71137. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71138. },
  71139. enumerable: true,
  71140. configurable: true
  71141. });
  71142. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71143. /** Gets or sets value of Y button */
  71144. get: function () {
  71145. return this._buttonY;
  71146. },
  71147. set: function (value) {
  71148. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71149. },
  71150. enumerable: true,
  71151. configurable: true
  71152. });
  71153. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71154. /** Gets or sets value of Start button */
  71155. get: function () {
  71156. return this._buttonStart;
  71157. },
  71158. set: function (value) {
  71159. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71160. },
  71161. enumerable: true,
  71162. configurable: true
  71163. });
  71164. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71165. /** Gets or sets value of Back button */
  71166. get: function () {
  71167. return this._buttonBack;
  71168. },
  71169. set: function (value) {
  71170. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71171. },
  71172. enumerable: true,
  71173. configurable: true
  71174. });
  71175. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71176. /** Gets or sets value of Left button */
  71177. get: function () {
  71178. return this._buttonLB;
  71179. },
  71180. set: function (value) {
  71181. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71182. },
  71183. enumerable: true,
  71184. configurable: true
  71185. });
  71186. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71187. /** Gets or sets value of Right button */
  71188. get: function () {
  71189. return this._buttonRB;
  71190. },
  71191. set: function (value) {
  71192. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71193. },
  71194. enumerable: true,
  71195. configurable: true
  71196. });
  71197. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71198. /** Gets or sets value of left stick */
  71199. get: function () {
  71200. return this._buttonLeftStick;
  71201. },
  71202. set: function (value) {
  71203. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71204. },
  71205. enumerable: true,
  71206. configurable: true
  71207. });
  71208. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71209. /** Gets or sets value of right stick */
  71210. get: function () {
  71211. return this._buttonRightStick;
  71212. },
  71213. set: function (value) {
  71214. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71215. },
  71216. enumerable: true,
  71217. configurable: true
  71218. });
  71219. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71220. /** Gets or sets value of DPad up */
  71221. get: function () {
  71222. return this._dPadUp;
  71223. },
  71224. set: function (value) {
  71225. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71226. },
  71227. enumerable: true,
  71228. configurable: true
  71229. });
  71230. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71231. /** Gets or sets value of DPad down */
  71232. get: function () {
  71233. return this._dPadDown;
  71234. },
  71235. set: function (value) {
  71236. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71237. },
  71238. enumerable: true,
  71239. configurable: true
  71240. });
  71241. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71242. /** Gets or sets value of DPad left */
  71243. get: function () {
  71244. return this._dPadLeft;
  71245. },
  71246. set: function (value) {
  71247. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71248. },
  71249. enumerable: true,
  71250. configurable: true
  71251. });
  71252. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71253. /** Gets or sets value of DPad right */
  71254. get: function () {
  71255. return this._dPadRight;
  71256. },
  71257. set: function (value) {
  71258. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71259. },
  71260. enumerable: true,
  71261. configurable: true
  71262. });
  71263. /**
  71264. * Force the gamepad to synchronize with device values
  71265. */
  71266. Xbox360Pad.prototype.update = function () {
  71267. _super.prototype.update.call(this);
  71268. if (this._isXboxOnePad) {
  71269. this.buttonA = this.browserGamepad.buttons[0].value;
  71270. this.buttonB = this.browserGamepad.buttons[1].value;
  71271. this.buttonX = this.browserGamepad.buttons[2].value;
  71272. this.buttonY = this.browserGamepad.buttons[3].value;
  71273. this.buttonLB = this.browserGamepad.buttons[4].value;
  71274. this.buttonRB = this.browserGamepad.buttons[5].value;
  71275. this.leftTrigger = this.browserGamepad.axes[2];
  71276. this.rightTrigger = this.browserGamepad.axes[5];
  71277. this.buttonBack = this.browserGamepad.buttons[9].value;
  71278. this.buttonStart = this.browserGamepad.buttons[8].value;
  71279. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71280. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71281. this.dPadUp = this.browserGamepad.buttons[11].value;
  71282. this.dPadDown = this.browserGamepad.buttons[12].value;
  71283. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71284. this.dPadRight = this.browserGamepad.buttons[14].value;
  71285. }
  71286. else {
  71287. this.buttonA = this.browserGamepad.buttons[0].value;
  71288. this.buttonB = this.browserGamepad.buttons[1].value;
  71289. this.buttonX = this.browserGamepad.buttons[2].value;
  71290. this.buttonY = this.browserGamepad.buttons[3].value;
  71291. this.buttonLB = this.browserGamepad.buttons[4].value;
  71292. this.buttonRB = this.browserGamepad.buttons[5].value;
  71293. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71294. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71295. this.buttonBack = this.browserGamepad.buttons[8].value;
  71296. this.buttonStart = this.browserGamepad.buttons[9].value;
  71297. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71298. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71299. this.dPadUp = this.browserGamepad.buttons[12].value;
  71300. this.dPadDown = this.browserGamepad.buttons[13].value;
  71301. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71302. this.dPadRight = this.browserGamepad.buttons[15].value;
  71303. }
  71304. };
  71305. Xbox360Pad.prototype.dispose = function () {
  71306. _super.prototype.dispose.call(this);
  71307. this.onButtonDownObservable.clear();
  71308. this.onButtonUpObservable.clear();
  71309. this.onPadDownObservable.clear();
  71310. this.onPadUpObservable.clear();
  71311. };
  71312. return Xbox360Pad;
  71313. }(BABYLON.Gamepad));
  71314. BABYLON.Xbox360Pad = Xbox360Pad;
  71315. })(BABYLON || (BABYLON = {}));
  71316. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71317. var BABYLON;
  71318. (function (BABYLON) {
  71319. /**
  71320. * Defines the types of pose enabled controllers that are supported
  71321. */
  71322. var PoseEnabledControllerType;
  71323. (function (PoseEnabledControllerType) {
  71324. /**
  71325. * HTC Vive
  71326. */
  71327. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71328. /**
  71329. * Oculus Rift
  71330. */
  71331. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71332. /**
  71333. * Windows mixed reality
  71334. */
  71335. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71336. /**
  71337. * Samsung gear VR
  71338. */
  71339. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71340. /**
  71341. * Google Daydream
  71342. */
  71343. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71344. /**
  71345. * Generic
  71346. */
  71347. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71348. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71349. /**
  71350. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71351. */
  71352. var PoseEnabledControllerHelper = /** @class */ (function () {
  71353. function PoseEnabledControllerHelper() {
  71354. }
  71355. /**
  71356. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71357. * @param vrGamepad the gamepad to initialized
  71358. * @returns a vr controller of the type the gamepad identified as
  71359. */
  71360. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71361. // Oculus Touch
  71362. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71363. return new BABYLON.OculusTouchController(vrGamepad);
  71364. }
  71365. // Windows Mixed Reality controllers
  71366. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71367. return new BABYLON.WindowsMotionController(vrGamepad);
  71368. }
  71369. // HTC Vive
  71370. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71371. return new BABYLON.ViveController(vrGamepad);
  71372. }
  71373. // Samsung/Oculus Gear VR or Oculus Go
  71374. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71375. return new BABYLON.GearVRController(vrGamepad);
  71376. }
  71377. // Google Daydream
  71378. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71379. return new BABYLON.DaydreamController(vrGamepad);
  71380. }
  71381. // Generic
  71382. else {
  71383. return new BABYLON.GenericController(vrGamepad);
  71384. }
  71385. };
  71386. return PoseEnabledControllerHelper;
  71387. }());
  71388. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71389. /**
  71390. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71391. */
  71392. var PoseEnabledController = /** @class */ (function (_super) {
  71393. __extends(PoseEnabledController, _super);
  71394. /**
  71395. * Creates a new PoseEnabledController from a gamepad
  71396. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71397. */
  71398. function PoseEnabledController(browserGamepad) {
  71399. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71400. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71401. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71402. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71403. /**
  71404. * The device position in babylon space
  71405. */
  71406. _this.devicePosition = BABYLON.Vector3.Zero();
  71407. /**
  71408. * The device rotation in babylon space
  71409. */
  71410. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71411. /**
  71412. * The scale factor of the device in babylon space
  71413. */
  71414. _this.deviceScaleFactor = 1;
  71415. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71416. /**
  71417. * Internal, matrix used to convert room space to babylon space
  71418. */
  71419. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71420. /**
  71421. * Node to be used when casting a ray from the controller
  71422. */
  71423. _this._pointingPoseNode = null;
  71424. _this._workingMatrix = BABYLON.Matrix.Identity();
  71425. /**
  71426. * @hidden
  71427. */
  71428. _this._meshAttachedObservable = new BABYLON.Observable();
  71429. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71430. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71431. _this.position = BABYLON.Vector3.Zero();
  71432. _this.rotationQuaternion = new BABYLON.Quaternion();
  71433. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71434. _this._calculatedRotation = new BABYLON.Quaternion();
  71435. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71436. return _this;
  71437. }
  71438. /**
  71439. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71440. */
  71441. PoseEnabledController.prototype.update = function () {
  71442. _super.prototype.update.call(this);
  71443. var pose = this.browserGamepad.pose;
  71444. this.updateFromDevice(pose);
  71445. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71446. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71447. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71448. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71449. if (this._mesh) {
  71450. this._mesh.position.copyFrom(this.devicePosition);
  71451. if (this._mesh.rotationQuaternion) {
  71452. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71453. }
  71454. }
  71455. };
  71456. /**
  71457. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71458. * @param poseData raw pose fromthe device
  71459. */
  71460. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71461. if (poseData) {
  71462. this.rawPose = poseData;
  71463. if (poseData.position) {
  71464. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71465. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71466. this._deviceRoomPosition.z *= -1;
  71467. }
  71468. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71469. this._calculatedPosition.addInPlace(this.position);
  71470. }
  71471. var pose = this.rawPose;
  71472. if (poseData.orientation && pose.orientation) {
  71473. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71474. if (this._mesh) {
  71475. if (this._mesh.getScene().useRightHandedSystem) {
  71476. this._deviceRoomRotationQuaternion.z *= -1;
  71477. this._deviceRoomRotationQuaternion.w *= -1;
  71478. }
  71479. else {
  71480. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71481. }
  71482. }
  71483. // if the camera is set, rotate to the camera's rotation
  71484. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71485. }
  71486. }
  71487. };
  71488. /**
  71489. * Attaches a mesh to the controller
  71490. * @param mesh the mesh to be attached
  71491. */
  71492. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71493. if (this._mesh) {
  71494. this._mesh.parent = null;
  71495. }
  71496. this._mesh = mesh;
  71497. if (this._poseControlledCamera) {
  71498. this._mesh.parent = this._poseControlledCamera;
  71499. }
  71500. if (!this._mesh.rotationQuaternion) {
  71501. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71502. }
  71503. // Sync controller mesh and pointing pose node's state with controller
  71504. this.update();
  71505. if (this._pointingPoseNode) {
  71506. var parents = [];
  71507. var obj = this._pointingPoseNode;
  71508. while (obj.parent) {
  71509. parents.push(obj.parent);
  71510. obj = obj.parent;
  71511. }
  71512. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71513. }
  71514. this._meshAttachedObservable.notifyObservers(mesh);
  71515. };
  71516. /**
  71517. * Attaches the controllers mesh to a camera
  71518. * @param camera the camera the mesh should be attached to
  71519. */
  71520. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71521. this._poseControlledCamera = camera;
  71522. if (this._mesh) {
  71523. this._mesh.parent = this._poseControlledCamera;
  71524. }
  71525. };
  71526. /**
  71527. * Disposes of the controller
  71528. */
  71529. PoseEnabledController.prototype.dispose = function () {
  71530. if (this._mesh) {
  71531. this._mesh.dispose();
  71532. }
  71533. this._mesh = null;
  71534. _super.prototype.dispose.call(this);
  71535. };
  71536. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71537. /**
  71538. * The mesh that is attached to the controller
  71539. */
  71540. get: function () {
  71541. return this._mesh;
  71542. },
  71543. enumerable: true,
  71544. configurable: true
  71545. });
  71546. /**
  71547. * Gets the ray of the controller in the direction the controller is pointing
  71548. * @param length the length the resulting ray should be
  71549. * @returns a ray in the direction the controller is pointing
  71550. */
  71551. PoseEnabledController.prototype.getForwardRay = function (length) {
  71552. if (length === void 0) { length = 100; }
  71553. if (!this.mesh) {
  71554. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71555. }
  71556. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71557. var origin = m.getTranslation();
  71558. var forward = new BABYLON.Vector3(0, 0, -1);
  71559. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71560. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71561. return new BABYLON.Ray(origin, direction, length);
  71562. };
  71563. /**
  71564. * Name of the child mesh that can be used to cast a ray from the controller
  71565. */
  71566. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71567. return PoseEnabledController;
  71568. }(BABYLON.Gamepad));
  71569. BABYLON.PoseEnabledController = PoseEnabledController;
  71570. })(BABYLON || (BABYLON = {}));
  71571. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71572. var BABYLON;
  71573. (function (BABYLON) {
  71574. /**
  71575. * Defines the WebVRController object that represents controllers tracked in 3D space
  71576. */
  71577. var WebVRController = /** @class */ (function (_super) {
  71578. __extends(WebVRController, _super);
  71579. /**
  71580. * Creates a new WebVRController from a gamepad
  71581. * @param vrGamepad the gamepad that the WebVRController should be created from
  71582. */
  71583. function WebVRController(vrGamepad) {
  71584. var _this = _super.call(this, vrGamepad) || this;
  71585. // Observables
  71586. /**
  71587. * Fired when the trigger state has changed
  71588. */
  71589. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71590. /**
  71591. * Fired when the main button state has changed
  71592. */
  71593. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71594. /**
  71595. * Fired when the secondary button state has changed
  71596. */
  71597. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71598. /**
  71599. * Fired when the pad state has changed
  71600. */
  71601. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71602. /**
  71603. * Fired when controllers stick values have changed
  71604. */
  71605. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71606. /**
  71607. * X and Y axis corrisponding to the controllers joystick
  71608. */
  71609. _this.pad = { x: 0, y: 0 };
  71610. // avoid GC, store state in a tmp object
  71611. _this._changes = {
  71612. pressChanged: false,
  71613. touchChanged: false,
  71614. valueChanged: false,
  71615. changed: false
  71616. };
  71617. _this._buttons = new Array(vrGamepad.buttons.length);
  71618. _this.hand = vrGamepad.hand;
  71619. return _this;
  71620. }
  71621. /**
  71622. * Fired when a controller button's state has changed
  71623. * @param callback the callback containing the button that was modified
  71624. */
  71625. WebVRController.prototype.onButtonStateChange = function (callback) {
  71626. this._onButtonStateChange = callback;
  71627. };
  71628. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71629. /**
  71630. * The default controller model for the controller
  71631. */
  71632. get: function () {
  71633. return this._defaultModel;
  71634. },
  71635. enumerable: true,
  71636. configurable: true
  71637. });
  71638. /**
  71639. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71640. */
  71641. WebVRController.prototype.update = function () {
  71642. _super.prototype.update.call(this);
  71643. for (var index = 0; index < this._buttons.length; index++) {
  71644. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71645. }
  71646. ;
  71647. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71648. this.pad.x = this.leftStick.x;
  71649. this.pad.y = this.leftStick.y;
  71650. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71651. }
  71652. };
  71653. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71654. if (!newState) {
  71655. newState = {
  71656. pressed: false,
  71657. touched: false,
  71658. value: 0
  71659. };
  71660. }
  71661. if (!currentState) {
  71662. this._buttons[buttonIndex] = {
  71663. pressed: newState.pressed,
  71664. touched: newState.touched,
  71665. value: newState.value
  71666. };
  71667. return;
  71668. }
  71669. this._checkChanges(newState, currentState);
  71670. if (this._changes.changed) {
  71671. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71672. this._handleButtonChange(buttonIndex, newState, this._changes);
  71673. }
  71674. this._buttons[buttonIndex].pressed = newState.pressed;
  71675. this._buttons[buttonIndex].touched = newState.touched;
  71676. // oculus triggers are never 0, thou not touched.
  71677. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71678. };
  71679. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71680. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71681. this._changes.touchChanged = newState.touched !== currentState.touched;
  71682. this._changes.valueChanged = newState.value !== currentState.value;
  71683. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71684. return this._changes;
  71685. };
  71686. /**
  71687. * Disposes of th webVRCOntroller
  71688. */
  71689. WebVRController.prototype.dispose = function () {
  71690. _super.prototype.dispose.call(this);
  71691. this.onTriggerStateChangedObservable.clear();
  71692. this.onMainButtonStateChangedObservable.clear();
  71693. this.onSecondaryButtonStateChangedObservable.clear();
  71694. this.onPadStateChangedObservable.clear();
  71695. this.onPadValuesChangedObservable.clear();
  71696. };
  71697. return WebVRController;
  71698. }(BABYLON.PoseEnabledController));
  71699. BABYLON.WebVRController = WebVRController;
  71700. })(BABYLON || (BABYLON = {}));
  71701. //# sourceMappingURL=babylon.webVRController.js.map
  71702. var BABYLON;
  71703. (function (BABYLON) {
  71704. /**
  71705. * Oculus Touch Controller
  71706. */
  71707. var OculusTouchController = /** @class */ (function (_super) {
  71708. __extends(OculusTouchController, _super);
  71709. /**
  71710. * Creates a new OculusTouchController from a gamepad
  71711. * @param vrGamepad the gamepad that the controller should be created from
  71712. */
  71713. function OculusTouchController(vrGamepad) {
  71714. var _this = _super.call(this, vrGamepad) || this;
  71715. /**
  71716. * Fired when the secondary trigger on this controller is modified
  71717. */
  71718. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71719. /**
  71720. * Fired when the thumb rest on this controller is modified
  71721. */
  71722. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71723. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71724. return _this;
  71725. }
  71726. /**
  71727. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71728. * @param scene scene in which to add meshes
  71729. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71730. */
  71731. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71732. var _this = this;
  71733. var meshName;
  71734. // Hand
  71735. if (this.hand === 'left') {
  71736. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71737. }
  71738. else { // Right is the default if no hand is specified
  71739. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71740. }
  71741. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71742. /*
  71743. Parent Mesh name: oculus_touch_left
  71744. - body
  71745. - trigger
  71746. - thumbstick
  71747. - grip
  71748. - button_y
  71749. - button_x
  71750. - button_enter
  71751. */
  71752. _this._defaultModel = newMeshes[1];
  71753. _this.attachToMesh(_this._defaultModel);
  71754. if (meshLoaded) {
  71755. meshLoaded(_this._defaultModel);
  71756. }
  71757. });
  71758. };
  71759. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71760. /**
  71761. * Fired when the A button on this controller is modified
  71762. */
  71763. get: function () {
  71764. if (this.hand === 'right') {
  71765. return this.onMainButtonStateChangedObservable;
  71766. }
  71767. else {
  71768. throw new Error('No A button on left hand');
  71769. }
  71770. },
  71771. enumerable: true,
  71772. configurable: true
  71773. });
  71774. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71775. /**
  71776. * Fired when the B button on this controller is modified
  71777. */
  71778. get: function () {
  71779. if (this.hand === 'right') {
  71780. return this.onSecondaryButtonStateChangedObservable;
  71781. }
  71782. else {
  71783. throw new Error('No B button on left hand');
  71784. }
  71785. },
  71786. enumerable: true,
  71787. configurable: true
  71788. });
  71789. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71790. /**
  71791. * Fired when the X button on this controller is modified
  71792. */
  71793. get: function () {
  71794. if (this.hand === 'left') {
  71795. return this.onMainButtonStateChangedObservable;
  71796. }
  71797. else {
  71798. throw new Error('No X button on right hand');
  71799. }
  71800. },
  71801. enumerable: true,
  71802. configurable: true
  71803. });
  71804. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71805. /**
  71806. * Fired when the Y button on this controller is modified
  71807. */
  71808. get: function () {
  71809. if (this.hand === 'left') {
  71810. return this.onSecondaryButtonStateChangedObservable;
  71811. }
  71812. else {
  71813. throw new Error('No Y button on right hand');
  71814. }
  71815. },
  71816. enumerable: true,
  71817. configurable: true
  71818. });
  71819. /**
  71820. * Called once for each button that changed state since the last frame
  71821. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71822. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71823. * 2) secondary trigger (same)
  71824. * 3) A (right) X (left), touch, pressed = value
  71825. * 4) B / Y
  71826. * 5) thumb rest
  71827. * @param buttonIdx Which button index changed
  71828. * @param state New state of the button
  71829. * @param changes Which properties on the state changed since last frame
  71830. */
  71831. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71832. var notifyObject = state; //{ state: state, changes: changes };
  71833. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71834. switch (buttonIdx) {
  71835. case 0:
  71836. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71837. return;
  71838. case 1: // index trigger
  71839. if (this._defaultModel) {
  71840. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71841. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71842. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71843. }
  71844. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71845. return;
  71846. case 2: // secondary trigger
  71847. if (this._defaultModel) {
  71848. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71849. }
  71850. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71851. return;
  71852. case 3:
  71853. if (this._defaultModel) {
  71854. if (notifyObject.pressed) {
  71855. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71856. }
  71857. else {
  71858. (this._defaultModel.getChildren()[1]).position.y = 0;
  71859. }
  71860. }
  71861. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71862. return;
  71863. case 4:
  71864. if (this._defaultModel) {
  71865. if (notifyObject.pressed) {
  71866. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71867. }
  71868. else {
  71869. (this._defaultModel.getChildren()[2]).position.y = 0;
  71870. }
  71871. }
  71872. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71873. return;
  71874. case 5:
  71875. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71876. return;
  71877. }
  71878. };
  71879. /**
  71880. * Base Url for the controller model.
  71881. */
  71882. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71883. /**
  71884. * File name for the left controller model.
  71885. */
  71886. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71887. /**
  71888. * File name for the right controller model.
  71889. */
  71890. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71891. return OculusTouchController;
  71892. }(BABYLON.WebVRController));
  71893. BABYLON.OculusTouchController = OculusTouchController;
  71894. })(BABYLON || (BABYLON = {}));
  71895. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71896. var BABYLON;
  71897. (function (BABYLON) {
  71898. /**
  71899. * Vive Controller
  71900. */
  71901. var ViveController = /** @class */ (function (_super) {
  71902. __extends(ViveController, _super);
  71903. /**
  71904. * Creates a new ViveController from a gamepad
  71905. * @param vrGamepad the gamepad that the controller should be created from
  71906. */
  71907. function ViveController(vrGamepad) {
  71908. var _this = _super.call(this, vrGamepad) || this;
  71909. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71910. _this._invertLeftStickY = true;
  71911. return _this;
  71912. }
  71913. /**
  71914. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71915. * @param scene scene in which to add meshes
  71916. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71917. */
  71918. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71919. var _this = this;
  71920. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71921. /*
  71922. Parent Mesh name: ViveWand
  71923. - body
  71924. - r_gripper
  71925. - l_gripper
  71926. - menu_button
  71927. - system_button
  71928. - trackpad
  71929. - trigger
  71930. - LED
  71931. */
  71932. _this._defaultModel = newMeshes[1];
  71933. _this.attachToMesh(_this._defaultModel);
  71934. if (meshLoaded) {
  71935. meshLoaded(_this._defaultModel);
  71936. }
  71937. });
  71938. };
  71939. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71940. /**
  71941. * Fired when the left button on this controller is modified
  71942. */
  71943. get: function () {
  71944. return this.onMainButtonStateChangedObservable;
  71945. },
  71946. enumerable: true,
  71947. configurable: true
  71948. });
  71949. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71950. /**
  71951. * Fired when the right button on this controller is modified
  71952. */
  71953. get: function () {
  71954. return this.onMainButtonStateChangedObservable;
  71955. },
  71956. enumerable: true,
  71957. configurable: true
  71958. });
  71959. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71960. /**
  71961. * Fired when the menu button on this controller is modified
  71962. */
  71963. get: function () {
  71964. return this.onSecondaryButtonStateChangedObservable;
  71965. },
  71966. enumerable: true,
  71967. configurable: true
  71968. });
  71969. /**
  71970. * Called once for each button that changed state since the last frame
  71971. * Vive mapping:
  71972. * 0: touchpad
  71973. * 1: trigger
  71974. * 2: left AND right buttons
  71975. * 3: menu button
  71976. * @param buttonIdx Which button index changed
  71977. * @param state New state of the button
  71978. * @param changes Which properties on the state changed since last frame
  71979. */
  71980. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71981. var notifyObject = state; //{ state: state, changes: changes };
  71982. switch (buttonIdx) {
  71983. case 0:
  71984. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71985. return;
  71986. case 1: // index trigger
  71987. if (this._defaultModel) {
  71988. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71989. }
  71990. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71991. return;
  71992. case 2: // left AND right button
  71993. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71994. return;
  71995. case 3:
  71996. if (this._defaultModel) {
  71997. if (notifyObject.pressed) {
  71998. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71999. }
  72000. else {
  72001. (this._defaultModel.getChildren()[2]).position.y = 0;
  72002. }
  72003. }
  72004. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72005. return;
  72006. }
  72007. };
  72008. /**
  72009. * Base Url for the controller model.
  72010. */
  72011. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72012. /**
  72013. * File name for the controller model.
  72014. */
  72015. ViveController.MODEL_FILENAME = 'wand.babylon';
  72016. return ViveController;
  72017. }(BABYLON.WebVRController));
  72018. BABYLON.ViveController = ViveController;
  72019. })(BABYLON || (BABYLON = {}));
  72020. //# sourceMappingURL=babylon.viveController.js.map
  72021. var BABYLON;
  72022. (function (BABYLON) {
  72023. /**
  72024. * Generic Controller
  72025. */
  72026. var GenericController = /** @class */ (function (_super) {
  72027. __extends(GenericController, _super);
  72028. /**
  72029. * Creates a new GenericController from a gamepad
  72030. * @param vrGamepad the gamepad that the controller should be created from
  72031. */
  72032. function GenericController(vrGamepad) {
  72033. return _super.call(this, vrGamepad) || this;
  72034. }
  72035. /**
  72036. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72037. * @param scene scene in which to add meshes
  72038. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72039. */
  72040. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72041. var _this = this;
  72042. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72043. _this._defaultModel = newMeshes[1];
  72044. _this.attachToMesh(_this._defaultModel);
  72045. if (meshLoaded) {
  72046. meshLoaded(_this._defaultModel);
  72047. }
  72048. });
  72049. };
  72050. /**
  72051. * Called once for each button that changed state since the last frame
  72052. * @param buttonIdx Which button index changed
  72053. * @param state New state of the button
  72054. * @param changes Which properties on the state changed since last frame
  72055. */
  72056. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72057. console.log("Button id: " + buttonIdx + "state: ");
  72058. console.dir(state);
  72059. };
  72060. /**
  72061. * Base Url for the controller model.
  72062. */
  72063. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72064. /**
  72065. * File name for the controller model.
  72066. */
  72067. GenericController.MODEL_FILENAME = 'generic.babylon';
  72068. return GenericController;
  72069. }(BABYLON.WebVRController));
  72070. BABYLON.GenericController = GenericController;
  72071. })(BABYLON || (BABYLON = {}));
  72072. //# sourceMappingURL=babylon.genericController.js.map
  72073. var BABYLON;
  72074. (function (BABYLON) {
  72075. /**
  72076. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72077. */
  72078. var LoadedMeshInfo = /** @class */ (function () {
  72079. function LoadedMeshInfo() {
  72080. /**
  72081. * Map of the button meshes contained in the controller
  72082. */
  72083. this.buttonMeshes = {};
  72084. /**
  72085. * Map of the axis meshes contained in the controller
  72086. */
  72087. this.axisMeshes = {};
  72088. }
  72089. return LoadedMeshInfo;
  72090. }());
  72091. /**
  72092. * Defines the WindowsMotionController object that the state of the windows motion controller
  72093. */
  72094. var WindowsMotionController = /** @class */ (function (_super) {
  72095. __extends(WindowsMotionController, _super);
  72096. /**
  72097. * Creates a new WindowsMotionController from a gamepad
  72098. * @param vrGamepad the gamepad that the controller should be created from
  72099. */
  72100. function WindowsMotionController(vrGamepad) {
  72101. var _this = _super.call(this, vrGamepad) || this;
  72102. _this._mapping = {
  72103. // Semantic button names
  72104. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72105. // A mapping of the button name to glTF model node name
  72106. // that should be transformed by button value.
  72107. buttonMeshNames: {
  72108. 'trigger': 'SELECT',
  72109. 'menu': 'MENU',
  72110. 'grip': 'GRASP',
  72111. 'thumbstick': 'THUMBSTICK_PRESS',
  72112. 'trackpad': 'TOUCHPAD_PRESS'
  72113. },
  72114. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72115. buttonObservableNames: {
  72116. 'trigger': 'onTriggerStateChangedObservable',
  72117. 'menu': 'onSecondaryButtonStateChangedObservable',
  72118. 'grip': 'onMainButtonStateChangedObservable',
  72119. 'thumbstick': 'onPadStateChangedObservable',
  72120. 'trackpad': 'onTrackpadChangedObservable'
  72121. },
  72122. // A mapping of the axis name to glTF model node name
  72123. // that should be transformed by axis value.
  72124. // This array mirrors the browserGamepad.axes array, such that
  72125. // the mesh corresponding to axis 0 is in this array index 0.
  72126. axisMeshNames: [
  72127. 'THUMBSTICK_X',
  72128. 'THUMBSTICK_Y',
  72129. 'TOUCHPAD_TOUCH_X',
  72130. 'TOUCHPAD_TOUCH_Y'
  72131. ],
  72132. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72133. };
  72134. /**
  72135. * Fired when the trackpad on this controller is clicked
  72136. */
  72137. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72138. /**
  72139. * Fired when the trackpad on this controller is modified
  72140. */
  72141. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72142. /**
  72143. * The current x and y values of this controller's trackpad
  72144. */
  72145. _this.trackpad = { x: 0, y: 0 };
  72146. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72147. _this._loadedMeshInfo = null;
  72148. return _this;
  72149. }
  72150. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72151. /**
  72152. * Fired when the trigger on this controller is modified
  72153. */
  72154. get: function () {
  72155. return this.onTriggerStateChangedObservable;
  72156. },
  72157. enumerable: true,
  72158. configurable: true
  72159. });
  72160. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72161. /**
  72162. * Fired when the menu button on this controller is modified
  72163. */
  72164. get: function () {
  72165. return this.onSecondaryButtonStateChangedObservable;
  72166. },
  72167. enumerable: true,
  72168. configurable: true
  72169. });
  72170. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72171. /**
  72172. * Fired when the grip button on this controller is modified
  72173. */
  72174. get: function () {
  72175. return this.onMainButtonStateChangedObservable;
  72176. },
  72177. enumerable: true,
  72178. configurable: true
  72179. });
  72180. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72181. /**
  72182. * Fired when the thumbstick button on this controller is modified
  72183. */
  72184. get: function () {
  72185. return this.onPadStateChangedObservable;
  72186. },
  72187. enumerable: true,
  72188. configurable: true
  72189. });
  72190. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72191. /**
  72192. * Fired when the touchpad button on this controller is modified
  72193. */
  72194. get: function () {
  72195. return this.onTrackpadChangedObservable;
  72196. },
  72197. enumerable: true,
  72198. configurable: true
  72199. });
  72200. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72201. /**
  72202. * Fired when the touchpad values on this controller are modified
  72203. */
  72204. get: function () {
  72205. return this.onTrackpadValuesChangedObservable;
  72206. },
  72207. enumerable: true,
  72208. configurable: true
  72209. });
  72210. WindowsMotionController.prototype._updateTrackpad = function () {
  72211. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72212. this.trackpad.x = this.browserGamepad["axes"][2];
  72213. this.trackpad.y = this.browserGamepad["axes"][3];
  72214. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72215. }
  72216. };
  72217. /**
  72218. * Called once per frame by the engine.
  72219. */
  72220. WindowsMotionController.prototype.update = function () {
  72221. _super.prototype.update.call(this);
  72222. if (this.browserGamepad.axes) {
  72223. this._updateTrackpad();
  72224. // Only need to animate axes if there is a loaded mesh
  72225. if (this._loadedMeshInfo) {
  72226. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72227. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72228. }
  72229. }
  72230. }
  72231. };
  72232. /**
  72233. * Called once for each button that changed state since the last frame
  72234. * @param buttonIdx Which button index changed
  72235. * @param state New state of the button
  72236. * @param changes Which properties on the state changed since last frame
  72237. */
  72238. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72239. var buttonName = this._mapping.buttons[buttonIdx];
  72240. if (!buttonName) {
  72241. return;
  72242. }
  72243. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72244. this._updateTrackpad();
  72245. // Only emit events for buttons that we know how to map from index to name
  72246. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72247. if (observable) {
  72248. observable.notifyObservers(state);
  72249. }
  72250. this._lerpButtonTransform(buttonName, state.value);
  72251. };
  72252. /**
  72253. * Moves the buttons on the controller mesh based on their current state
  72254. * @param buttonName the name of the button to move
  72255. * @param buttonValue the value of the button which determines the buttons new position
  72256. */
  72257. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72258. // If there is no loaded mesh, there is nothing to transform.
  72259. if (!this._loadedMeshInfo) {
  72260. return;
  72261. }
  72262. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72263. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72264. return;
  72265. }
  72266. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72267. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72268. };
  72269. /**
  72270. * Moves the axis on the controller mesh based on its current state
  72271. * @param axis the index of the axis
  72272. * @param axisValue the value of the axis which determines the meshes new position
  72273. * @hidden
  72274. */
  72275. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72276. if (!this._loadedMeshInfo) {
  72277. return;
  72278. }
  72279. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72280. if (!meshInfo) {
  72281. return;
  72282. }
  72283. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72284. return;
  72285. }
  72286. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72287. var lerpValue = axisValue * 0.5 + 0.5;
  72288. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72289. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72290. };
  72291. /**
  72292. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72293. * @param scene scene in which to add meshes
  72294. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72295. */
  72296. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72297. var _this = this;
  72298. if (forceDefault === void 0) { forceDefault = false; }
  72299. var path;
  72300. var filename;
  72301. // Checking if GLB loader is present
  72302. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72303. // Determine the device specific folder based on the ID suffix
  72304. var device = 'default';
  72305. if (this.id && !forceDefault) {
  72306. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72307. device = ((match && match[0]) || device);
  72308. }
  72309. // Hand
  72310. if (this.hand === 'left') {
  72311. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72312. }
  72313. else { // Right is the default if no hand is specified
  72314. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72315. }
  72316. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72317. }
  72318. else {
  72319. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72320. path = BABYLON.GenericController.MODEL_BASE_URL;
  72321. filename = BABYLON.GenericController.MODEL_FILENAME;
  72322. }
  72323. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72324. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72325. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72326. if (!_this._loadedMeshInfo) {
  72327. return;
  72328. }
  72329. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72330. _this.attachToMesh(_this._defaultModel);
  72331. if (meshLoaded) {
  72332. meshLoaded(_this._defaultModel);
  72333. }
  72334. }, null, function (scene, message) {
  72335. BABYLON.Tools.Log(message);
  72336. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72337. if (!forceDefault) {
  72338. _this.initControllerMesh(scene, meshLoaded, true);
  72339. }
  72340. });
  72341. };
  72342. /**
  72343. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72344. * can be transformed by button presses and axes values, based on this._mapping.
  72345. *
  72346. * @param scene scene in which the meshes exist
  72347. * @param meshes list of meshes that make up the controller model to process
  72348. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72349. */
  72350. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72351. var loadedMeshInfo = null;
  72352. // Create a new mesh to contain the glTF hierarchy
  72353. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72354. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72355. var childMesh = null;
  72356. for (var i = 0; i < meshes.length; i++) {
  72357. var mesh = meshes[i];
  72358. if (!mesh.parent) {
  72359. // Exclude controller meshes from picking results
  72360. mesh.isPickable = false;
  72361. // Handle root node, attach to the new parentMesh
  72362. childMesh = mesh;
  72363. break;
  72364. }
  72365. }
  72366. if (childMesh) {
  72367. childMesh.setParent(parentMesh);
  72368. // Create our mesh info. Note that this method will always return non-null.
  72369. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72370. }
  72371. else {
  72372. BABYLON.Tools.Warn('Could not find root node in model file.');
  72373. }
  72374. return loadedMeshInfo;
  72375. };
  72376. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72377. var loadedMeshInfo = new LoadedMeshInfo();
  72378. var i;
  72379. loadedMeshInfo.rootNode = rootNode;
  72380. // Reset the caches
  72381. loadedMeshInfo.buttonMeshes = {};
  72382. loadedMeshInfo.axisMeshes = {};
  72383. // Button Meshes
  72384. for (i = 0; i < this._mapping.buttons.length; i++) {
  72385. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72386. if (!buttonMeshName) {
  72387. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72388. continue;
  72389. }
  72390. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72391. if (!buttonMesh) {
  72392. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72393. continue;
  72394. }
  72395. var buttonMeshInfo = {
  72396. index: i,
  72397. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72398. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72399. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72400. };
  72401. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72402. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72403. }
  72404. else {
  72405. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72406. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72407. '(VALUE: ' + !!buttonMeshInfo.value +
  72408. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72409. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72410. ')');
  72411. }
  72412. }
  72413. // Axis Meshes
  72414. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72415. var axisMeshName = this._mapping.axisMeshNames[i];
  72416. if (!axisMeshName) {
  72417. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72418. continue;
  72419. }
  72420. var axisMesh = getChildByName(rootNode, axisMeshName);
  72421. if (!axisMesh) {
  72422. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72423. continue;
  72424. }
  72425. var axisMeshInfo = {
  72426. index: i,
  72427. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72428. min: getImmediateChildByName(axisMesh, 'MIN'),
  72429. max: getImmediateChildByName(axisMesh, 'MAX')
  72430. };
  72431. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72432. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72433. }
  72434. else {
  72435. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72436. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72437. '(VALUE: ' + !!axisMeshInfo.value +
  72438. ', MIN: ' + !!axisMeshInfo.min +
  72439. ', MAX:' + !!axisMeshInfo.max +
  72440. ')');
  72441. }
  72442. }
  72443. // Pointing Ray
  72444. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72445. if (!loadedMeshInfo.pointingPoseNode) {
  72446. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72447. }
  72448. else {
  72449. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72450. }
  72451. return loadedMeshInfo;
  72452. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72453. function getChildByName(node, name) {
  72454. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72455. }
  72456. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72457. function getImmediateChildByName(node, name) {
  72458. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72459. }
  72460. };
  72461. /**
  72462. * Gets the ray of the controller in the direction the controller is pointing
  72463. * @param length the length the resulting ray should be
  72464. * @returns a ray in the direction the controller is pointing
  72465. */
  72466. WindowsMotionController.prototype.getForwardRay = function (length) {
  72467. if (length === void 0) { length = 100; }
  72468. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72469. return _super.prototype.getForwardRay.call(this, length);
  72470. }
  72471. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72472. var origin = m.getTranslation();
  72473. var forward = new BABYLON.Vector3(0, 0, -1);
  72474. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72475. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72476. return new BABYLON.Ray(origin, direction, length);
  72477. };
  72478. /**
  72479. * Disposes of the controller
  72480. */
  72481. WindowsMotionController.prototype.dispose = function () {
  72482. _super.prototype.dispose.call(this);
  72483. this.onTrackpadChangedObservable.clear();
  72484. };
  72485. /**
  72486. * The base url used to load the left and right controller models
  72487. */
  72488. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72489. /**
  72490. * The name of the left controller model file
  72491. */
  72492. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72493. /**
  72494. * The name of the right controller model file
  72495. */
  72496. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72497. /**
  72498. * The controller name prefix for this controller type
  72499. */
  72500. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72501. /**
  72502. * The controller id pattern for this controller type
  72503. */
  72504. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72505. return WindowsMotionController;
  72506. }(BABYLON.WebVRController));
  72507. BABYLON.WindowsMotionController = WindowsMotionController;
  72508. })(BABYLON || (BABYLON = {}));
  72509. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72510. var BABYLON;
  72511. (function (BABYLON) {
  72512. /**
  72513. * Gear VR Controller
  72514. */
  72515. var GearVRController = /** @class */ (function (_super) {
  72516. __extends(GearVRController, _super);
  72517. /**
  72518. * Creates a new GearVRController from a gamepad
  72519. * @param vrGamepad the gamepad that the controller should be created from
  72520. */
  72521. function GearVRController(vrGamepad) {
  72522. var _this = _super.call(this, vrGamepad) || this;
  72523. _this._buttonIndexToObservableNameMap = [
  72524. 'onTrackpadChangedObservable',
  72525. 'onTriggerStateChangedObservable' // Trigger
  72526. ];
  72527. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72528. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72529. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72530. return _this;
  72531. }
  72532. /**
  72533. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72534. * @param scene scene in which to add meshes
  72535. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72536. */
  72537. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72538. var _this = this;
  72539. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72540. _this._defaultModel = newMeshes[1];
  72541. _this.attachToMesh(_this._defaultModel);
  72542. if (meshLoaded) {
  72543. meshLoaded(_this._defaultModel);
  72544. }
  72545. });
  72546. };
  72547. /**
  72548. * Called once for each button that changed state since the last frame
  72549. * @param buttonIdx Which button index changed
  72550. * @param state New state of the button
  72551. * @param changes Which properties on the state changed since last frame
  72552. */
  72553. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72554. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72555. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72556. // Only emit events for buttons that we know how to map from index to observable
  72557. var observable = this[observableName];
  72558. if (observable) {
  72559. observable.notifyObservers(state);
  72560. }
  72561. }
  72562. };
  72563. /**
  72564. * Base Url for the controller model.
  72565. */
  72566. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72567. /**
  72568. * File name for the controller model.
  72569. */
  72570. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72571. /**
  72572. * Gamepad Id prefix used to identify this controller.
  72573. */
  72574. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72575. return GearVRController;
  72576. }(BABYLON.WebVRController));
  72577. BABYLON.GearVRController = GearVRController;
  72578. })(BABYLON || (BABYLON = {}));
  72579. //# sourceMappingURL=babylon.gearVRController.js.map
  72580. var BABYLON;
  72581. (function (BABYLON) {
  72582. /**
  72583. * Google Daydream controller
  72584. */
  72585. var DaydreamController = /** @class */ (function (_super) {
  72586. __extends(DaydreamController, _super);
  72587. /**
  72588. * Creates a new DaydreamController from a gamepad
  72589. * @param vrGamepad the gamepad that the controller should be created from
  72590. */
  72591. function DaydreamController(vrGamepad) {
  72592. var _this = _super.call(this, vrGamepad) || this;
  72593. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72594. return _this;
  72595. }
  72596. /**
  72597. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72598. * @param scene scene in which to add meshes
  72599. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72600. */
  72601. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72602. var _this = this;
  72603. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72604. _this._defaultModel = newMeshes[1];
  72605. _this.attachToMesh(_this._defaultModel);
  72606. if (meshLoaded) {
  72607. meshLoaded(_this._defaultModel);
  72608. }
  72609. });
  72610. };
  72611. /**
  72612. * Called once for each button that changed state since the last frame
  72613. * @param buttonIdx Which button index changed
  72614. * @param state New state of the button
  72615. * @param changes Which properties on the state changed since last frame
  72616. */
  72617. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72618. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72619. if (buttonIdx === 0) {
  72620. var observable = this.onTriggerStateChangedObservable;
  72621. if (observable) {
  72622. observable.notifyObservers(state);
  72623. }
  72624. }
  72625. else {
  72626. // If the app or home buttons are ever made available
  72627. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72628. }
  72629. };
  72630. /**
  72631. * Base Url for the controller model.
  72632. */
  72633. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72634. /**
  72635. * File name for the controller model.
  72636. */
  72637. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72638. /**
  72639. * Gamepad Id prefix used to identify Daydream Controller.
  72640. */
  72641. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72642. return DaydreamController;
  72643. }(BABYLON.WebVRController));
  72644. BABYLON.DaydreamController = DaydreamController;
  72645. })(BABYLON || (BABYLON = {}));
  72646. //# sourceMappingURL=babylon.daydreamController.js.map
  72647. var BABYLON;
  72648. (function (BABYLON) {
  72649. var FollowCamera = /** @class */ (function (_super) {
  72650. __extends(FollowCamera, _super);
  72651. function FollowCamera(name, position, scene, lockedTarget) {
  72652. if (lockedTarget === void 0) { lockedTarget = null; }
  72653. var _this = _super.call(this, name, position, scene) || this;
  72654. _this.radius = 12;
  72655. _this.rotationOffset = 0;
  72656. _this.heightOffset = 4;
  72657. _this.cameraAcceleration = 0.05;
  72658. _this.maxCameraSpeed = 20;
  72659. _this.lockedTarget = lockedTarget;
  72660. return _this;
  72661. }
  72662. FollowCamera.prototype.getRadians = function (degrees) {
  72663. return degrees * Math.PI / 180;
  72664. };
  72665. FollowCamera.prototype.follow = function (cameraTarget) {
  72666. if (!cameraTarget)
  72667. return;
  72668. var yRotation;
  72669. if (cameraTarget.rotationQuaternion) {
  72670. var rotMatrix = new BABYLON.Matrix();
  72671. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72672. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72673. }
  72674. else {
  72675. yRotation = cameraTarget.rotation.y;
  72676. }
  72677. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72678. var targetPosition = cameraTarget.getAbsolutePosition();
  72679. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72680. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72681. var dx = targetX - this.position.x;
  72682. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72683. var dz = (targetZ) - this.position.z;
  72684. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72685. var vy = dy * this.cameraAcceleration;
  72686. var vz = dz * this.cameraAcceleration * 2;
  72687. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72688. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72689. }
  72690. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72691. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72692. }
  72693. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72694. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72695. }
  72696. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72697. this.setTarget(targetPosition);
  72698. };
  72699. FollowCamera.prototype._checkInputs = function () {
  72700. _super.prototype._checkInputs.call(this);
  72701. if (this.lockedTarget) {
  72702. this.follow(this.lockedTarget);
  72703. }
  72704. };
  72705. FollowCamera.prototype.getClassName = function () {
  72706. return "FollowCamera";
  72707. };
  72708. __decorate([
  72709. BABYLON.serialize()
  72710. ], FollowCamera.prototype, "radius", void 0);
  72711. __decorate([
  72712. BABYLON.serialize()
  72713. ], FollowCamera.prototype, "rotationOffset", void 0);
  72714. __decorate([
  72715. BABYLON.serialize()
  72716. ], FollowCamera.prototype, "heightOffset", void 0);
  72717. __decorate([
  72718. BABYLON.serialize()
  72719. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72720. __decorate([
  72721. BABYLON.serialize()
  72722. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72723. __decorate([
  72724. BABYLON.serializeAsMeshReference("lockedTargetId")
  72725. ], FollowCamera.prototype, "lockedTarget", void 0);
  72726. return FollowCamera;
  72727. }(BABYLON.TargetCamera));
  72728. BABYLON.FollowCamera = FollowCamera;
  72729. var ArcFollowCamera = /** @class */ (function (_super) {
  72730. __extends(ArcFollowCamera, _super);
  72731. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72732. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72733. _this.alpha = alpha;
  72734. _this.beta = beta;
  72735. _this.radius = radius;
  72736. _this.target = target;
  72737. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72738. _this.follow();
  72739. return _this;
  72740. }
  72741. ArcFollowCamera.prototype.follow = function () {
  72742. if (!this.target) {
  72743. return;
  72744. }
  72745. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72746. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72747. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72748. var targetPosition = this.target.getAbsolutePosition();
  72749. this.position = targetPosition.add(this._cartesianCoordinates);
  72750. this.setTarget(targetPosition);
  72751. };
  72752. ArcFollowCamera.prototype._checkInputs = function () {
  72753. _super.prototype._checkInputs.call(this);
  72754. this.follow();
  72755. };
  72756. ArcFollowCamera.prototype.getClassName = function () {
  72757. return "ArcFollowCamera";
  72758. };
  72759. return ArcFollowCamera;
  72760. }(BABYLON.TargetCamera));
  72761. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72762. })(BABYLON || (BABYLON = {}));
  72763. //# sourceMappingURL=babylon.followCamera.js.map
  72764. var BABYLON;
  72765. (function (BABYLON) {
  72766. // We're mainly based on the logic defined into the FreeCamera code
  72767. var UniversalCamera = /** @class */ (function (_super) {
  72768. __extends(UniversalCamera, _super);
  72769. //-- end properties for backward compatibility for inputs
  72770. function UniversalCamera(name, position, scene) {
  72771. var _this = _super.call(this, name, position, scene) || this;
  72772. _this.inputs.addGamepad();
  72773. return _this;
  72774. }
  72775. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72776. //-- Begin properties for backward compatibility for inputs
  72777. get: function () {
  72778. var gamepad = this.inputs.attached["gamepad"];
  72779. if (gamepad)
  72780. return gamepad.gamepadAngularSensibility;
  72781. return 0;
  72782. },
  72783. set: function (value) {
  72784. var gamepad = this.inputs.attached["gamepad"];
  72785. if (gamepad)
  72786. gamepad.gamepadAngularSensibility = value;
  72787. },
  72788. enumerable: true,
  72789. configurable: true
  72790. });
  72791. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72792. get: function () {
  72793. var gamepad = this.inputs.attached["gamepad"];
  72794. if (gamepad)
  72795. return gamepad.gamepadMoveSensibility;
  72796. return 0;
  72797. },
  72798. set: function (value) {
  72799. var gamepad = this.inputs.attached["gamepad"];
  72800. if (gamepad)
  72801. gamepad.gamepadMoveSensibility = value;
  72802. },
  72803. enumerable: true,
  72804. configurable: true
  72805. });
  72806. UniversalCamera.prototype.getClassName = function () {
  72807. return "UniversalCamera";
  72808. };
  72809. return UniversalCamera;
  72810. }(BABYLON.TouchCamera));
  72811. BABYLON.UniversalCamera = UniversalCamera;
  72812. })(BABYLON || (BABYLON = {}));
  72813. //# sourceMappingURL=babylon.universalCamera.js.map
  72814. var BABYLON;
  72815. (function (BABYLON) {
  72816. // We're mainly based on the logic defined into the FreeCamera code
  72817. var GamepadCamera = /** @class */ (function (_super) {
  72818. __extends(GamepadCamera, _super);
  72819. //-- end properties for backward compatibility for inputs
  72820. function GamepadCamera(name, position, scene) {
  72821. return _super.call(this, name, position, scene) || this;
  72822. }
  72823. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72824. //-- Begin properties for backward compatibility for inputs
  72825. get: function () {
  72826. var gamepad = this.inputs.attached["gamepad"];
  72827. if (gamepad)
  72828. return gamepad.gamepadAngularSensibility;
  72829. return 0;
  72830. },
  72831. set: function (value) {
  72832. var gamepad = this.inputs.attached["gamepad"];
  72833. if (gamepad)
  72834. gamepad.gamepadAngularSensibility = value;
  72835. },
  72836. enumerable: true,
  72837. configurable: true
  72838. });
  72839. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72840. get: function () {
  72841. var gamepad = this.inputs.attached["gamepad"];
  72842. if (gamepad)
  72843. return gamepad.gamepadMoveSensibility;
  72844. return 0;
  72845. },
  72846. set: function (value) {
  72847. var gamepad = this.inputs.attached["gamepad"];
  72848. if (gamepad)
  72849. gamepad.gamepadMoveSensibility = value;
  72850. },
  72851. enumerable: true,
  72852. configurable: true
  72853. });
  72854. GamepadCamera.prototype.getClassName = function () {
  72855. return "GamepadCamera";
  72856. };
  72857. return GamepadCamera;
  72858. }(BABYLON.UniversalCamera));
  72859. BABYLON.GamepadCamera = GamepadCamera;
  72860. })(BABYLON || (BABYLON = {}));
  72861. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72862. var BABYLON;
  72863. (function (BABYLON) {
  72864. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72865. function PostProcessRenderPipelineManager() {
  72866. this._renderPipelines = {};
  72867. }
  72868. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72869. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72870. };
  72871. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72872. if (unique === void 0) { unique = false; }
  72873. var renderPipeline = this._renderPipelines[renderPipelineName];
  72874. if (!renderPipeline) {
  72875. return;
  72876. }
  72877. renderPipeline._attachCameras(cameras, unique);
  72878. };
  72879. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72880. var renderPipeline = this._renderPipelines[renderPipelineName];
  72881. if (!renderPipeline) {
  72882. return;
  72883. }
  72884. renderPipeline._detachCameras(cameras);
  72885. };
  72886. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72887. var renderPipeline = this._renderPipelines[renderPipelineName];
  72888. if (!renderPipeline) {
  72889. return;
  72890. }
  72891. renderPipeline._enableEffect(renderEffectName, cameras);
  72892. };
  72893. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72894. var renderPipeline = this._renderPipelines[renderPipelineName];
  72895. if (!renderPipeline) {
  72896. return;
  72897. }
  72898. renderPipeline._disableEffect(renderEffectName, cameras);
  72899. };
  72900. PostProcessRenderPipelineManager.prototype.update = function () {
  72901. for (var renderPipelineName in this._renderPipelines) {
  72902. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72903. var pipeline = this._renderPipelines[renderPipelineName];
  72904. if (!pipeline.isSupported) {
  72905. pipeline.dispose();
  72906. delete this._renderPipelines[renderPipelineName];
  72907. }
  72908. else {
  72909. pipeline._update();
  72910. }
  72911. }
  72912. }
  72913. };
  72914. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72915. for (var renderPipelineName in this._renderPipelines) {
  72916. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72917. var pipeline = this._renderPipelines[renderPipelineName];
  72918. pipeline._rebuild();
  72919. }
  72920. }
  72921. };
  72922. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72923. for (var renderPipelineName in this._renderPipelines) {
  72924. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72925. var pipeline = this._renderPipelines[renderPipelineName];
  72926. pipeline.dispose();
  72927. }
  72928. }
  72929. };
  72930. return PostProcessRenderPipelineManager;
  72931. }());
  72932. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72933. })(BABYLON || (BABYLON = {}));
  72934. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72935. var BABYLON;
  72936. (function (BABYLON) {
  72937. /**
  72938. * This represents a set of one or more post processes in Babylon.
  72939. * A post process can be used to apply a shader to a texture after it is rendered.
  72940. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72941. */
  72942. var PostProcessRenderEffect = /** @class */ (function () {
  72943. /**
  72944. * Instantiates a post process render effect.
  72945. * A post process can be used to apply a shader to a texture after it is rendered.
  72946. * @param engine The engine the effect is tied to
  72947. * @param name The name of the effect
  72948. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72949. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72950. */
  72951. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72952. this._name = name;
  72953. this._singleInstance = singleInstance || true;
  72954. this._getPostProcesses = getPostProcesses;
  72955. this._cameras = {};
  72956. this._indicesForCamera = {};
  72957. this._postProcesses = {};
  72958. }
  72959. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72960. /**
  72961. * Checks if all the post processes in the effect are supported.
  72962. */
  72963. get: function () {
  72964. for (var index in this._postProcesses) {
  72965. if (this._postProcesses.hasOwnProperty(index)) {
  72966. var pps = this._postProcesses[index];
  72967. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72968. if (!pps[ppIndex].isSupported) {
  72969. return false;
  72970. }
  72971. }
  72972. }
  72973. }
  72974. return true;
  72975. },
  72976. enumerable: true,
  72977. configurable: true
  72978. });
  72979. /**
  72980. * Updates the current state of the effect
  72981. */
  72982. PostProcessRenderEffect.prototype._update = function () {
  72983. };
  72984. /**
  72985. * Attaches the effect on cameras
  72986. * @param cameras The camera to attach to.
  72987. */
  72988. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72989. var _this = this;
  72990. var cameraKey;
  72991. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72992. if (!cams) {
  72993. return;
  72994. }
  72995. for (var i = 0; i < cams.length; i++) {
  72996. var camera = cams[i];
  72997. var cameraName = camera.name;
  72998. if (this._singleInstance) {
  72999. cameraKey = 0;
  73000. }
  73001. else {
  73002. cameraKey = cameraName;
  73003. }
  73004. if (!this._postProcesses[cameraKey]) {
  73005. var postProcess = this._getPostProcesses();
  73006. if (postProcess) {
  73007. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73008. }
  73009. }
  73010. if (!this._indicesForCamera[cameraName]) {
  73011. this._indicesForCamera[cameraName] = [];
  73012. }
  73013. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73014. var index = camera.attachPostProcess(postProcess);
  73015. _this._indicesForCamera[cameraName].push(index);
  73016. });
  73017. if (!this._cameras[cameraName]) {
  73018. this._cameras[cameraName] = camera;
  73019. }
  73020. }
  73021. };
  73022. /**
  73023. * Detatches the effect on cameras
  73024. * @param cameras The camera to detatch from.
  73025. */
  73026. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73027. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73028. if (!cams) {
  73029. return;
  73030. }
  73031. for (var i = 0; i < cams.length; i++) {
  73032. var camera = cams[i];
  73033. var cameraName = camera.name;
  73034. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73035. camera.detachPostProcess(postProcess);
  73036. });
  73037. if (this._cameras[cameraName]) {
  73038. //this._indicesForCamera.splice(index, 1);
  73039. this._cameras[cameraName] = null;
  73040. }
  73041. }
  73042. };
  73043. /**
  73044. * Enables the effect on given cameras
  73045. * @param cameras The camera to enable.
  73046. */
  73047. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73048. var _this = this;
  73049. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73050. if (!cams) {
  73051. return;
  73052. }
  73053. for (var i = 0; i < cams.length; i++) {
  73054. var camera = cams[i];
  73055. var cameraName = camera.name;
  73056. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73057. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73058. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73059. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73060. });
  73061. }
  73062. }
  73063. }
  73064. };
  73065. /**
  73066. * Disables the effect on the given cameras
  73067. * @param cameras The camera to disable.
  73068. */
  73069. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73070. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73071. if (!cams) {
  73072. return;
  73073. }
  73074. for (var i = 0; i < cams.length; i++) {
  73075. var camera = cams[i];
  73076. var cameraName = camera.name;
  73077. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73078. camera.detachPostProcess(postProcess);
  73079. });
  73080. }
  73081. };
  73082. /**
  73083. * Gets a list of the post processes contained in the effect.
  73084. * @param camera The camera to get the post processes on.
  73085. * @returns The list of the post processes in the effect.
  73086. */
  73087. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73088. if (this._singleInstance) {
  73089. return this._postProcesses[0];
  73090. }
  73091. else {
  73092. if (!camera) {
  73093. return null;
  73094. }
  73095. return this._postProcesses[camera.name];
  73096. }
  73097. };
  73098. return PostProcessRenderEffect;
  73099. }());
  73100. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73101. })(BABYLON || (BABYLON = {}));
  73102. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73103. var BABYLON;
  73104. (function (BABYLON) {
  73105. var PostProcessRenderPipeline = /** @class */ (function () {
  73106. function PostProcessRenderPipeline(engine, name) {
  73107. this.engine = engine;
  73108. this._name = name;
  73109. this._renderEffects = {};
  73110. this._renderEffectsForIsolatedPass = new Array();
  73111. this._cameras = [];
  73112. }
  73113. PostProcessRenderPipeline.prototype.getClassName = function () {
  73114. return "PostProcessRenderPipeline";
  73115. };
  73116. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73117. get: function () {
  73118. for (var renderEffectName in this._renderEffects) {
  73119. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73120. if (!this._renderEffects[renderEffectName].isSupported) {
  73121. return false;
  73122. }
  73123. }
  73124. }
  73125. return true;
  73126. },
  73127. enumerable: true,
  73128. configurable: true
  73129. });
  73130. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73131. this._renderEffects[renderEffect._name] = renderEffect;
  73132. };
  73133. // private
  73134. PostProcessRenderPipeline.prototype._rebuild = function () {
  73135. };
  73136. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73137. var renderEffects = this._renderEffects[renderEffectName];
  73138. if (!renderEffects) {
  73139. return;
  73140. }
  73141. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73142. };
  73143. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73144. var renderEffects = this._renderEffects[renderEffectName];
  73145. if (!renderEffects) {
  73146. return;
  73147. }
  73148. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73149. };
  73150. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73151. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73152. if (!cams) {
  73153. return;
  73154. }
  73155. var indicesToDelete = [];
  73156. var i;
  73157. for (i = 0; i < cams.length; i++) {
  73158. var camera = cams[i];
  73159. var cameraName = camera.name;
  73160. if (this._cameras.indexOf(camera) === -1) {
  73161. this._cameras[cameraName] = camera;
  73162. }
  73163. else if (unique) {
  73164. indicesToDelete.push(i);
  73165. }
  73166. }
  73167. for (i = 0; i < indicesToDelete.length; i++) {
  73168. cameras.splice(indicesToDelete[i], 1);
  73169. }
  73170. for (var renderEffectName in this._renderEffects) {
  73171. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73172. this._renderEffects[renderEffectName]._attachCameras(cams);
  73173. }
  73174. }
  73175. };
  73176. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73177. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73178. if (!cams) {
  73179. return;
  73180. }
  73181. for (var renderEffectName in this._renderEffects) {
  73182. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73183. this._renderEffects[renderEffectName]._detachCameras(cams);
  73184. }
  73185. }
  73186. for (var i = 0; i < cams.length; i++) {
  73187. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73188. }
  73189. };
  73190. PostProcessRenderPipeline.prototype._update = function () {
  73191. for (var renderEffectName in this._renderEffects) {
  73192. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73193. this._renderEffects[renderEffectName]._update();
  73194. }
  73195. }
  73196. for (var i = 0; i < this._cameras.length; i++) {
  73197. var cameraName = this._cameras[i].name;
  73198. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73199. this._renderEffectsForIsolatedPass[cameraName]._update();
  73200. }
  73201. }
  73202. };
  73203. PostProcessRenderPipeline.prototype._reset = function () {
  73204. this._renderEffects = {};
  73205. this._renderEffectsForIsolatedPass = new Array();
  73206. };
  73207. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73208. // 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)
  73209. var effectKeys = Object.keys(this._renderEffects);
  73210. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73211. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73212. if (postProcesses) {
  73213. postProcesses[0].samples = sampleCount;
  73214. return true;
  73215. }
  73216. }
  73217. return false;
  73218. };
  73219. PostProcessRenderPipeline.prototype.dispose = function () {
  73220. // Must be implemented by children
  73221. };
  73222. __decorate([
  73223. BABYLON.serialize()
  73224. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73225. return PostProcessRenderPipeline;
  73226. }());
  73227. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73228. })(BABYLON || (BABYLON = {}));
  73229. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73230. var BABYLON;
  73231. (function (BABYLON) {
  73232. /**
  73233. * This represents a depth renderer in Babylon.
  73234. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73235. */
  73236. var DepthRenderer = /** @class */ (function () {
  73237. /**
  73238. * Instantiates a depth renderer
  73239. * @param scene The scene the renderer belongs to
  73240. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73241. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73242. */
  73243. function DepthRenderer(scene, type, camera) {
  73244. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73245. if (camera === void 0) { camera = null; }
  73246. var _this = this;
  73247. this._scene = scene;
  73248. this._camera = camera;
  73249. var engine = scene.getEngine();
  73250. // Render target
  73251. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73252. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73253. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73254. this._depthMap.refreshRate = 1;
  73255. this._depthMap.renderParticles = false;
  73256. this._depthMap.renderList = null;
  73257. // Camera to get depth map from to support multiple concurrent cameras
  73258. this._depthMap.activeCamera = this._camera;
  73259. this._depthMap.ignoreCameraViewport = true;
  73260. this._depthMap.useCameraPostProcesses = false;
  73261. // set default depth value to 1.0 (far away)
  73262. this._depthMap.onClearObservable.add(function (engine) {
  73263. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73264. });
  73265. // Custom render function
  73266. var renderSubMesh = function (subMesh) {
  73267. var mesh = subMesh.getRenderingMesh();
  73268. var scene = _this._scene;
  73269. var engine = scene.getEngine();
  73270. var material = subMesh.getMaterial();
  73271. if (!material) {
  73272. return;
  73273. }
  73274. // Culling and reverse (right handed system)
  73275. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73276. // Managing instances
  73277. var batch = mesh._getInstancesRenderList(subMesh._id);
  73278. if (batch.mustReturn) {
  73279. return;
  73280. }
  73281. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73282. var camera = _this._camera || scene.activeCamera;
  73283. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73284. engine.enableEffect(_this._effect);
  73285. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73286. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73287. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73288. // Alpha test
  73289. if (material && material.needAlphaTesting()) {
  73290. var alphaTexture = material.getAlphaTestTexture();
  73291. if (alphaTexture) {
  73292. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73293. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73294. }
  73295. }
  73296. // Bones
  73297. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73298. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73299. }
  73300. // Draw
  73301. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73302. }
  73303. };
  73304. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73305. var index;
  73306. if (depthOnlySubMeshes.length) {
  73307. engine.setColorWrite(false);
  73308. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73309. renderSubMesh(depthOnlySubMeshes.data[index]);
  73310. }
  73311. engine.setColorWrite(true);
  73312. }
  73313. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73314. renderSubMesh(opaqueSubMeshes.data[index]);
  73315. }
  73316. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73317. renderSubMesh(alphaTestSubMeshes.data[index]);
  73318. }
  73319. };
  73320. }
  73321. /**
  73322. * Creates the depth rendering effect and checks if the effect is ready.
  73323. * @param subMesh The submesh to be used to render the depth map of
  73324. * @param useInstances If multiple world instances should be used
  73325. * @returns if the depth renderer is ready to render the depth map
  73326. */
  73327. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73328. var material = subMesh.getMaterial();
  73329. if (material.disableDepthWrite) {
  73330. return false;
  73331. }
  73332. var defines = [];
  73333. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73334. var mesh = subMesh.getMesh();
  73335. // Alpha test
  73336. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73337. defines.push("#define ALPHATEST");
  73338. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73339. attribs.push(BABYLON.VertexBuffer.UVKind);
  73340. defines.push("#define UV1");
  73341. }
  73342. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73343. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73344. defines.push("#define UV2");
  73345. }
  73346. }
  73347. // Bones
  73348. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73349. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73350. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73351. if (mesh.numBoneInfluencers > 4) {
  73352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73354. }
  73355. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73356. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73357. }
  73358. else {
  73359. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73360. }
  73361. // Instances
  73362. if (useInstances) {
  73363. defines.push("#define INSTANCES");
  73364. attribs.push("world0");
  73365. attribs.push("world1");
  73366. attribs.push("world2");
  73367. attribs.push("world3");
  73368. }
  73369. // Get correct effect
  73370. var join = defines.join("\n");
  73371. if (this._cachedDefines !== join) {
  73372. this._cachedDefines = join;
  73373. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73374. }
  73375. return this._effect.isReady();
  73376. };
  73377. /**
  73378. * Gets the texture which the depth map will be written to.
  73379. * @returns The depth map texture
  73380. */
  73381. DepthRenderer.prototype.getDepthMap = function () {
  73382. return this._depthMap;
  73383. };
  73384. /**
  73385. * Disposes of the depth renderer.
  73386. */
  73387. DepthRenderer.prototype.dispose = function () {
  73388. this._depthMap.dispose();
  73389. };
  73390. return DepthRenderer;
  73391. }());
  73392. BABYLON.DepthRenderer = DepthRenderer;
  73393. })(BABYLON || (BABYLON = {}));
  73394. //# sourceMappingURL=babylon.depthRenderer.js.map
  73395. var BABYLON;
  73396. (function (BABYLON) {
  73397. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73398. __extends(SSAORenderingPipeline, _super);
  73399. /**
  73400. * @constructor
  73401. * @param {string} name - The rendering pipeline name
  73402. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73403. * @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 }
  73404. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73405. */
  73406. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73407. var _this = _super.call(this, scene.getEngine(), name) || this;
  73408. // Members
  73409. /**
  73410. * The PassPostProcess id in the pipeline that contains the original scene color
  73411. */
  73412. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73413. /**
  73414. * The SSAO PostProcess id in the pipeline
  73415. */
  73416. _this.SSAORenderEffect = "SSAORenderEffect";
  73417. /**
  73418. * The horizontal blur PostProcess id in the pipeline
  73419. */
  73420. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73421. /**
  73422. * The vertical blur PostProcess id in the pipeline
  73423. */
  73424. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73425. /**
  73426. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73427. */
  73428. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73429. /**
  73430. * The output strength of the SSAO post-process. Default value is 1.0.
  73431. */
  73432. _this.totalStrength = 1.0;
  73433. /**
  73434. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73435. */
  73436. _this.radius = 0.0001;
  73437. /**
  73438. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73439. * Must not be equal to fallOff and superior to fallOff.
  73440. * Default value is 0.975
  73441. */
  73442. _this.area = 0.0075;
  73443. /**
  73444. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73445. * Must not be equal to area and inferior to area.
  73446. * Default value is 0.0
  73447. */
  73448. _this.fallOff = 0.000001;
  73449. /**
  73450. * The base color of the SSAO post-process
  73451. * The final result is "base + ssao" between [0, 1]
  73452. */
  73453. _this.base = 0.5;
  73454. _this._firstUpdate = true;
  73455. _this._scene = scene;
  73456. // Set up assets
  73457. _this._createRandomTexture();
  73458. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73459. var ssaoRatio = ratio.ssaoRatio || ratio;
  73460. var combineRatio = ratio.combineRatio || ratio;
  73461. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73462. _this._createSSAOPostProcess(ssaoRatio);
  73463. _this._createBlurPostProcess(ssaoRatio);
  73464. _this._createSSAOCombinePostProcess(combineRatio);
  73465. // Set up pipeline
  73466. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73467. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73468. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73469. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73470. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73471. // Finish
  73472. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73473. if (cameras)
  73474. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73475. return _this;
  73476. }
  73477. // Public Methods
  73478. /**
  73479. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73480. */
  73481. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73482. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73483. for (var i = 0; i < this._scene.cameras.length; i++) {
  73484. var camera = this._scene.cameras[i];
  73485. this._originalColorPostProcess.dispose(camera);
  73486. this._ssaoPostProcess.dispose(camera);
  73487. this._blurHPostProcess.dispose(camera);
  73488. this._blurVPostProcess.dispose(camera);
  73489. this._ssaoCombinePostProcess.dispose(camera);
  73490. }
  73491. this._randomTexture.dispose();
  73492. if (disableDepthRender)
  73493. this._scene.disableDepthRenderer();
  73494. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73495. _super.prototype.dispose.call(this);
  73496. };
  73497. // Private Methods
  73498. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73499. var _this = this;
  73500. var size = 16;
  73501. 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);
  73502. 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);
  73503. this._blurHPostProcess.onActivateObservable.add(function () {
  73504. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73505. _this._blurHPostProcess.kernel = size * dw;
  73506. });
  73507. this._blurVPostProcess.onActivateObservable.add(function () {
  73508. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73509. _this._blurVPostProcess.kernel = size * dw;
  73510. });
  73511. };
  73512. SSAORenderingPipeline.prototype._rebuild = function () {
  73513. this._firstUpdate = true;
  73514. _super.prototype._rebuild.call(this);
  73515. };
  73516. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73517. var _this = this;
  73518. var numSamples = 16;
  73519. var sampleSphere = [
  73520. 0.5381, 0.1856, -0.4319,
  73521. 0.1379, 0.2486, 0.4430,
  73522. 0.3371, 0.5679, -0.0057,
  73523. -0.6999, -0.0451, -0.0019,
  73524. 0.0689, -0.1598, -0.8547,
  73525. 0.0560, 0.0069, -0.1843,
  73526. -0.0146, 0.1402, 0.0762,
  73527. 0.0100, -0.1924, -0.0344,
  73528. -0.3577, -0.5301, -0.4358,
  73529. -0.3169, 0.1063, 0.0158,
  73530. 0.0103, -0.5869, 0.0046,
  73531. -0.0897, -0.4940, 0.3287,
  73532. 0.7119, -0.0154, -0.0918,
  73533. -0.0533, 0.0596, -0.5411,
  73534. 0.0352, -0.0631, 0.5460,
  73535. -0.4776, 0.2847, -0.0271
  73536. ];
  73537. var samplesFactor = 1.0 / numSamples;
  73538. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73539. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73540. "area", "fallOff", "base", "range", "viewport"
  73541. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73542. this._ssaoPostProcess.onApply = function (effect) {
  73543. if (_this._firstUpdate) {
  73544. effect.setArray3("sampleSphere", sampleSphere);
  73545. effect.setFloat("samplesFactor", samplesFactor);
  73546. effect.setFloat("randTextureTiles", 4.0);
  73547. }
  73548. effect.setFloat("totalStrength", _this.totalStrength);
  73549. effect.setFloat("radius", _this.radius);
  73550. effect.setFloat("area", _this.area);
  73551. effect.setFloat("fallOff", _this.fallOff);
  73552. effect.setFloat("base", _this.base);
  73553. effect.setTexture("textureSampler", _this._depthTexture);
  73554. effect.setTexture("randomSampler", _this._randomTexture);
  73555. };
  73556. };
  73557. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73558. var _this = this;
  73559. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73560. this._ssaoCombinePostProcess.onApply = function (effect) {
  73561. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73562. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73563. };
  73564. };
  73565. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73566. var size = 512;
  73567. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73568. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73569. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73570. var context = this._randomTexture.getContext();
  73571. var rand = function (min, max) {
  73572. return Math.random() * (max - min) + min;
  73573. };
  73574. var randVector = BABYLON.Vector3.Zero();
  73575. for (var x = 0; x < size; x++) {
  73576. for (var y = 0; y < size; y++) {
  73577. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73578. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73579. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73580. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73581. context.fillRect(x, y, 1, 1);
  73582. }
  73583. }
  73584. this._randomTexture.update(false);
  73585. };
  73586. __decorate([
  73587. BABYLON.serialize()
  73588. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73589. __decorate([
  73590. BABYLON.serialize()
  73591. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73592. __decorate([
  73593. BABYLON.serialize()
  73594. ], SSAORenderingPipeline.prototype, "area", void 0);
  73595. __decorate([
  73596. BABYLON.serialize()
  73597. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73598. __decorate([
  73599. BABYLON.serialize()
  73600. ], SSAORenderingPipeline.prototype, "base", void 0);
  73601. return SSAORenderingPipeline;
  73602. }(BABYLON.PostProcessRenderPipeline));
  73603. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73604. })(BABYLON || (BABYLON = {}));
  73605. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73606. var BABYLON;
  73607. (function (BABYLON) {
  73608. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73609. __extends(SSAO2RenderingPipeline, _super);
  73610. /**
  73611. * @constructor
  73612. * @param {string} name - The rendering pipeline name
  73613. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73614. * @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 }
  73615. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73616. */
  73617. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73618. var _this = _super.call(this, scene.getEngine(), name) || this;
  73619. // Members
  73620. /**
  73621. * The PassPostProcess id in the pipeline that contains the original scene color
  73622. */
  73623. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73624. /**
  73625. * The SSAO PostProcess id in the pipeline
  73626. */
  73627. _this.SSAORenderEffect = "SSAORenderEffect";
  73628. /**
  73629. * The horizontal blur PostProcess id in the pipeline
  73630. */
  73631. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73632. /**
  73633. * The vertical blur PostProcess id in the pipeline
  73634. */
  73635. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73636. /**
  73637. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73638. */
  73639. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73640. /**
  73641. * The output strength of the SSAO post-process. Default value is 1.0.
  73642. */
  73643. _this.totalStrength = 1.0;
  73644. /**
  73645. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73646. */
  73647. _this.maxZ = 100.0;
  73648. /**
  73649. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73650. */
  73651. _this.minZAspect = 0.2;
  73652. /**
  73653. * Number of samples used for the SSAO calculations. Default value is 8
  73654. */
  73655. _this._samples = 8;
  73656. /**
  73657. * Are we using bilateral blur ?
  73658. */
  73659. _this._expensiveBlur = true;
  73660. /**
  73661. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73662. */
  73663. _this.radius = 2.0;
  73664. /**
  73665. * The base color of the SSAO post-process
  73666. * The final result is "base + ssao" between [0, 1]
  73667. */
  73668. _this.base = 0.1;
  73669. _this._firstUpdate = true;
  73670. _this._scene = scene;
  73671. _this._ratio = ratio;
  73672. if (!_this.isSupported) {
  73673. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73674. return _this;
  73675. }
  73676. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73677. var blurRatio = _this._ratio.blurRatio || ratio;
  73678. // Set up assets
  73679. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73680. _this._createRandomTexture();
  73681. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73682. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73683. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73684. _this._createSSAOPostProcess(1.0);
  73685. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73686. _this._createSSAOCombinePostProcess(blurRatio);
  73687. // Set up pipeline
  73688. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73689. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73690. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73691. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73692. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73693. // Finish
  73694. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73695. if (cameras)
  73696. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73697. return _this;
  73698. }
  73699. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73700. get: function () {
  73701. return this._samples;
  73702. },
  73703. set: function (n) {
  73704. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73705. this._samples = n;
  73706. this._sampleSphere = this._generateHemisphere();
  73707. this._firstUpdate = true;
  73708. },
  73709. enumerable: true,
  73710. configurable: true
  73711. });
  73712. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73713. get: function () {
  73714. return this._expensiveBlur;
  73715. },
  73716. set: function (b) {
  73717. 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"]);
  73718. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73719. this._expensiveBlur = b;
  73720. this._firstUpdate = true;
  73721. },
  73722. enumerable: true,
  73723. configurable: true
  73724. });
  73725. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73726. /**
  73727. * Support test.
  73728. */
  73729. get: function () {
  73730. var engine = BABYLON.Engine.LastCreatedEngine;
  73731. if (!engine) {
  73732. return false;
  73733. }
  73734. return engine.getCaps().drawBuffersExtension;
  73735. },
  73736. enumerable: true,
  73737. configurable: true
  73738. });
  73739. // Public Methods
  73740. /**
  73741. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73742. */
  73743. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73744. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73745. for (var i = 0; i < this._scene.cameras.length; i++) {
  73746. var camera = this._scene.cameras[i];
  73747. this._originalColorPostProcess.dispose(camera);
  73748. this._ssaoPostProcess.dispose(camera);
  73749. this._blurHPostProcess.dispose(camera);
  73750. this._blurVPostProcess.dispose(camera);
  73751. this._ssaoCombinePostProcess.dispose(camera);
  73752. }
  73753. this._randomTexture.dispose();
  73754. if (disableGeometryBufferRenderer)
  73755. this._scene.disableGeometryBufferRenderer();
  73756. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73757. _super.prototype.dispose.call(this);
  73758. };
  73759. // Private Methods
  73760. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73761. var _this = this;
  73762. this._samplerOffsets = [];
  73763. var expensive = this.expensiveBlur;
  73764. for (var i = -8; i < 8; i++) {
  73765. this._samplerOffsets.push(i * 2 + 0.5);
  73766. }
  73767. 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");
  73768. this._blurHPostProcess.onApply = function (effect) {
  73769. if (!_this._scene.activeCamera) {
  73770. return;
  73771. }
  73772. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73773. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73774. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73775. effect.setFloat("radius", _this.radius);
  73776. effect.setTexture("depthSampler", _this._depthTexture);
  73777. if (_this._firstUpdate) {
  73778. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73779. }
  73780. };
  73781. 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");
  73782. this._blurVPostProcess.onApply = function (effect) {
  73783. if (!_this._scene.activeCamera) {
  73784. return;
  73785. }
  73786. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73787. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73788. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73789. effect.setFloat("radius", _this.radius);
  73790. effect.setTexture("depthSampler", _this._depthTexture);
  73791. if (_this._firstUpdate) {
  73792. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73793. _this._firstUpdate = false;
  73794. }
  73795. };
  73796. };
  73797. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73798. this._firstUpdate = true;
  73799. _super.prototype._rebuild.call(this);
  73800. };
  73801. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73802. var numSamples = this.samples;
  73803. var result = [];
  73804. var vector, scale;
  73805. var rand = function (min, max) {
  73806. return Math.random() * (max - min) + min;
  73807. };
  73808. var i = 0;
  73809. while (i < numSamples) {
  73810. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73811. vector.normalize();
  73812. scale = i / numSamples;
  73813. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73814. vector.scaleInPlace(scale);
  73815. result.push(vector.x, vector.y, vector.z);
  73816. i++;
  73817. }
  73818. return result;
  73819. };
  73820. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73821. var _this = this;
  73822. var numSamples = this.samples;
  73823. this._sampleSphere = this._generateHemisphere();
  73824. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73825. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73826. "base", "range", "projection", "near", "far", "texelSize",
  73827. "xViewport", "yViewport", "maxZ", "minZAspect"
  73828. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73829. this._ssaoPostProcess.onApply = function (effect) {
  73830. if (_this._firstUpdate) {
  73831. effect.setArray3("sampleSphere", _this._sampleSphere);
  73832. effect.setFloat("randTextureTiles", 4.0);
  73833. }
  73834. if (!_this._scene.activeCamera) {
  73835. return;
  73836. }
  73837. effect.setFloat("samplesFactor", 1 / _this.samples);
  73838. effect.setFloat("totalStrength", _this.totalStrength);
  73839. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73840. effect.setFloat("radius", _this.radius);
  73841. effect.setFloat("maxZ", _this.maxZ);
  73842. effect.setFloat("minZAspect", _this.minZAspect);
  73843. effect.setFloat("base", _this.base);
  73844. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73845. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73846. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73847. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73848. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73849. effect.setTexture("textureSampler", _this._depthTexture);
  73850. effect.setTexture("normalSampler", _this._normalTexture);
  73851. effect.setTexture("randomSampler", _this._randomTexture);
  73852. };
  73853. };
  73854. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73855. var _this = this;
  73856. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73857. this._ssaoCombinePostProcess.onApply = function (effect) {
  73858. var viewport = _this._scene.activeCamera.viewport;
  73859. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73860. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73861. };
  73862. };
  73863. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73864. var size = 512;
  73865. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73866. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73867. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73868. var context = this._randomTexture.getContext();
  73869. var rand = function (min, max) {
  73870. return Math.random() * (max - min) + min;
  73871. };
  73872. var randVector = BABYLON.Vector3.Zero();
  73873. for (var x = 0; x < size; x++) {
  73874. for (var y = 0; y < size; y++) {
  73875. randVector.x = rand(0.0, 1.0);
  73876. randVector.y = rand(0.0, 1.0);
  73877. randVector.z = 0.0;
  73878. randVector.normalize();
  73879. randVector.scaleInPlace(255);
  73880. randVector.x = Math.floor(randVector.x);
  73881. randVector.y = Math.floor(randVector.y);
  73882. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73883. context.fillRect(x, y, 1, 1);
  73884. }
  73885. }
  73886. this._randomTexture.update(false);
  73887. };
  73888. /**
  73889. * Serialize the rendering pipeline (Used when exporting)
  73890. * @returns the serialized object
  73891. */
  73892. SSAO2RenderingPipeline.prototype.serialize = function () {
  73893. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73894. serializationObject.customType = "SSAO2RenderingPipeline";
  73895. return serializationObject;
  73896. };
  73897. /**
  73898. * Parse the serialized pipeline
  73899. * @param source Source pipeline.
  73900. * @param scene The scene to load the pipeline to.
  73901. * @param rootUrl The URL of the serialized pipeline.
  73902. * @returns An instantiated pipeline from the serialized object.
  73903. */
  73904. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73905. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73906. };
  73907. __decorate([
  73908. BABYLON.serialize()
  73909. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73910. __decorate([
  73911. BABYLON.serialize()
  73912. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73913. __decorate([
  73914. BABYLON.serialize()
  73915. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73916. __decorate([
  73917. BABYLON.serialize("samples")
  73918. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73919. __decorate([
  73920. BABYLON.serialize()
  73921. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73922. __decorate([
  73923. BABYLON.serialize("expensiveBlur")
  73924. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73925. __decorate([
  73926. BABYLON.serialize()
  73927. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73928. __decorate([
  73929. BABYLON.serialize()
  73930. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73931. return SSAO2RenderingPipeline;
  73932. }(BABYLON.PostProcessRenderPipeline));
  73933. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73934. })(BABYLON || (BABYLON = {}));
  73935. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73936. // BABYLON.JS Chromatic Aberration GLSL Shader
  73937. // Author: Olivier Guyot
  73938. // Separates very slightly R, G and B colors on the edges of the screen
  73939. // Inspired by Francois Tarlier & Martins Upitis
  73940. var BABYLON;
  73941. (function (BABYLON) {
  73942. var LensRenderingPipeline = /** @class */ (function (_super) {
  73943. __extends(LensRenderingPipeline, _super);
  73944. /**
  73945. * @constructor
  73946. *
  73947. * Effect parameters are as follow:
  73948. * {
  73949. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73950. * edge_blur: number; // from 0 to x (1 for realism)
  73951. * distortion: number; // from 0 to x (1 for realism)
  73952. * grain_amount: number; // from 0 to 1
  73953. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73954. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73955. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73956. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73957. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73958. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73959. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73960. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73961. * }
  73962. * Note: if an effect parameter is unset, effect is disabled
  73963. *
  73964. * @param {string} name - The rendering pipeline name
  73965. * @param {object} parameters - An object containing all parameters (see above)
  73966. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73967. * @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)
  73968. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73969. */
  73970. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73971. if (ratio === void 0) { ratio = 1.0; }
  73972. var _this = _super.call(this, scene.getEngine(), name) || this;
  73973. // Lens effects can be of the following:
  73974. // - chromatic aberration (slight shift of RGB colors)
  73975. // - blur on the edge of the lens
  73976. // - lens distortion
  73977. // - depth-of-field blur & highlights enhancing
  73978. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73979. // - grain effect (noise or custom texture)
  73980. // Two additional texture samplers are needed:
  73981. // - depth map (for depth-of-field)
  73982. // - grain texture
  73983. /**
  73984. * The chromatic aberration PostProcess id in the pipeline
  73985. */
  73986. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73987. /**
  73988. * The highlights enhancing PostProcess id in the pipeline
  73989. */
  73990. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73991. /**
  73992. * The depth-of-field PostProcess id in the pipeline
  73993. */
  73994. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73995. _this._scene = scene;
  73996. // Fetch texture samplers
  73997. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73998. if (parameters.grain_texture) {
  73999. _this._grainTexture = parameters.grain_texture;
  74000. }
  74001. else {
  74002. _this._createGrainTexture();
  74003. }
  74004. // save parameters
  74005. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74006. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74007. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74008. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74009. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74010. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74011. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74012. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74013. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74014. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74015. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74016. // Create effects
  74017. _this._createChromaticAberrationPostProcess(ratio);
  74018. _this._createHighlightsPostProcess(ratio);
  74019. _this._createDepthOfFieldPostProcess(ratio / 4);
  74020. // Set up pipeline
  74021. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74022. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74023. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74024. if (_this._highlightsGain === -1) {
  74025. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74026. }
  74027. // Finish
  74028. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74029. if (cameras) {
  74030. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74031. }
  74032. return _this;
  74033. }
  74034. // public methods (self explanatory)
  74035. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74036. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74037. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74038. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74039. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74040. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74041. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74042. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74043. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74044. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74045. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74046. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74047. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74048. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74049. };
  74050. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74051. this._highlightsPostProcess.updateEffect();
  74052. };
  74053. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74054. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74055. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74056. this._highlightsGain = amount;
  74057. };
  74058. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74059. if (this._highlightsGain === -1) {
  74060. this._highlightsGain = 1.0;
  74061. }
  74062. this._highlightsThreshold = amount;
  74063. };
  74064. LensRenderingPipeline.prototype.disableHighlights = function () {
  74065. this._highlightsGain = -1;
  74066. };
  74067. /**
  74068. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74069. */
  74070. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74071. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74072. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74073. this._chromaticAberrationPostProcess = null;
  74074. this._highlightsPostProcess = null;
  74075. this._depthOfFieldPostProcess = null;
  74076. this._grainTexture.dispose();
  74077. if (disableDepthRender)
  74078. this._scene.disableDepthRenderer();
  74079. };
  74080. // colors shifting and distortion
  74081. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74082. var _this = this;
  74083. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74084. [], // samplers
  74085. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74086. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74087. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74088. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74089. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74090. effect.setFloat('radialIntensity', 1);
  74091. effect.setFloat2('direction', 17, 17);
  74092. effect.setFloat2('centerPosition', 0.5, 0.5);
  74093. };
  74094. };
  74095. // highlights enhancing
  74096. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74097. var _this = this;
  74098. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74099. [], // samplers
  74100. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74101. this._highlightsPostProcess.onApply = function (effect) {
  74102. effect.setFloat('gain', _this._highlightsGain);
  74103. effect.setFloat('threshold', _this._highlightsThreshold);
  74104. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74105. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74106. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74107. };
  74108. };
  74109. // colors shifting and distortion
  74110. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74111. var _this = this;
  74112. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74113. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74114. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74115. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74116. this._depthOfFieldPostProcess.onApply = function (effect) {
  74117. effect.setTexture("depthSampler", _this._depthTexture);
  74118. effect.setTexture("grainSampler", _this._grainTexture);
  74119. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74120. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74121. effect.setFloat('grain_amount', _this._grainAmount);
  74122. effect.setBool('blur_noise', _this._blurNoise);
  74123. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74124. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74125. effect.setFloat('distortion', _this._distortion);
  74126. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74127. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74128. effect.setFloat('aperture', _this._dofAperture);
  74129. effect.setFloat('darken', _this._dofDarken);
  74130. effect.setFloat('edge_blur', _this._edgeBlur);
  74131. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74132. if (_this._scene.activeCamera) {
  74133. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74134. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74135. }
  74136. };
  74137. };
  74138. // creates a black and white random noise texture, 512x512
  74139. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74140. var size = 512;
  74141. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74142. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74143. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74144. var context = this._grainTexture.getContext();
  74145. var rand = function (min, max) {
  74146. return Math.random() * (max - min) + min;
  74147. };
  74148. var value;
  74149. for (var x = 0; x < size; x++) {
  74150. for (var y = 0; y < size; y++) {
  74151. value = Math.floor(rand(0.42, 0.58) * 255);
  74152. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74153. context.fillRect(x, y, 1, 1);
  74154. }
  74155. }
  74156. this._grainTexture.update(false);
  74157. };
  74158. return LensRenderingPipeline;
  74159. }(BABYLON.PostProcessRenderPipeline));
  74160. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74161. })(BABYLON || (BABYLON = {}));
  74162. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74163. var BABYLON;
  74164. (function (BABYLON) {
  74165. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74166. __extends(StandardRenderingPipeline, _super);
  74167. /**
  74168. * @constructor
  74169. * @param {string} name - The rendering pipeline name
  74170. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74171. * @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)
  74172. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74173. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74174. */
  74175. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74176. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74177. var _this = _super.call(this, scene.getEngine(), name) || this;
  74178. _this.downSampleX4PostProcess = null;
  74179. _this.brightPassPostProcess = null;
  74180. _this.blurHPostProcesses = [];
  74181. _this.blurVPostProcesses = [];
  74182. _this.textureAdderPostProcess = null;
  74183. _this.volumetricLightPostProcess = null;
  74184. _this.volumetricLightSmoothXPostProcess = null;
  74185. _this.volumetricLightSmoothYPostProcess = null;
  74186. _this.volumetricLightMergePostProces = null;
  74187. _this.volumetricLightFinalPostProcess = null;
  74188. _this.luminancePostProcess = null;
  74189. _this.luminanceDownSamplePostProcesses = [];
  74190. _this.hdrPostProcess = null;
  74191. _this.textureAdderFinalPostProcess = null;
  74192. _this.lensFlareFinalPostProcess = null;
  74193. _this.hdrFinalPostProcess = null;
  74194. _this.lensFlarePostProcess = null;
  74195. _this.lensFlareComposePostProcess = null;
  74196. _this.motionBlurPostProcess = null;
  74197. _this.depthOfFieldPostProcess = null;
  74198. // Values
  74199. _this.brightThreshold = 1.0;
  74200. _this.blurWidth = 512.0;
  74201. _this.horizontalBlur = false;
  74202. _this.exposure = 1.0;
  74203. _this.lensTexture = null;
  74204. _this.volumetricLightCoefficient = 0.2;
  74205. _this.volumetricLightPower = 4.0;
  74206. _this.volumetricLightBlurScale = 64.0;
  74207. _this.sourceLight = null;
  74208. _this.hdrMinimumLuminance = 1.0;
  74209. _this.hdrDecreaseRate = 0.5;
  74210. _this.hdrIncreaseRate = 0.5;
  74211. _this.lensColorTexture = null;
  74212. _this.lensFlareStrength = 20.0;
  74213. _this.lensFlareGhostDispersal = 1.4;
  74214. _this.lensFlareHaloWidth = 0.7;
  74215. _this.lensFlareDistortionStrength = 16.0;
  74216. _this.lensStarTexture = null;
  74217. _this.lensFlareDirtTexture = null;
  74218. _this.depthOfFieldDistance = 10.0;
  74219. _this.depthOfFieldBlurWidth = 64.0;
  74220. _this.motionStrength = 1.0;
  74221. // IAnimatable
  74222. _this.animations = [];
  74223. _this._currentDepthOfFieldSource = null;
  74224. _this._hdrCurrentLuminance = 1.0;
  74225. // Getters and setters
  74226. _this._bloomEnabled = true;
  74227. _this._depthOfFieldEnabled = false;
  74228. _this._vlsEnabled = false;
  74229. _this._lensFlareEnabled = false;
  74230. _this._hdrEnabled = false;
  74231. _this._motionBlurEnabled = false;
  74232. _this._motionBlurSamples = 64.0;
  74233. _this._volumetricLightStepsCount = 50.0;
  74234. _this._cameras = cameras || [];
  74235. // Initialize
  74236. _this._scene = scene;
  74237. _this._basePostProcess = originalPostProcess;
  74238. _this._ratio = ratio;
  74239. // Misc
  74240. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74241. // Finish
  74242. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74243. _this._buildPipeline();
  74244. return _this;
  74245. }
  74246. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74247. get: function () {
  74248. return this._bloomEnabled;
  74249. },
  74250. set: function (enabled) {
  74251. if (this._bloomEnabled === enabled) {
  74252. return;
  74253. }
  74254. this._bloomEnabled = enabled;
  74255. this._buildPipeline();
  74256. },
  74257. enumerable: true,
  74258. configurable: true
  74259. });
  74260. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74261. get: function () {
  74262. return this._depthOfFieldEnabled;
  74263. },
  74264. set: function (enabled) {
  74265. if (this._depthOfFieldEnabled === enabled) {
  74266. return;
  74267. }
  74268. this._depthOfFieldEnabled = enabled;
  74269. this._buildPipeline();
  74270. },
  74271. enumerable: true,
  74272. configurable: true
  74273. });
  74274. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74275. get: function () {
  74276. return this._lensFlareEnabled;
  74277. },
  74278. set: function (enabled) {
  74279. if (this._lensFlareEnabled === enabled) {
  74280. return;
  74281. }
  74282. this._lensFlareEnabled = enabled;
  74283. this._buildPipeline();
  74284. },
  74285. enumerable: true,
  74286. configurable: true
  74287. });
  74288. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74289. get: function () {
  74290. return this._hdrEnabled;
  74291. },
  74292. set: function (enabled) {
  74293. if (this._hdrEnabled === enabled) {
  74294. return;
  74295. }
  74296. this._hdrEnabled = enabled;
  74297. this._buildPipeline();
  74298. },
  74299. enumerable: true,
  74300. configurable: true
  74301. });
  74302. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74303. get: function () {
  74304. return this._vlsEnabled;
  74305. },
  74306. set: function (enabled) {
  74307. if (this._vlsEnabled === enabled) {
  74308. return;
  74309. }
  74310. if (enabled) {
  74311. var geometry = this._scene.enableGeometryBufferRenderer();
  74312. if (!geometry) {
  74313. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74314. return;
  74315. }
  74316. }
  74317. this._vlsEnabled = enabled;
  74318. this._buildPipeline();
  74319. },
  74320. enumerable: true,
  74321. configurable: true
  74322. });
  74323. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74324. get: function () {
  74325. return this._motionBlurEnabled;
  74326. },
  74327. set: function (enabled) {
  74328. if (this._motionBlurEnabled === enabled) {
  74329. return;
  74330. }
  74331. this._motionBlurEnabled = enabled;
  74332. this._buildPipeline();
  74333. },
  74334. enumerable: true,
  74335. configurable: true
  74336. });
  74337. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74338. get: function () {
  74339. return this._volumetricLightStepsCount;
  74340. },
  74341. set: function (count) {
  74342. if (this.volumetricLightPostProcess) {
  74343. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74344. }
  74345. this._volumetricLightStepsCount = count;
  74346. },
  74347. enumerable: true,
  74348. configurable: true
  74349. });
  74350. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74351. get: function () {
  74352. return this._motionBlurSamples;
  74353. },
  74354. set: function (samples) {
  74355. if (this.motionBlurPostProcess) {
  74356. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74357. }
  74358. this._motionBlurSamples = samples;
  74359. },
  74360. enumerable: true,
  74361. configurable: true
  74362. });
  74363. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74364. var _this = this;
  74365. var ratio = this._ratio;
  74366. var scene = this._scene;
  74367. this._disposePostProcesses();
  74368. this._reset();
  74369. // Create pass post-process
  74370. if (!this._basePostProcess) {
  74371. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74372. this.originalPostProcess.onApply = function (effect) {
  74373. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74374. };
  74375. }
  74376. else {
  74377. this.originalPostProcess = this._basePostProcess;
  74378. }
  74379. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74380. this._currentDepthOfFieldSource = this.originalPostProcess;
  74381. if (this._bloomEnabled) {
  74382. // Create down sample X4 post-process
  74383. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74384. // Create bright pass post-process
  74385. this._createBrightPassPostProcess(scene, ratio / 2);
  74386. // Create gaussian blur post-processes (down sampling blurs)
  74387. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74388. // Create texture adder post-process
  74389. this._createTextureAdderPostProcess(scene, ratio);
  74390. // Create depth-of-field source post-process
  74391. 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);
  74392. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74393. }
  74394. if (this._vlsEnabled) {
  74395. // Create volumetric light
  74396. this._createVolumetricLightPostProcess(scene, ratio);
  74397. // Create volumetric light final post-process
  74398. 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);
  74399. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74400. }
  74401. if (this._lensFlareEnabled) {
  74402. // Create lens flare post-process
  74403. this._createLensFlarePostProcess(scene, ratio);
  74404. // Create depth-of-field source post-process post lens-flare and disable it now
  74405. 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);
  74406. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74407. }
  74408. if (this._hdrEnabled) {
  74409. // Create luminance
  74410. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74411. // Create HDR
  74412. this._createHdrPostProcess(scene, ratio);
  74413. // Create depth-of-field source post-process post hdr and disable it now
  74414. 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);
  74415. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74416. }
  74417. if (this._depthOfFieldEnabled) {
  74418. // Create gaussian blur used by depth-of-field
  74419. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74420. // Create depth-of-field post-process
  74421. this._createDepthOfFieldPostProcess(scene, ratio);
  74422. }
  74423. if (this._motionBlurEnabled) {
  74424. // Create motion blur post-process
  74425. this._createMotionBlurPostProcess(scene, ratio);
  74426. }
  74427. if (this._cameras !== null) {
  74428. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74429. }
  74430. };
  74431. // Down Sample X4 Post-Processs
  74432. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74433. var _this = this;
  74434. var downSampleX4Offsets = new Array(32);
  74435. 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);
  74436. this.downSampleX4PostProcess.onApply = function (effect) {
  74437. var id = 0;
  74438. var width = _this.downSampleX4PostProcess.width;
  74439. var height = _this.downSampleX4PostProcess.height;
  74440. for (var i = -2; i < 2; i++) {
  74441. for (var j = -2; j < 2; j++) {
  74442. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74443. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74444. id += 2;
  74445. }
  74446. }
  74447. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74448. };
  74449. // Add to pipeline
  74450. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74451. };
  74452. // Brightpass Post-Process
  74453. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74454. var _this = this;
  74455. var brightOffsets = new Array(8);
  74456. 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);
  74457. this.brightPassPostProcess.onApply = function (effect) {
  74458. var sU = (1.0 / _this.brightPassPostProcess.width);
  74459. var sV = (1.0 / _this.brightPassPostProcess.height);
  74460. brightOffsets[0] = -0.5 * sU;
  74461. brightOffsets[1] = 0.5 * sV;
  74462. brightOffsets[2] = 0.5 * sU;
  74463. brightOffsets[3] = 0.5 * sV;
  74464. brightOffsets[4] = -0.5 * sU;
  74465. brightOffsets[5] = -0.5 * sV;
  74466. brightOffsets[6] = 0.5 * sU;
  74467. brightOffsets[7] = -0.5 * sV;
  74468. effect.setArray2("dsOffsets", brightOffsets);
  74469. effect.setFloat("brightThreshold", _this.brightThreshold);
  74470. };
  74471. // Add to pipeline
  74472. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74473. };
  74474. // Create blur H&V post-processes
  74475. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74476. var _this = this;
  74477. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74478. var engine = scene.getEngine();
  74479. 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);
  74480. 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);
  74481. blurX.onActivateObservable.add(function () {
  74482. var dw = blurX.width / engine.getRenderWidth();
  74483. blurX.kernel = _this[blurWidthKey] * dw;
  74484. });
  74485. blurY.onActivateObservable.add(function () {
  74486. var dw = blurY.height / engine.getRenderHeight();
  74487. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74488. });
  74489. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74491. this.blurHPostProcesses.push(blurX);
  74492. this.blurVPostProcesses.push(blurY);
  74493. };
  74494. // Create texture adder post-process
  74495. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74496. var _this = this;
  74497. 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);
  74498. this.textureAdderPostProcess.onApply = function (effect) {
  74499. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74500. effect.setTexture("lensSampler", _this.lensTexture);
  74501. effect.setFloat("exposure", _this.exposure);
  74502. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74503. };
  74504. // Add to pipeline
  74505. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74506. };
  74507. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74508. var _this = this;
  74509. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74510. geometryRenderer.enablePosition = true;
  74511. var geometry = geometryRenderer.getGBuffer();
  74512. // Base post-process
  74513. 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));
  74514. var depthValues = BABYLON.Vector2.Zero();
  74515. this.volumetricLightPostProcess.onApply = function (effect) {
  74516. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74517. var generator = _this.sourceLight.getShadowGenerator();
  74518. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74519. effect.setTexture("positionSampler", geometry.textures[2]);
  74520. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74521. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74522. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74523. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74524. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74525. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74526. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74527. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74528. effect.setVector2("depthValues", depthValues);
  74529. }
  74530. };
  74531. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74532. // Smooth
  74533. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74534. // Merge
  74535. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74536. this.volumetricLightMergePostProces.onApply = function (effect) {
  74537. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74538. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74539. };
  74540. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74541. };
  74542. // Create luminance
  74543. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74544. var _this = this;
  74545. // Create luminance
  74546. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74547. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74548. var offsets = [];
  74549. this.luminancePostProcess.onApply = function (effect) {
  74550. var sU = (1.0 / _this.luminancePostProcess.width);
  74551. var sV = (1.0 / _this.luminancePostProcess.height);
  74552. offsets[0] = -0.5 * sU;
  74553. offsets[1] = 0.5 * sV;
  74554. offsets[2] = 0.5 * sU;
  74555. offsets[3] = 0.5 * sV;
  74556. offsets[4] = -0.5 * sU;
  74557. offsets[5] = -0.5 * sV;
  74558. offsets[6] = 0.5 * sU;
  74559. offsets[7] = -0.5 * sV;
  74560. effect.setArray2("lumOffsets", offsets);
  74561. };
  74562. // Add to pipeline
  74563. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74564. // Create down sample luminance
  74565. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74566. var size = Math.pow(3, i);
  74567. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74568. if (i === 0) {
  74569. defines += "#define FINAL_DOWN_SAMPLER";
  74570. }
  74571. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74572. this.luminanceDownSamplePostProcesses.push(postProcess);
  74573. }
  74574. // Create callbacks and add effects
  74575. var lastLuminance = this.luminancePostProcess;
  74576. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74577. var downSampleOffsets = new Array(18);
  74578. pp.onApply = function (effect) {
  74579. if (!lastLuminance) {
  74580. return;
  74581. }
  74582. var id = 0;
  74583. for (var x = -1; x < 2; x++) {
  74584. for (var y = -1; y < 2; y++) {
  74585. downSampleOffsets[id] = x / lastLuminance.width;
  74586. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74587. id += 2;
  74588. }
  74589. }
  74590. effect.setArray2("dsOffsets", downSampleOffsets);
  74591. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74592. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74593. lastLuminance = _this.luminancePostProcess;
  74594. }
  74595. else {
  74596. lastLuminance = pp;
  74597. }
  74598. };
  74599. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74600. pp.onAfterRender = function (effect) {
  74601. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74602. 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);
  74603. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74604. };
  74605. }
  74606. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74607. });
  74608. };
  74609. // Create HDR post-process
  74610. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74611. var _this = this;
  74612. 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);
  74613. var outputLiminance = 1;
  74614. var time = 0;
  74615. var lastTime = 0;
  74616. this.hdrPostProcess.onApply = function (effect) {
  74617. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74618. time += scene.getEngine().getDeltaTime();
  74619. if (outputLiminance < 0) {
  74620. outputLiminance = _this._hdrCurrentLuminance;
  74621. }
  74622. else {
  74623. var dt = (lastTime - time) / 1000.0;
  74624. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74625. outputLiminance += _this.hdrDecreaseRate * dt;
  74626. }
  74627. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74628. outputLiminance -= _this.hdrIncreaseRate * dt;
  74629. }
  74630. else {
  74631. outputLiminance = _this._hdrCurrentLuminance;
  74632. }
  74633. }
  74634. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74635. effect.setFloat("averageLuminance", outputLiminance);
  74636. lastTime = time;
  74637. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74638. };
  74639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74640. };
  74641. // Create lens flare post-process
  74642. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74643. var _this = this;
  74644. 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);
  74645. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74646. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74647. 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);
  74648. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74649. var resolution = new BABYLON.Vector2(0, 0);
  74650. // Lens flare
  74651. this.lensFlarePostProcess.onApply = function (effect) {
  74652. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74653. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74654. effect.setFloat("strength", _this.lensFlareStrength);
  74655. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74656. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74657. // Shift
  74658. resolution.x = _this.lensFlarePostProcess.width;
  74659. resolution.y = _this.lensFlarePostProcess.height;
  74660. effect.setVector2("resolution", resolution);
  74661. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74662. };
  74663. // Compose
  74664. 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);
  74665. 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);
  74666. this.lensFlareComposePostProcess.onApply = function (effect) {
  74667. if (!_this._scene.activeCamera) {
  74668. return;
  74669. }
  74670. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74671. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74672. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74673. // Lens start rotation matrix
  74674. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74675. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74676. 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));
  74677. camRot *= 4.0;
  74678. 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);
  74679. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74680. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74681. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74682. };
  74683. };
  74684. // Create depth-of-field post-process
  74685. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74686. var _this = this;
  74687. 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);
  74688. this.depthOfFieldPostProcess.onApply = function (effect) {
  74689. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74690. effect.setTexture("depthSampler", _this._getDepthTexture());
  74691. effect.setFloat("distance", _this.depthOfFieldDistance);
  74692. };
  74693. // Add to pipeline
  74694. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74695. };
  74696. // Create motion blur post-process
  74697. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74698. var _this = this;
  74699. 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);
  74700. var motionScale = 0;
  74701. var prevViewProjection = BABYLON.Matrix.Identity();
  74702. var invViewProjection = BABYLON.Matrix.Identity();
  74703. var viewProjection = BABYLON.Matrix.Identity();
  74704. var screenSize = BABYLON.Vector2.Zero();
  74705. this.motionBlurPostProcess.onApply = function (effect) {
  74706. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74707. viewProjection.invertToRef(invViewProjection);
  74708. effect.setMatrix("inverseViewProjection", invViewProjection);
  74709. effect.setMatrix("prevViewProjection", prevViewProjection);
  74710. prevViewProjection = viewProjection;
  74711. screenSize.x = _this.motionBlurPostProcess.width;
  74712. screenSize.y = _this.motionBlurPostProcess.height;
  74713. effect.setVector2("screenSize", screenSize);
  74714. motionScale = scene.getEngine().getFps() / 60.0;
  74715. effect.setFloat("motionScale", motionScale);
  74716. effect.setFloat("motionStrength", _this.motionStrength);
  74717. effect.setTexture("depthSampler", _this._getDepthTexture());
  74718. };
  74719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74720. };
  74721. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74722. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74723. var renderer = this._scene.enableGeometryBufferRenderer();
  74724. return renderer.getGBuffer().textures[0];
  74725. }
  74726. return this._scene.enableDepthRenderer().getDepthMap();
  74727. };
  74728. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74729. for (var i = 0; i < this._cameras.length; i++) {
  74730. var camera = this._cameras[i];
  74731. if (this.originalPostProcess) {
  74732. this.originalPostProcess.dispose(camera);
  74733. }
  74734. if (this.downSampleX4PostProcess) {
  74735. this.downSampleX4PostProcess.dispose(camera);
  74736. }
  74737. if (this.brightPassPostProcess) {
  74738. this.brightPassPostProcess.dispose(camera);
  74739. }
  74740. if (this.textureAdderPostProcess) {
  74741. this.textureAdderPostProcess.dispose(camera);
  74742. }
  74743. if (this.textureAdderFinalPostProcess) {
  74744. this.textureAdderFinalPostProcess.dispose(camera);
  74745. }
  74746. if (this.volumetricLightPostProcess) {
  74747. this.volumetricLightPostProcess.dispose(camera);
  74748. }
  74749. if (this.volumetricLightSmoothXPostProcess) {
  74750. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74751. }
  74752. if (this.volumetricLightSmoothYPostProcess) {
  74753. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74754. }
  74755. if (this.volumetricLightMergePostProces) {
  74756. this.volumetricLightMergePostProces.dispose(camera);
  74757. }
  74758. if (this.volumetricLightFinalPostProcess) {
  74759. this.volumetricLightFinalPostProcess.dispose(camera);
  74760. }
  74761. if (this.lensFlarePostProcess) {
  74762. this.lensFlarePostProcess.dispose(camera);
  74763. }
  74764. if (this.lensFlareComposePostProcess) {
  74765. this.lensFlareComposePostProcess.dispose(camera);
  74766. }
  74767. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74768. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74769. }
  74770. if (this.luminancePostProcess) {
  74771. this.luminancePostProcess.dispose(camera);
  74772. }
  74773. if (this.hdrPostProcess) {
  74774. this.hdrPostProcess.dispose(camera);
  74775. }
  74776. if (this.hdrFinalPostProcess) {
  74777. this.hdrFinalPostProcess.dispose(camera);
  74778. }
  74779. if (this.depthOfFieldPostProcess) {
  74780. this.depthOfFieldPostProcess.dispose(camera);
  74781. }
  74782. if (this.motionBlurPostProcess) {
  74783. this.motionBlurPostProcess.dispose(camera);
  74784. }
  74785. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74786. this.blurHPostProcesses[j].dispose(camera);
  74787. }
  74788. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74789. this.blurVPostProcesses[j].dispose(camera);
  74790. }
  74791. }
  74792. this.originalPostProcess = null;
  74793. this.downSampleX4PostProcess = null;
  74794. this.brightPassPostProcess = null;
  74795. this.textureAdderPostProcess = null;
  74796. this.textureAdderFinalPostProcess = null;
  74797. this.volumetricLightPostProcess = null;
  74798. this.volumetricLightSmoothXPostProcess = null;
  74799. this.volumetricLightSmoothYPostProcess = null;
  74800. this.volumetricLightMergePostProces = null;
  74801. this.volumetricLightFinalPostProcess = null;
  74802. this.lensFlarePostProcess = null;
  74803. this.lensFlareComposePostProcess = null;
  74804. this.luminancePostProcess = null;
  74805. this.hdrPostProcess = null;
  74806. this.hdrFinalPostProcess = null;
  74807. this.depthOfFieldPostProcess = null;
  74808. this.motionBlurPostProcess = null;
  74809. this.luminanceDownSamplePostProcesses = [];
  74810. this.blurHPostProcesses = [];
  74811. this.blurVPostProcesses = [];
  74812. };
  74813. /**
  74814. * Dispose of the pipeline and stop all post processes
  74815. */
  74816. StandardRenderingPipeline.prototype.dispose = function () {
  74817. this._disposePostProcesses();
  74818. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74819. _super.prototype.dispose.call(this);
  74820. };
  74821. /**
  74822. * Serialize the rendering pipeline (Used when exporting)
  74823. * @returns the serialized object
  74824. */
  74825. StandardRenderingPipeline.prototype.serialize = function () {
  74826. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74827. if (this.sourceLight) {
  74828. serializationObject.sourceLightId = this.sourceLight.id;
  74829. }
  74830. serializationObject.customType = "StandardRenderingPipeline";
  74831. return serializationObject;
  74832. };
  74833. /**
  74834. * Parse the serialized pipeline
  74835. * @param source Source pipeline.
  74836. * @param scene The scene to load the pipeline to.
  74837. * @param rootUrl The URL of the serialized pipeline.
  74838. * @returns An instantiated pipeline from the serialized object.
  74839. */
  74840. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74841. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74842. if (source.sourceLightId) {
  74843. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74844. }
  74845. return p;
  74846. };
  74847. // Luminance steps
  74848. StandardRenderingPipeline.LuminanceSteps = 6;
  74849. __decorate([
  74850. BABYLON.serialize()
  74851. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74852. __decorate([
  74853. BABYLON.serialize()
  74854. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74855. __decorate([
  74856. BABYLON.serialize()
  74857. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74858. __decorate([
  74859. BABYLON.serialize()
  74860. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74861. __decorate([
  74862. BABYLON.serializeAsTexture("lensTexture")
  74863. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74864. __decorate([
  74865. BABYLON.serialize()
  74866. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74867. __decorate([
  74868. BABYLON.serialize()
  74869. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74870. __decorate([
  74871. BABYLON.serialize()
  74872. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74873. __decorate([
  74874. BABYLON.serialize()
  74875. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74876. __decorate([
  74877. BABYLON.serialize()
  74878. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74879. __decorate([
  74880. BABYLON.serialize()
  74881. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74882. __decorate([
  74883. BABYLON.serializeAsTexture("lensColorTexture")
  74884. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74885. __decorate([
  74886. BABYLON.serialize()
  74887. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74888. __decorate([
  74889. BABYLON.serialize()
  74890. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74891. __decorate([
  74892. BABYLON.serialize()
  74893. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74894. __decorate([
  74895. BABYLON.serialize()
  74896. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74897. __decorate([
  74898. BABYLON.serializeAsTexture("lensStarTexture")
  74899. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74900. __decorate([
  74901. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74902. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74903. __decorate([
  74904. BABYLON.serialize()
  74905. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74906. __decorate([
  74907. BABYLON.serialize()
  74908. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74909. __decorate([
  74910. BABYLON.serialize()
  74911. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74912. __decorate([
  74913. BABYLON.serialize()
  74914. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74915. __decorate([
  74916. BABYLON.serialize()
  74917. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74918. __decorate([
  74919. BABYLON.serialize()
  74920. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74921. __decorate([
  74922. BABYLON.serialize()
  74923. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74924. __decorate([
  74925. BABYLON.serialize()
  74926. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74927. __decorate([
  74928. BABYLON.serialize()
  74929. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74930. __decorate([
  74931. BABYLON.serialize()
  74932. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74933. __decorate([
  74934. BABYLON.serialize()
  74935. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74936. __decorate([
  74937. BABYLON.serialize()
  74938. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74939. return StandardRenderingPipeline;
  74940. }(BABYLON.PostProcessRenderPipeline));
  74941. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74942. })(BABYLON || (BABYLON = {}));
  74943. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74944. var BABYLON;
  74945. (function (BABYLON) {
  74946. var FxaaPostProcess = /** @class */ (function (_super) {
  74947. __extends(FxaaPostProcess, _super);
  74948. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74949. if (camera === void 0) { camera = null; }
  74950. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74951. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74952. var defines = _this._getDefines();
  74953. _this.updateEffect(defines);
  74954. _this.onApplyObservable.add(function (effect) {
  74955. var texelSize = _this.texelSize;
  74956. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74957. });
  74958. return _this;
  74959. }
  74960. FxaaPostProcess.prototype._getDefines = function () {
  74961. var engine = this.getEngine();
  74962. if (!engine) {
  74963. return null;
  74964. }
  74965. var glInfo = engine.getGlInfo();
  74966. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74967. return "#define MALI 1\n";
  74968. }
  74969. return null;
  74970. };
  74971. return FxaaPostProcess;
  74972. }(BABYLON.PostProcess));
  74973. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74974. })(BABYLON || (BABYLON = {}));
  74975. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74976. var BABYLON;
  74977. (function (BABYLON) {
  74978. /**
  74979. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74980. */
  74981. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74982. __extends(ChromaticAberrationPostProcess, _super);
  74983. /**
  74984. * Creates a new instance ChromaticAberrationPostProcess
  74985. * @param name The name of the effect.
  74986. * @param screenWidth The width of the screen to apply the effect on.
  74987. * @param screenHeight The height of the screen to apply the effect on.
  74988. * @param options The required width/height ratio to downsize to before computing the render pass.
  74989. * @param camera The camera to apply the render pass to.
  74990. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74991. * @param engine The engine which the post process will be applied. (default: current engine)
  74992. * @param reusable If the post process can be reused on the same frame. (default: false)
  74993. * @param textureType Type of textures used when performing the post process. (default: 0)
  74994. * @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)
  74995. */
  74996. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74997. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74998. if (blockCompilation === void 0) { blockCompilation = false; }
  74999. 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;
  75000. /**
  75001. * The amount of seperation of rgb channels (default: 30)
  75002. */
  75003. _this.aberrationAmount = 30;
  75004. /**
  75005. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75006. */
  75007. _this.radialIntensity = 0;
  75008. /**
  75009. * 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))
  75010. */
  75011. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75012. /**
  75013. * 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))
  75014. */
  75015. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75016. _this.onApplyObservable.add(function (effect) {
  75017. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75018. effect.setFloat('screen_width', screenWidth);
  75019. effect.setFloat('screen_height', screenHeight);
  75020. effect.setFloat('radialIntensity', _this.radialIntensity);
  75021. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75022. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75023. });
  75024. return _this;
  75025. }
  75026. return ChromaticAberrationPostProcess;
  75027. }(BABYLON.PostProcess));
  75028. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75029. })(BABYLON || (BABYLON = {}));
  75030. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75031. var BABYLON;
  75032. (function (BABYLON) {
  75033. /**
  75034. * The GrainPostProcess adds noise to the image at mid luminance levels
  75035. */
  75036. var GrainPostProcess = /** @class */ (function (_super) {
  75037. __extends(GrainPostProcess, _super);
  75038. /**
  75039. * Creates a new instance of @see GrainPostProcess
  75040. * @param name The name of the effect.
  75041. * @param options The required width/height ratio to downsize to before computing the render pass.
  75042. * @param camera The camera to apply the render pass to.
  75043. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75044. * @param engine The engine which the post process will be applied. (default: current engine)
  75045. * @param reusable If the post process can be reused on the same frame. (default: false)
  75046. * @param textureType Type of textures used when performing the post process. (default: 0)
  75047. * @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)
  75048. */
  75049. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75050. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75051. if (blockCompilation === void 0) { blockCompilation = false; }
  75052. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75053. /**
  75054. * The intensity of the grain added (default: 30)
  75055. */
  75056. _this.intensity = 30;
  75057. /**
  75058. * If the grain should be randomized on every frame
  75059. */
  75060. _this.animated = false;
  75061. _this.onApplyObservable.add(function (effect) {
  75062. effect.setFloat('intensity', _this.intensity);
  75063. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75064. });
  75065. return _this;
  75066. }
  75067. return GrainPostProcess;
  75068. }(BABYLON.PostProcess));
  75069. BABYLON.GrainPostProcess = GrainPostProcess;
  75070. })(BABYLON || (BABYLON = {}));
  75071. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75072. var BABYLON;
  75073. (function (BABYLON) {
  75074. /**
  75075. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75076. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75077. */
  75078. var SharpenPostProcess = /** @class */ (function (_super) {
  75079. __extends(SharpenPostProcess, _super);
  75080. /**
  75081. * Creates a new instance ConvolutionPostProcess
  75082. * @param name The name of the effect.
  75083. * @param options The required width/height ratio to downsize to before computing the render pass.
  75084. * @param camera The camera to apply the render pass to.
  75085. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75086. * @param engine The engine which the post process will be applied. (default: current engine)
  75087. * @param reusable If the post process can be reused on the same frame. (default: false)
  75088. * @param textureType Type of textures used when performing the post process. (default: 0)
  75089. * @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)
  75090. */
  75091. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75092. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75093. if (blockCompilation === void 0) { blockCompilation = false; }
  75094. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75095. /**
  75096. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75097. */
  75098. _this.colorAmount = 1.0;
  75099. /**
  75100. * How much sharpness should be applied (default: 0.3)
  75101. */
  75102. _this.edgeAmount = 0.3;
  75103. _this.onApply = function (effect) {
  75104. effect.setFloat2("screenSize", _this.width, _this.height);
  75105. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75106. };
  75107. return _this;
  75108. }
  75109. return SharpenPostProcess;
  75110. }(BABYLON.PostProcess));
  75111. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75112. })(BABYLON || (BABYLON = {}));
  75113. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75114. var BABYLON;
  75115. (function (BABYLON) {
  75116. /**
  75117. * The Blur Post Process which blurs an image based on a kernel and direction.
  75118. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75119. */
  75120. var BlurPostProcess = /** @class */ (function (_super) {
  75121. __extends(BlurPostProcess, _super);
  75122. /**
  75123. * Creates a new instance BlurPostProcess
  75124. * @param name The name of the effect.
  75125. * @param direction The direction in which to blur the image.
  75126. * @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.
  75127. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75128. * @param camera The camera to apply the render pass to.
  75129. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75130. * @param engine The engine which the post process will be applied. (default: current engine)
  75131. * @param reusable If the post process can be reused on the same frame. (default: false)
  75132. * @param textureType Type of textures used when performing the post process. (default: 0)
  75133. * @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)
  75134. */
  75135. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75136. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75137. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75138. if (defines === void 0) { defines = ""; }
  75139. if (blockCompilation === void 0) { blockCompilation = false; }
  75140. 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;
  75141. _this.direction = direction;
  75142. _this.blockCompilation = blockCompilation;
  75143. _this._packedFloat = false;
  75144. _this._staticDefines = "";
  75145. _this._staticDefines = defines;
  75146. _this.onApplyObservable.add(function (effect) {
  75147. if (_this._outputTexture) {
  75148. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75149. }
  75150. else {
  75151. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75152. }
  75153. });
  75154. _this.kernel = kernel;
  75155. return _this;
  75156. }
  75157. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75158. /**
  75159. * Gets the length in pixels of the blur sample region
  75160. */
  75161. get: function () {
  75162. return this._idealKernel;
  75163. },
  75164. /**
  75165. * Sets the length in pixels of the blur sample region
  75166. */
  75167. set: function (v) {
  75168. if (this._idealKernel === v) {
  75169. return;
  75170. }
  75171. v = Math.max(v, 1);
  75172. this._idealKernel = v;
  75173. this._kernel = this._nearestBestKernel(v);
  75174. if (!this.blockCompilation) {
  75175. this._updateParameters();
  75176. }
  75177. },
  75178. enumerable: true,
  75179. configurable: true
  75180. });
  75181. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75182. /**
  75183. * Gets wether or not the blur is unpacking/repacking floats
  75184. */
  75185. get: function () {
  75186. return this._packedFloat;
  75187. },
  75188. /**
  75189. * Sets wether or not the blur needs to unpack/repack floats
  75190. */
  75191. set: function (v) {
  75192. if (this._packedFloat === v) {
  75193. return;
  75194. }
  75195. this._packedFloat = v;
  75196. if (!this.blockCompilation) {
  75197. this._updateParameters();
  75198. }
  75199. },
  75200. enumerable: true,
  75201. configurable: true
  75202. });
  75203. /**
  75204. * Updates the effect with the current post process compile time values and recompiles the shader.
  75205. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75206. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75207. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75208. * @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
  75209. * @param onCompiled Called when the shader has been compiled.
  75210. * @param onError Called if there is an error when compiling a shader.
  75211. */
  75212. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75213. if (defines === void 0) { defines = null; }
  75214. if (uniforms === void 0) { uniforms = null; }
  75215. if (samplers === void 0) { samplers = null; }
  75216. this._updateParameters(onCompiled, onError);
  75217. };
  75218. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75219. // Generate sampling offsets and weights
  75220. var N = this._kernel;
  75221. var centerIndex = (N - 1) / 2;
  75222. // Generate Gaussian sampling weights over kernel
  75223. var offsets = [];
  75224. var weights = [];
  75225. var totalWeight = 0;
  75226. for (var i = 0; i < N; i++) {
  75227. var u = i / (N - 1);
  75228. var w = this._gaussianWeight(u * 2.0 - 1);
  75229. offsets[i] = (i - centerIndex);
  75230. weights[i] = w;
  75231. totalWeight += w;
  75232. }
  75233. // Normalize weights
  75234. for (var i = 0; i < weights.length; i++) {
  75235. weights[i] /= totalWeight;
  75236. }
  75237. // Optimize: combine samples to take advantage of hardware linear sampling
  75238. // Walk from left to center, combining pairs (symmetrically)
  75239. var linearSamplingWeights = [];
  75240. var linearSamplingOffsets = [];
  75241. var linearSamplingMap = [];
  75242. for (var i = 0; i <= centerIndex; i += 2) {
  75243. var j = Math.min(i + 1, Math.floor(centerIndex));
  75244. var singleCenterSample = i === j;
  75245. if (singleCenterSample) {
  75246. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75247. }
  75248. else {
  75249. var sharedCell = j === centerIndex;
  75250. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75251. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75252. if (offsetLinear === 0) {
  75253. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75254. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75255. }
  75256. else {
  75257. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75258. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75259. }
  75260. }
  75261. }
  75262. for (var i = 0; i < linearSamplingMap.length; i++) {
  75263. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75264. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75265. }
  75266. // Replace with optimized
  75267. offsets = linearSamplingOffsets;
  75268. weights = linearSamplingWeights;
  75269. // Generate shaders
  75270. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75271. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75272. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75273. var defines = "";
  75274. defines += this._staticDefines;
  75275. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75276. if (this._staticDefines.indexOf("DOF") != -1) {
  75277. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75278. varyingCount--;
  75279. }
  75280. for (var i = 0; i < varyingCount; i++) {
  75281. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75282. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75283. }
  75284. var depCount = 0;
  75285. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75286. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75287. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75288. depCount++;
  75289. }
  75290. if (this.packedFloat) {
  75291. defines += "#define PACKEDFLOAT 1";
  75292. }
  75293. this.blockCompilation = false;
  75294. _super.prototype.updateEffect.call(this, defines, null, null, {
  75295. varyingCount: varyingCount,
  75296. depCount: depCount
  75297. }, onCompiled, onError);
  75298. };
  75299. /**
  75300. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75301. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75302. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75303. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75304. * The gaps between physical kernels are compensated for in the weighting of the samples
  75305. * @param idealKernel Ideal blur kernel.
  75306. * @return Nearest best kernel.
  75307. */
  75308. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75309. var v = Math.round(idealKernel);
  75310. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75311. var k = _a[_i];
  75312. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75313. return Math.max(k, 3);
  75314. }
  75315. }
  75316. return Math.max(v, 3);
  75317. };
  75318. /**
  75319. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75320. * @param x The point on the Gaussian distribution to sample.
  75321. * @return the value of the Gaussian function at x.
  75322. */
  75323. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75324. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75325. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75326. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75327. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75328. // truncated at around 1.3% of peak strength.
  75329. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75330. var sigma = (1 / 3);
  75331. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75332. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75333. var weight = (1.0 / denominator) * Math.exp(exponent);
  75334. return weight;
  75335. };
  75336. /**
  75337. * Generates a string that can be used as a floating point number in GLSL.
  75338. * @param x Value to print.
  75339. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75340. * @return GLSL float string.
  75341. */
  75342. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75343. if (decimalFigures === void 0) { decimalFigures = 8; }
  75344. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75345. };
  75346. return BlurPostProcess;
  75347. }(BABYLON.PostProcess));
  75348. BABYLON.BlurPostProcess = BlurPostProcess;
  75349. })(BABYLON || (BABYLON = {}));
  75350. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75351. var BABYLON;
  75352. (function (BABYLON) {
  75353. /**
  75354. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75355. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75356. * based on samples that have a large difference in distance than the center pixel.
  75357. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75358. */
  75359. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75360. __extends(DepthOfFieldBlurPostProcess, _super);
  75361. /**
  75362. * Creates a new instance CircleOfConfusionPostProcess
  75363. * @param name The name of the effect.
  75364. * @param scene The scene the effect belongs to.
  75365. * @param direction The direction the blur should be applied.
  75366. * @param kernel The size of the kernel used to blur.
  75367. * @param options The required width/height ratio to downsize to before computing the render pass.
  75368. * @param camera The camera to apply the render pass to.
  75369. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75370. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75371. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75372. * @param engine The engine which the post process will be applied. (default: current engine)
  75373. * @param reusable If the post process can be reused on the same frame. (default: false)
  75374. * @param textureType Type of textures used when performing the post process. (default: 0)
  75375. * @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)
  75376. */
  75377. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75378. if (imageToBlur === void 0) { imageToBlur = null; }
  75379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75380. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75381. if (blockCompilation === void 0) { blockCompilation = false; }
  75382. 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;
  75383. _this.direction = direction;
  75384. _this.onApplyObservable.add(function (effect) {
  75385. if (imageToBlur != null) {
  75386. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75387. }
  75388. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75389. if (scene.activeCamera) {
  75390. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75391. }
  75392. });
  75393. return _this;
  75394. }
  75395. return DepthOfFieldBlurPostProcess;
  75396. }(BABYLON.BlurPostProcess));
  75397. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75398. })(BABYLON || (BABYLON = {}));
  75399. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75400. var BABYLON;
  75401. (function (BABYLON) {
  75402. /**
  75403. * Options to be set when merging outputs from the default pipeline.
  75404. */
  75405. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75406. function DepthOfFieldMergePostProcessOptions() {
  75407. }
  75408. return DepthOfFieldMergePostProcessOptions;
  75409. }());
  75410. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75411. /**
  75412. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75413. */
  75414. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75415. __extends(DepthOfFieldMergePostProcess, _super);
  75416. /**
  75417. * Creates a new instance of DepthOfFieldMergePostProcess
  75418. * @param name The name of the effect.
  75419. * @param originalFromInput Post process which's input will be used for the merge.
  75420. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75421. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75422. * @param options The required width/height ratio to downsize to before computing the render pass.
  75423. * @param camera The camera to apply the render pass to.
  75424. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75425. * @param engine The engine which the post process will be applied. (default: current engine)
  75426. * @param reusable If the post process can be reused on the same frame. (default: false)
  75427. * @param textureType Type of textures used when performing the post process. (default: 0)
  75428. * @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)
  75429. */
  75430. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75431. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75432. if (blockCompilation === void 0) { blockCompilation = false; }
  75433. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75434. _this.blurSteps = blurSteps;
  75435. _this.onApplyObservable.add(function (effect) {
  75436. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75437. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75438. blurSteps.forEach(function (step, index) {
  75439. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75440. });
  75441. });
  75442. if (!blockCompilation) {
  75443. _this.updateEffect();
  75444. }
  75445. return _this;
  75446. }
  75447. /**
  75448. * Updates the effect with the current post process compile time values and recompiles the shader.
  75449. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75450. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75451. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75452. * @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
  75453. * @param onCompiled Called when the shader has been compiled.
  75454. * @param onError Called if there is an error when compiling a shader.
  75455. */
  75456. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75457. if (defines === void 0) { defines = null; }
  75458. if (uniforms === void 0) { uniforms = null; }
  75459. if (samplers === void 0) { samplers = null; }
  75460. if (!defines) {
  75461. defines = "";
  75462. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75463. }
  75464. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75465. };
  75466. return DepthOfFieldMergePostProcess;
  75467. }(BABYLON.PostProcess));
  75468. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75469. })(BABYLON || (BABYLON = {}));
  75470. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75471. var BABYLON;
  75472. (function (BABYLON) {
  75473. /**
  75474. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75475. */
  75476. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75477. __extends(CircleOfConfusionPostProcess, _super);
  75478. /**
  75479. * Creates a new instance CircleOfConfusionPostProcess
  75480. * @param name The name of the effect.
  75481. * @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.
  75482. * @param options The required width/height ratio to downsize to before computing the render pass.
  75483. * @param camera The camera to apply the render pass to.
  75484. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75485. * @param engine The engine which the post process will be applied. (default: current engine)
  75486. * @param reusable If the post process can be reused on the same frame. (default: false)
  75487. * @param textureType Type of textures used when performing the post process. (default: 0)
  75488. * @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)
  75489. */
  75490. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75491. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75492. if (blockCompilation === void 0) { blockCompilation = false; }
  75493. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75494. /**
  75495. * 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.
  75496. */
  75497. _this.lensSize = 50;
  75498. /**
  75499. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75500. */
  75501. _this.fStop = 1.4;
  75502. /**
  75503. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75504. */
  75505. _this.focusDistance = 2000;
  75506. /**
  75507. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75508. */
  75509. _this.focalLength = 50;
  75510. _this._depthTexture = null;
  75511. _this._depthTexture = depthTexture;
  75512. _this.onApplyObservable.add(function (effect) {
  75513. if (!_this._depthTexture) {
  75514. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75515. return;
  75516. }
  75517. effect.setTexture("depthSampler", _this._depthTexture);
  75518. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75519. var aperture = _this.lensSize / _this.fStop;
  75520. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75521. effect.setFloat('focusDistance', _this.focusDistance);
  75522. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75523. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75524. });
  75525. return _this;
  75526. }
  75527. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75528. /**
  75529. * 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.
  75530. */
  75531. set: function (value) {
  75532. this._depthTexture = value;
  75533. },
  75534. enumerable: true,
  75535. configurable: true
  75536. });
  75537. return CircleOfConfusionPostProcess;
  75538. }(BABYLON.PostProcess));
  75539. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75540. })(BABYLON || (BABYLON = {}));
  75541. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75542. var BABYLON;
  75543. (function (BABYLON) {
  75544. /**
  75545. * Specifies the level of max blur that should be applied when using the depth of field effect
  75546. */
  75547. var DepthOfFieldEffectBlurLevel;
  75548. (function (DepthOfFieldEffectBlurLevel) {
  75549. /**
  75550. * Subtle blur
  75551. */
  75552. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75553. /**
  75554. * Medium blur
  75555. */
  75556. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75557. /**
  75558. * Large blur
  75559. */
  75560. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75561. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75562. ;
  75563. /**
  75564. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75565. */
  75566. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75567. __extends(DepthOfFieldEffect, _super);
  75568. /**
  75569. * Creates a new instance DepthOfFieldEffect
  75570. * @param scene The scene the effect belongs to.
  75571. * @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.
  75572. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75573. * @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)
  75574. */
  75575. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75576. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75577. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75578. if (blockCompilation === void 0) { blockCompilation = false; }
  75579. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75580. return _this._effects;
  75581. }, true) || this;
  75582. /**
  75583. * Internal post processes in depth of field effect
  75584. */
  75585. _this._effects = [];
  75586. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75587. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75588. // 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)
  75589. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75590. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75591. _this._depthOfFieldBlurY = [];
  75592. _this._depthOfFieldBlurX = [];
  75593. var blurCount = 1;
  75594. var kernelSize = 15;
  75595. switch (blurLevel) {
  75596. case DepthOfFieldEffectBlurLevel.High: {
  75597. blurCount = 3;
  75598. kernelSize = 51;
  75599. break;
  75600. }
  75601. case DepthOfFieldEffectBlurLevel.Medium: {
  75602. blurCount = 2;
  75603. kernelSize = 31;
  75604. break;
  75605. }
  75606. default: {
  75607. kernelSize = 15;
  75608. blurCount = 1;
  75609. break;
  75610. }
  75611. }
  75612. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75613. var ratio = 1.0;
  75614. for (var i = 0; i < blurCount; i++) {
  75615. 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);
  75616. blurY.autoClear = false;
  75617. ratio = 0.75 / Math.pow(2, i);
  75618. 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);
  75619. blurX.autoClear = false;
  75620. _this._depthOfFieldBlurY.push(blurY);
  75621. _this._depthOfFieldBlurX.push(blurX);
  75622. }
  75623. // Set all post processes on the effect.
  75624. _this._effects = [_this._circleOfConfusion];
  75625. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75626. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75627. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75628. }
  75629. // Merge blurred images with original image based on circleOfConfusion
  75630. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75631. _this._dofMerge.autoClear = false;
  75632. _this._effects.push(_this._dofMerge);
  75633. return _this;
  75634. }
  75635. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75636. get: function () {
  75637. return this._circleOfConfusion.focalLength;
  75638. },
  75639. /**
  75640. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75641. */
  75642. set: function (value) {
  75643. this._circleOfConfusion.focalLength = value;
  75644. },
  75645. enumerable: true,
  75646. configurable: true
  75647. });
  75648. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75649. get: function () {
  75650. return this._circleOfConfusion.fStop;
  75651. },
  75652. /**
  75653. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75654. */
  75655. set: function (value) {
  75656. this._circleOfConfusion.fStop = value;
  75657. },
  75658. enumerable: true,
  75659. configurable: true
  75660. });
  75661. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75662. get: function () {
  75663. return this._circleOfConfusion.focusDistance;
  75664. },
  75665. /**
  75666. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75667. */
  75668. set: function (value) {
  75669. this._circleOfConfusion.focusDistance = value;
  75670. },
  75671. enumerable: true,
  75672. configurable: true
  75673. });
  75674. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75675. get: function () {
  75676. return this._circleOfConfusion.lensSize;
  75677. },
  75678. /**
  75679. * 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.
  75680. */
  75681. set: function (value) {
  75682. this._circleOfConfusion.lensSize = value;
  75683. },
  75684. enumerable: true,
  75685. configurable: true
  75686. });
  75687. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75688. /**
  75689. * 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.
  75690. */
  75691. set: function (value) {
  75692. this._circleOfConfusion.depthTexture = value;
  75693. },
  75694. enumerable: true,
  75695. configurable: true
  75696. });
  75697. /**
  75698. * Disposes each of the internal effects for a given camera.
  75699. * @param camera The camera to dispose the effect on.
  75700. */
  75701. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75702. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75703. this._effects[effectIndex].dispose(camera);
  75704. }
  75705. };
  75706. /**
  75707. * Internal
  75708. */
  75709. DepthOfFieldEffect.prototype._updateEffects = function () {
  75710. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75711. this._effects[effectIndex].updateEffect();
  75712. }
  75713. };
  75714. /**
  75715. * Internal
  75716. * @returns if all the contained post processes are ready.
  75717. */
  75718. DepthOfFieldEffect.prototype._isReady = function () {
  75719. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75720. if (!this._effects[effectIndex].isReady()) {
  75721. return false;
  75722. }
  75723. }
  75724. return true;
  75725. };
  75726. return DepthOfFieldEffect;
  75727. }(BABYLON.PostProcessRenderEffect));
  75728. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75729. })(BABYLON || (BABYLON = {}));
  75730. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75731. var BABYLON;
  75732. (function (BABYLON) {
  75733. /**
  75734. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75735. */
  75736. var BloomMergePostProcess = /** @class */ (function (_super) {
  75737. __extends(BloomMergePostProcess, _super);
  75738. /**
  75739. * Creates a new instance of @see BloomMergePostProcess
  75740. * @param name The name of the effect.
  75741. * @param originalFromInput Post process which's input will be used for the merge.
  75742. * @param blurred Blurred highlights post process which's output will be used.
  75743. * @param weight Weight of the bloom to be added to the original input.
  75744. * @param options The required width/height ratio to downsize to before computing the render pass.
  75745. * @param camera The camera to apply the render pass to.
  75746. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75747. * @param engine The engine which the post process will be applied. (default: current engine)
  75748. * @param reusable If the post process can be reused on the same frame. (default: false)
  75749. * @param textureType Type of textures used when performing the post process. (default: 0)
  75750. * @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)
  75751. */
  75752. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75753. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75754. if (blockCompilation === void 0) { blockCompilation = false; }
  75755. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75756. _this.weight = weight;
  75757. _this.onApplyObservable.add(function (effect) {
  75758. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75759. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75760. effect.setFloat("bloomWeight", _this.weight);
  75761. });
  75762. if (!blockCompilation) {
  75763. _this.updateEffect();
  75764. }
  75765. return _this;
  75766. }
  75767. return BloomMergePostProcess;
  75768. }(BABYLON.PostProcess));
  75769. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75770. })(BABYLON || (BABYLON = {}));
  75771. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75772. var BABYLON;
  75773. (function (BABYLON) {
  75774. /**
  75775. * 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.
  75776. */
  75777. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75778. __extends(ExtractHighlightsPostProcess, _super);
  75779. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75780. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75781. if (blockCompilation === void 0) { blockCompilation = false; }
  75782. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75783. /**
  75784. * The luminance threshold, pixels below this value will be set to black.
  75785. */
  75786. _this.threshold = 0.9;
  75787. /**
  75788. * Internal
  75789. */
  75790. _this._exposure = 1;
  75791. /**
  75792. * Post process which has the input texture to be used when performing highlight extraction
  75793. */
  75794. _this._inputPostProcess = null;
  75795. _this.onApplyObservable.add(function (effect) {
  75796. if (_this._inputPostProcess) {
  75797. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75798. }
  75799. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75800. effect.setFloat('exposure', _this._exposure);
  75801. });
  75802. return _this;
  75803. }
  75804. return ExtractHighlightsPostProcess;
  75805. }(BABYLON.PostProcess));
  75806. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75807. })(BABYLON || (BABYLON = {}));
  75808. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75809. var BABYLON;
  75810. (function (BABYLON) {
  75811. /**
  75812. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75813. */
  75814. var BloomEffect = /** @class */ (function (_super) {
  75815. __extends(BloomEffect, _super);
  75816. /**
  75817. * Creates a new instance of @see BloomEffect
  75818. * @param scene The scene the effect belongs to.
  75819. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75820. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75821. * @param bloomWeight The the strength of bloom.
  75822. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75823. * @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)
  75824. */
  75825. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75826. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75827. if (blockCompilation === void 0) { blockCompilation = false; }
  75828. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75829. return _this._effects;
  75830. }, true) || this;
  75831. _this.bloomScale = bloomScale;
  75832. /**
  75833. * Internal
  75834. */
  75835. _this._effects = [];
  75836. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75837. _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);
  75838. _this._blurX.alwaysForcePOT = true;
  75839. _this._blurX.autoClear = false;
  75840. _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);
  75841. _this._blurY.alwaysForcePOT = true;
  75842. _this._blurY.autoClear = false;
  75843. _this.kernel = bloomKernel;
  75844. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75845. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75846. _this._merge.autoClear = false;
  75847. _this._effects.push(_this._merge);
  75848. return _this;
  75849. }
  75850. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75851. /**
  75852. * The luminance threshold to find bright areas of the image to bloom.
  75853. */
  75854. get: function () {
  75855. return this._downscale.threshold;
  75856. },
  75857. set: function (value) {
  75858. this._downscale.threshold = value;
  75859. },
  75860. enumerable: true,
  75861. configurable: true
  75862. });
  75863. Object.defineProperty(BloomEffect.prototype, "weight", {
  75864. /**
  75865. * The strength of the bloom.
  75866. */
  75867. get: function () {
  75868. return this._merge.weight;
  75869. },
  75870. set: function (value) {
  75871. this._merge.weight = value;
  75872. },
  75873. enumerable: true,
  75874. configurable: true
  75875. });
  75876. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75877. /**
  75878. * Specifies the size of the bloom blur kernel, relative to the final output size
  75879. */
  75880. get: function () {
  75881. return this._blurX.kernel / this.bloomScale;
  75882. },
  75883. set: function (value) {
  75884. this._blurX.kernel = value * this.bloomScale;
  75885. this._blurY.kernel = value * this.bloomScale;
  75886. },
  75887. enumerable: true,
  75888. configurable: true
  75889. });
  75890. /**
  75891. * Disposes each of the internal effects for a given camera.
  75892. * @param camera The camera to dispose the effect on.
  75893. */
  75894. BloomEffect.prototype.disposeEffects = function (camera) {
  75895. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75896. this._effects[effectIndex].dispose(camera);
  75897. }
  75898. };
  75899. /**
  75900. * Internal
  75901. */
  75902. BloomEffect.prototype._updateEffects = function () {
  75903. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75904. this._effects[effectIndex].updateEffect();
  75905. }
  75906. };
  75907. /**
  75908. * Internal
  75909. * @returns if all the contained post processes are ready.
  75910. */
  75911. BloomEffect.prototype._isReady = function () {
  75912. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75913. if (!this._effects[effectIndex].isReady()) {
  75914. return false;
  75915. }
  75916. }
  75917. return true;
  75918. };
  75919. return BloomEffect;
  75920. }(BABYLON.PostProcessRenderEffect));
  75921. BABYLON.BloomEffect = BloomEffect;
  75922. })(BABYLON || (BABYLON = {}));
  75923. //# sourceMappingURL=babylon.bloomEffect.js.map
  75924. var BABYLON;
  75925. (function (BABYLON) {
  75926. /**
  75927. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75928. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75929. */
  75930. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75931. __extends(DefaultRenderingPipeline, _super);
  75932. /**
  75933. * @constructor
  75934. * @param {string} name - The rendering pipeline name (default: "")
  75935. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75936. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75937. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75938. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75939. */
  75940. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75941. if (name === void 0) { name = ""; }
  75942. if (hdr === void 0) { hdr = true; }
  75943. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75944. if (automaticBuild === void 0) { automaticBuild = true; }
  75945. var _this = _super.call(this, scene.getEngine(), name) || this;
  75946. _this._originalCameras = [];
  75947. /**
  75948. * ID of the sharpen post process,
  75949. */
  75950. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75951. /**
  75952. * ID of the image processing post process;
  75953. */
  75954. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75955. /**
  75956. * ID of the Fast Approximate Anti-Aliasing post process;
  75957. */
  75958. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75959. /**
  75960. * ID of the chromatic aberration post process,
  75961. */
  75962. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75963. /**
  75964. * ID of the grain post process
  75965. */
  75966. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75967. /**
  75968. * Glow post process which adds a glow to emmisive areas of the image
  75969. */
  75970. _this._glowLayer = null;
  75971. /**
  75972. * Animations which can be used to tweak settings over a period of time
  75973. */
  75974. _this.animations = [];
  75975. _this._imageProcessingConfigurationObserver = null;
  75976. // Values
  75977. _this._sharpenEnabled = false;
  75978. _this._bloomEnabled = false;
  75979. _this._depthOfFieldEnabled = false;
  75980. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75981. _this._fxaaEnabled = false;
  75982. _this._imageProcessingEnabled = true;
  75983. _this._bloomScale = 0.5;
  75984. _this._chromaticAberrationEnabled = false;
  75985. _this._grainEnabled = false;
  75986. _this._buildAllowed = true;
  75987. _this._resizeObserver = null;
  75988. _this._hardwareScaleLevel = 1.0;
  75989. _this._bloomKernel = 64;
  75990. /**
  75991. * Specifies the weight of the bloom in the final rendering
  75992. */
  75993. _this._bloomWeight = 0.15;
  75994. /**
  75995. * Specifies the luma threshold for the area that will be blurred by the bloom
  75996. */
  75997. _this._bloomThreshold = 0.9;
  75998. _this._samples = 1;
  75999. _this._hasCleared = false;
  76000. _this._prevPostProcess = null;
  76001. _this._prevPrevPostProcess = null;
  76002. _this._cameras = cameras || scene.cameras;
  76003. _this._originalCameras = _this._cameras.slice();
  76004. _this._buildAllowed = automaticBuild;
  76005. // Initialize
  76006. _this._scene = scene;
  76007. var caps = _this._scene.getEngine().getCaps();
  76008. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76009. // Misc
  76010. if (_this._hdr) {
  76011. if (caps.textureHalfFloatRender) {
  76012. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76013. }
  76014. else if (caps.textureFloatRender) {
  76015. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76016. }
  76017. }
  76018. else {
  76019. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76020. }
  76021. // Attach
  76022. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76023. var engine = _this._scene.getEngine();
  76024. // Create post processes before hand so they can be modified before enabled.
  76025. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76026. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76027. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76028. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76029. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76030. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76031. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76032. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76033. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76034. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76035. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76036. _this.bloomKernel = _this.bloomKernel;
  76037. });
  76038. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76039. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76040. });
  76041. _this._buildPipeline();
  76042. return _this;
  76043. }
  76044. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76045. get: function () {
  76046. return this._sharpenEnabled;
  76047. },
  76048. /**
  76049. * Enable or disable the sharpen process from the pipeline
  76050. */
  76051. set: function (enabled) {
  76052. if (this._sharpenEnabled === enabled) {
  76053. return;
  76054. }
  76055. this._sharpenEnabled = enabled;
  76056. this._buildPipeline();
  76057. },
  76058. enumerable: true,
  76059. configurable: true
  76060. });
  76061. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76062. /**
  76063. * Specifies the size of the bloom blur kernel, relative to the final output size
  76064. */
  76065. get: function () {
  76066. return this._bloomKernel;
  76067. },
  76068. set: function (value) {
  76069. this._bloomKernel = value;
  76070. this.bloom.kernel = value / this._hardwareScaleLevel;
  76071. },
  76072. enumerable: true,
  76073. configurable: true
  76074. });
  76075. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76076. get: function () {
  76077. return this._bloomWeight;
  76078. },
  76079. /**
  76080. * The strength of the bloom.
  76081. */
  76082. set: function (value) {
  76083. if (this._bloomWeight === value) {
  76084. return;
  76085. }
  76086. this.bloom.weight = value;
  76087. this._bloomWeight = value;
  76088. },
  76089. enumerable: true,
  76090. configurable: true
  76091. });
  76092. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76093. get: function () {
  76094. return this._bloomThreshold;
  76095. },
  76096. /**
  76097. * The strength of the bloom.
  76098. */
  76099. set: function (value) {
  76100. if (this._bloomThreshold === value) {
  76101. return;
  76102. }
  76103. this.bloom.threshold = value;
  76104. this._bloomThreshold = value;
  76105. },
  76106. enumerable: true,
  76107. configurable: true
  76108. });
  76109. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76110. get: function () {
  76111. return this._bloomScale;
  76112. },
  76113. /**
  76114. * The scale of the bloom, lower value will provide better performance.
  76115. */
  76116. set: function (value) {
  76117. if (this._bloomScale === value) {
  76118. return;
  76119. }
  76120. this._bloomScale = value;
  76121. // recreate bloom and dispose old as this setting is not dynamic
  76122. this._rebuildBloom();
  76123. this._buildPipeline();
  76124. },
  76125. enumerable: true,
  76126. configurable: true
  76127. });
  76128. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76129. get: function () {
  76130. return this._bloomEnabled;
  76131. },
  76132. /**
  76133. * Enable or disable the bloom from the pipeline
  76134. */
  76135. set: function (enabled) {
  76136. if (this._bloomEnabled === enabled) {
  76137. return;
  76138. }
  76139. this._bloomEnabled = enabled;
  76140. this._buildPipeline();
  76141. },
  76142. enumerable: true,
  76143. configurable: true
  76144. });
  76145. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76146. // recreate bloom and dispose old as this setting is not dynamic
  76147. var oldBloom = this.bloom;
  76148. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76149. this.bloom.threshold = oldBloom.threshold;
  76150. for (var i = 0; i < this._cameras.length; i++) {
  76151. oldBloom.disposeEffects(this._cameras[i]);
  76152. }
  76153. };
  76154. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76155. /**
  76156. * If the depth of field is enabled.
  76157. */
  76158. get: function () {
  76159. return this._depthOfFieldEnabled;
  76160. },
  76161. set: function (enabled) {
  76162. if (this._depthOfFieldEnabled === enabled) {
  76163. return;
  76164. }
  76165. this._depthOfFieldEnabled = enabled;
  76166. this._buildPipeline();
  76167. },
  76168. enumerable: true,
  76169. configurable: true
  76170. });
  76171. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76172. /**
  76173. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76174. */
  76175. get: function () {
  76176. return this._depthOfFieldBlurLevel;
  76177. },
  76178. set: function (value) {
  76179. if (this._depthOfFieldBlurLevel === value) {
  76180. return;
  76181. }
  76182. this._depthOfFieldBlurLevel = value;
  76183. // recreate dof and dispose old as this setting is not dynamic
  76184. var oldDof = this.depthOfField;
  76185. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76186. this.depthOfField.focalLength = oldDof.focalLength;
  76187. this.depthOfField.focusDistance = oldDof.focusDistance;
  76188. this.depthOfField.fStop = oldDof.fStop;
  76189. this.depthOfField.lensSize = oldDof.lensSize;
  76190. for (var i = 0; i < this._cameras.length; i++) {
  76191. oldDof.disposeEffects(this._cameras[i]);
  76192. }
  76193. this._buildPipeline();
  76194. },
  76195. enumerable: true,
  76196. configurable: true
  76197. });
  76198. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76199. get: function () {
  76200. return this._fxaaEnabled;
  76201. },
  76202. /**
  76203. * If the anti aliasing is enabled.
  76204. */
  76205. set: function (enabled) {
  76206. if (this._fxaaEnabled === enabled) {
  76207. return;
  76208. }
  76209. this._fxaaEnabled = enabled;
  76210. this._buildPipeline();
  76211. },
  76212. enumerable: true,
  76213. configurable: true
  76214. });
  76215. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76216. get: function () {
  76217. return this._samples;
  76218. },
  76219. /**
  76220. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76221. */
  76222. set: function (sampleCount) {
  76223. if (this._samples === sampleCount) {
  76224. return;
  76225. }
  76226. this._samples = sampleCount;
  76227. this._buildPipeline();
  76228. },
  76229. enumerable: true,
  76230. configurable: true
  76231. });
  76232. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76233. get: function () {
  76234. return this._imageProcessingEnabled;
  76235. },
  76236. /**
  76237. * If image processing is enabled.
  76238. */
  76239. set: function (enabled) {
  76240. if (this._imageProcessingEnabled === enabled) {
  76241. return;
  76242. }
  76243. this._imageProcessingEnabled = enabled;
  76244. this._buildPipeline();
  76245. },
  76246. enumerable: true,
  76247. configurable: true
  76248. });
  76249. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76250. get: function () {
  76251. return this._glowLayer == null;
  76252. },
  76253. /**
  76254. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76255. */
  76256. set: function (enabled) {
  76257. if (enabled && !this._glowLayer) {
  76258. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76259. }
  76260. else if (!enabled && this._glowLayer) {
  76261. this._glowLayer.dispose();
  76262. this._glowLayer = null;
  76263. }
  76264. },
  76265. enumerable: true,
  76266. configurable: true
  76267. });
  76268. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76269. get: function () {
  76270. return this._chromaticAberrationEnabled;
  76271. },
  76272. /**
  76273. * Enable or disable the chromaticAberration process from the pipeline
  76274. */
  76275. set: function (enabled) {
  76276. if (this._chromaticAberrationEnabled === enabled) {
  76277. return;
  76278. }
  76279. this._chromaticAberrationEnabled = enabled;
  76280. this._buildPipeline();
  76281. },
  76282. enumerable: true,
  76283. configurable: true
  76284. });
  76285. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76286. get: function () {
  76287. return this._grainEnabled;
  76288. },
  76289. /**
  76290. * Enable or disable the grain process from the pipeline
  76291. */
  76292. set: function (enabled) {
  76293. if (this._grainEnabled === enabled) {
  76294. return;
  76295. }
  76296. this._grainEnabled = enabled;
  76297. this._buildPipeline();
  76298. },
  76299. enumerable: true,
  76300. configurable: true
  76301. });
  76302. /**
  76303. * Force the compilation of the entire pipeline.
  76304. */
  76305. DefaultRenderingPipeline.prototype.prepare = function () {
  76306. var previousState = this._buildAllowed;
  76307. this._buildAllowed = true;
  76308. this._buildPipeline();
  76309. this._buildAllowed = previousState;
  76310. };
  76311. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76312. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76313. if (this._hasCleared) {
  76314. postProcess.autoClear = false;
  76315. }
  76316. else {
  76317. postProcess.autoClear = true;
  76318. this._scene.autoClear = false;
  76319. this._hasCleared = true;
  76320. }
  76321. if (!skipTextureSharing) {
  76322. if (this._prevPrevPostProcess) {
  76323. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76324. }
  76325. else {
  76326. postProcess.useOwnOutput();
  76327. }
  76328. if (this._prevPostProcess) {
  76329. this._prevPrevPostProcess = this._prevPostProcess;
  76330. }
  76331. this._prevPostProcess = postProcess;
  76332. }
  76333. };
  76334. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76335. var _this = this;
  76336. if (!this._buildAllowed) {
  76337. return;
  76338. }
  76339. this._scene.autoClear = true;
  76340. var engine = this._scene.getEngine();
  76341. this._disposePostProcesses();
  76342. if (this._cameras !== null) {
  76343. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76344. // get back cameras to be used to reattach pipeline
  76345. this._cameras = this._originalCameras.slice();
  76346. }
  76347. this._reset();
  76348. this._prevPostProcess = null;
  76349. this._prevPrevPostProcess = null;
  76350. this._hasCleared = false;
  76351. if (this.depthOfFieldEnabled) {
  76352. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76353. this.depthOfField.depthTexture = depthTexture;
  76354. if (!this.depthOfField._isReady()) {
  76355. this.depthOfField._updateEffects();
  76356. }
  76357. this.addEffect(this.depthOfField);
  76358. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76359. }
  76360. if (this.bloomEnabled) {
  76361. if (!this.bloom._isReady()) {
  76362. this.bloom._updateEffects();
  76363. }
  76364. this.addEffect(this.bloom);
  76365. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76366. }
  76367. if (this._imageProcessingEnabled) {
  76368. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76369. if (this._hdr) {
  76370. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76371. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76372. }
  76373. else {
  76374. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76375. }
  76376. }
  76377. if (this.sharpenEnabled) {
  76378. if (!this.sharpen.isReady()) {
  76379. this.sharpen.updateEffect();
  76380. }
  76381. this.addEffect(this._sharpenEffect);
  76382. this._setAutoClearAndTextureSharing(this.sharpen);
  76383. }
  76384. if (this.grainEnabled) {
  76385. if (!this.grain.isReady()) {
  76386. this.grain.updateEffect();
  76387. }
  76388. this.addEffect(this._grainEffect);
  76389. this._setAutoClearAndTextureSharing(this.grain);
  76390. }
  76391. if (this.chromaticAberrationEnabled) {
  76392. if (!this.chromaticAberration.isReady()) {
  76393. this.chromaticAberration.updateEffect();
  76394. }
  76395. this.addEffect(this._chromaticAberrationEffect);
  76396. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76397. }
  76398. if (this.fxaaEnabled) {
  76399. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76400. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76401. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76402. }
  76403. if (this._cameras !== null) {
  76404. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76405. }
  76406. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76407. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76408. }
  76409. };
  76410. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76411. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76412. for (var i = 0; i < this._cameras.length; i++) {
  76413. var camera = this._cameras[i];
  76414. if (this.imageProcessing) {
  76415. this.imageProcessing.dispose(camera);
  76416. }
  76417. if (this.fxaa) {
  76418. this.fxaa.dispose(camera);
  76419. }
  76420. // These are created in the constructor and should not be disposed on every pipeline change
  76421. if (disposeNonRecreated) {
  76422. if (this.sharpen) {
  76423. this.sharpen.dispose(camera);
  76424. }
  76425. if (this.depthOfField) {
  76426. this.depthOfField.disposeEffects(camera);
  76427. }
  76428. if (this.bloom) {
  76429. this.bloom.disposeEffects(camera);
  76430. }
  76431. if (this.chromaticAberration) {
  76432. this.chromaticAberration.dispose(camera);
  76433. }
  76434. if (this.grain) {
  76435. this.grain.dispose(camera);
  76436. }
  76437. if (this._glowLayer) {
  76438. this._glowLayer.dispose();
  76439. }
  76440. }
  76441. }
  76442. this.imageProcessing = null;
  76443. this.fxaa = null;
  76444. if (disposeNonRecreated) {
  76445. this.sharpen = null;
  76446. this._sharpenEffect = null;
  76447. this.depthOfField = null;
  76448. this.bloom = null;
  76449. this.chromaticAberration = null;
  76450. this._chromaticAberrationEffect = null;
  76451. this.grain = null;
  76452. this._grainEffect = null;
  76453. this._glowLayer = null;
  76454. }
  76455. };
  76456. /**
  76457. * Dispose of the pipeline and stop all post processes
  76458. */
  76459. DefaultRenderingPipeline.prototype.dispose = function () {
  76460. this._disposePostProcesses(true);
  76461. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76462. this._scene.autoClear = true;
  76463. if (this._resizeObserver) {
  76464. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76465. this._resizeObserver = null;
  76466. }
  76467. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76468. _super.prototype.dispose.call(this);
  76469. };
  76470. /**
  76471. * Serialize the rendering pipeline (Used when exporting)
  76472. * @returns the serialized object
  76473. */
  76474. DefaultRenderingPipeline.prototype.serialize = function () {
  76475. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76476. serializationObject.customType = "DefaultRenderingPipeline";
  76477. return serializationObject;
  76478. };
  76479. /**
  76480. * Parse the serialized pipeline
  76481. * @param source Source pipeline.
  76482. * @param scene The scene to load the pipeline to.
  76483. * @param rootUrl The URL of the serialized pipeline.
  76484. * @returns An instantiated pipeline from the serialized object.
  76485. */
  76486. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76487. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76488. };
  76489. __decorate([
  76490. BABYLON.serialize()
  76491. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76492. __decorate([
  76493. BABYLON.serialize()
  76494. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76495. __decorate([
  76496. BABYLON.serialize()
  76497. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76498. __decorate([
  76499. BABYLON.serialize()
  76500. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76501. __decorate([
  76502. BABYLON.serialize()
  76503. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76504. __decorate([
  76505. BABYLON.serialize()
  76506. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76507. __decorate([
  76508. BABYLON.serialize()
  76509. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76510. __decorate([
  76511. BABYLON.serialize()
  76512. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76513. __decorate([
  76514. BABYLON.serialize()
  76515. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76516. __decorate([
  76517. BABYLON.serialize()
  76518. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76519. __decorate([
  76520. BABYLON.serialize()
  76521. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76522. __decorate([
  76523. BABYLON.serialize()
  76524. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76525. __decorate([
  76526. BABYLON.serialize()
  76527. ], DefaultRenderingPipeline.prototype, "samples", null);
  76528. __decorate([
  76529. BABYLON.serialize()
  76530. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76531. __decorate([
  76532. BABYLON.serialize()
  76533. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76534. __decorate([
  76535. BABYLON.serialize()
  76536. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76537. __decorate([
  76538. BABYLON.serialize()
  76539. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76540. return DefaultRenderingPipeline;
  76541. }(BABYLON.PostProcessRenderPipeline));
  76542. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76543. })(BABYLON || (BABYLON = {}));
  76544. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76545. var BABYLON;
  76546. (function (BABYLON) {
  76547. /**
  76548. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76549. */
  76550. var GeometryBufferRenderer = /** @class */ (function () {
  76551. /**
  76552. * Creates a new G Buffer for the scene
  76553. * @param scene The scene the buffer belongs to
  76554. * @param ratio How big is the buffer related to the main canvas.
  76555. */
  76556. function GeometryBufferRenderer(scene, ratio) {
  76557. if (ratio === void 0) { ratio = 1; }
  76558. this._enablePosition = false;
  76559. this._scene = scene;
  76560. this._ratio = ratio;
  76561. // Render target
  76562. this._createRenderTargets();
  76563. }
  76564. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76565. /**
  76566. * Set the render list (meshes to be rendered) used in the G buffer.
  76567. */
  76568. set: function (meshes) {
  76569. this._multiRenderTarget.renderList = meshes;
  76570. },
  76571. enumerable: true,
  76572. configurable: true
  76573. });
  76574. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76575. /**
  76576. * Gets wether or not G buffer are supported by the running hardware.
  76577. * This requires draw buffer supports
  76578. */
  76579. get: function () {
  76580. return this._multiRenderTarget.isSupported;
  76581. },
  76582. enumerable: true,
  76583. configurable: true
  76584. });
  76585. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76586. /**
  76587. * Gets wether or not position are enabled for the G buffer.
  76588. */
  76589. get: function () {
  76590. return this._enablePosition;
  76591. },
  76592. /**
  76593. * Sets wether or not position are enabled for the G buffer.
  76594. */
  76595. set: function (enable) {
  76596. this._enablePosition = enable;
  76597. this.dispose();
  76598. this._createRenderTargets();
  76599. },
  76600. enumerable: true,
  76601. configurable: true
  76602. });
  76603. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76604. /**
  76605. * Gets the scene associated with the buffer.
  76606. */
  76607. get: function () {
  76608. return this._scene;
  76609. },
  76610. enumerable: true,
  76611. configurable: true
  76612. });
  76613. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76614. /**
  76615. * Gets the ratio used by the buffer during its creation.
  76616. * How big is the buffer related to the main canvas.
  76617. */
  76618. get: function () {
  76619. return this._ratio;
  76620. },
  76621. enumerable: true,
  76622. configurable: true
  76623. });
  76624. /**
  76625. * Checks wether everything is ready to render a submesh to the G buffer.
  76626. * @param subMesh the submesh to check readiness for
  76627. * @param useInstances is the mesh drawn using instance or not
  76628. * @returns true if ready otherwise false
  76629. */
  76630. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76631. var material = subMesh.getMaterial();
  76632. if (material && material.disableDepthWrite) {
  76633. return false;
  76634. }
  76635. var defines = [];
  76636. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76637. var mesh = subMesh.getMesh();
  76638. // Alpha test
  76639. if (material && material.needAlphaTesting()) {
  76640. defines.push("#define ALPHATEST");
  76641. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76642. attribs.push(BABYLON.VertexBuffer.UVKind);
  76643. defines.push("#define UV1");
  76644. }
  76645. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76646. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76647. defines.push("#define UV2");
  76648. }
  76649. }
  76650. // Buffers
  76651. if (this._enablePosition) {
  76652. defines.push("#define POSITION");
  76653. }
  76654. // Bones
  76655. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76656. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76657. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76658. if (mesh.numBoneInfluencers > 4) {
  76659. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76660. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76661. }
  76662. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76663. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76664. }
  76665. else {
  76666. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76667. }
  76668. // Instances
  76669. if (useInstances) {
  76670. defines.push("#define INSTANCES");
  76671. attribs.push("world0");
  76672. attribs.push("world1");
  76673. attribs.push("world2");
  76674. attribs.push("world3");
  76675. }
  76676. // Get correct effect
  76677. var join = defines.join("\n");
  76678. if (this._cachedDefines !== join) {
  76679. this._cachedDefines = join;
  76680. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76681. }
  76682. return this._effect.isReady();
  76683. };
  76684. /**
  76685. * Gets the current underlying G Buffer.
  76686. * @returns the buffer
  76687. */
  76688. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76689. return this._multiRenderTarget;
  76690. };
  76691. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76692. /**
  76693. * Gets the number of samples used to render the buffer (anti aliasing).
  76694. */
  76695. get: function () {
  76696. return this._multiRenderTarget.samples;
  76697. },
  76698. /**
  76699. * Sets the number of samples used to render the buffer (anti aliasing).
  76700. */
  76701. set: function (value) {
  76702. this._multiRenderTarget.samples = value;
  76703. },
  76704. enumerable: true,
  76705. configurable: true
  76706. });
  76707. /**
  76708. * Disposes the renderer and frees up associated resources.
  76709. */
  76710. GeometryBufferRenderer.prototype.dispose = function () {
  76711. this.getGBuffer().dispose();
  76712. };
  76713. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76714. var _this = this;
  76715. var engine = this._scene.getEngine();
  76716. var count = this._enablePosition ? 3 : 2;
  76717. 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 });
  76718. if (!this.isSupported) {
  76719. return;
  76720. }
  76721. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76722. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76723. this._multiRenderTarget.refreshRate = 1;
  76724. this._multiRenderTarget.renderParticles = false;
  76725. this._multiRenderTarget.renderList = null;
  76726. // set default depth value to 1.0 (far away)
  76727. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76728. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76729. });
  76730. // Custom render function
  76731. var renderSubMesh = function (subMesh) {
  76732. var mesh = subMesh.getRenderingMesh();
  76733. var scene = _this._scene;
  76734. var engine = scene.getEngine();
  76735. var material = subMesh.getMaterial();
  76736. if (!material) {
  76737. return;
  76738. }
  76739. // Culling
  76740. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76741. // Managing instances
  76742. var batch = mesh._getInstancesRenderList(subMesh._id);
  76743. if (batch.mustReturn) {
  76744. return;
  76745. }
  76746. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76747. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76748. engine.enableEffect(_this._effect);
  76749. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76750. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76751. _this._effect.setMatrix("view", scene.getViewMatrix());
  76752. // Alpha test
  76753. if (material && material.needAlphaTesting()) {
  76754. var alphaTexture = material.getAlphaTestTexture();
  76755. if (alphaTexture) {
  76756. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76757. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76758. }
  76759. }
  76760. // Bones
  76761. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76762. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76763. }
  76764. // Draw
  76765. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76766. }
  76767. };
  76768. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76769. var index;
  76770. if (depthOnlySubMeshes.length) {
  76771. engine.setColorWrite(false);
  76772. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76773. renderSubMesh(depthOnlySubMeshes.data[index]);
  76774. }
  76775. engine.setColorWrite(true);
  76776. }
  76777. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76778. renderSubMesh(opaqueSubMeshes.data[index]);
  76779. }
  76780. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76781. renderSubMesh(alphaTestSubMeshes.data[index]);
  76782. }
  76783. };
  76784. };
  76785. return GeometryBufferRenderer;
  76786. }());
  76787. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76788. })(BABYLON || (BABYLON = {}));
  76789. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76790. var BABYLON;
  76791. (function (BABYLON) {
  76792. /**
  76793. * This groups together the common properties used for image processing either in direct forward pass
  76794. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76795. * or not.
  76796. */
  76797. var ImageProcessingConfiguration = /** @class */ (function () {
  76798. function ImageProcessingConfiguration() {
  76799. /**
  76800. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76801. */
  76802. this.colorCurves = new BABYLON.ColorCurves();
  76803. this._colorCurvesEnabled = false;
  76804. this._colorGradingEnabled = false;
  76805. this._colorGradingWithGreenDepth = true;
  76806. this._colorGradingBGR = true;
  76807. this._exposure = 1.0;
  76808. this._toneMappingEnabled = false;
  76809. this._contrast = 1.0;
  76810. /**
  76811. * Vignette stretch size.
  76812. */
  76813. this.vignetteStretch = 0;
  76814. /**
  76815. * Vignette centre X Offset.
  76816. */
  76817. this.vignetteCentreX = 0;
  76818. /**
  76819. * Vignette centre Y Offset.
  76820. */
  76821. this.vignetteCentreY = 0;
  76822. /**
  76823. * Vignette weight or intensity of the vignette effect.
  76824. */
  76825. this.vignetteWeight = 1.5;
  76826. /**
  76827. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76828. * if vignetteEnabled is set to true.
  76829. */
  76830. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76831. /**
  76832. * Camera field of view used by the Vignette effect.
  76833. */
  76834. this.vignetteCameraFov = 0.5;
  76835. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76836. this._vignetteEnabled = false;
  76837. this._applyByPostProcess = false;
  76838. this._isEnabled = true;
  76839. /**
  76840. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76841. */
  76842. this.onUpdateParameters = new BABYLON.Observable();
  76843. }
  76844. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76845. /**
  76846. * Gets wether the color curves effect is enabled.
  76847. */
  76848. get: function () {
  76849. return this._colorCurvesEnabled;
  76850. },
  76851. /**
  76852. * Sets wether the color curves effect is enabled.
  76853. */
  76854. set: function (value) {
  76855. if (this._colorCurvesEnabled === value) {
  76856. return;
  76857. }
  76858. this._colorCurvesEnabled = value;
  76859. this._updateParameters();
  76860. },
  76861. enumerable: true,
  76862. configurable: true
  76863. });
  76864. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76865. /**
  76866. * Gets wether the color grading effect is enabled.
  76867. */
  76868. get: function () {
  76869. return this._colorGradingEnabled;
  76870. },
  76871. /**
  76872. * Sets wether the color grading effect is enabled.
  76873. */
  76874. set: function (value) {
  76875. if (this._colorGradingEnabled === value) {
  76876. return;
  76877. }
  76878. this._colorGradingEnabled = value;
  76879. this._updateParameters();
  76880. },
  76881. enumerable: true,
  76882. configurable: true
  76883. });
  76884. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76885. /**
  76886. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76887. */
  76888. get: function () {
  76889. return this._colorGradingWithGreenDepth;
  76890. },
  76891. /**
  76892. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76893. */
  76894. set: function (value) {
  76895. if (this._colorGradingWithGreenDepth === value) {
  76896. return;
  76897. }
  76898. this._colorGradingWithGreenDepth = value;
  76899. this._updateParameters();
  76900. },
  76901. enumerable: true,
  76902. configurable: true
  76903. });
  76904. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76905. /**
  76906. * Gets wether the color grading texture contains BGR values.
  76907. */
  76908. get: function () {
  76909. return this._colorGradingBGR;
  76910. },
  76911. /**
  76912. * Sets wether the color grading texture contains BGR values.
  76913. */
  76914. set: function (value) {
  76915. if (this._colorGradingBGR === value) {
  76916. return;
  76917. }
  76918. this._colorGradingBGR = value;
  76919. this._updateParameters();
  76920. },
  76921. enumerable: true,
  76922. configurable: true
  76923. });
  76924. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76925. /**
  76926. * Gets the Exposure used in the effect.
  76927. */
  76928. get: function () {
  76929. return this._exposure;
  76930. },
  76931. /**
  76932. * Sets the Exposure used in the effect.
  76933. */
  76934. set: function (value) {
  76935. if (this._exposure === value) {
  76936. return;
  76937. }
  76938. this._exposure = value;
  76939. this._updateParameters();
  76940. },
  76941. enumerable: true,
  76942. configurable: true
  76943. });
  76944. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76945. /**
  76946. * Gets wether the tone mapping effect is enabled.
  76947. */
  76948. get: function () {
  76949. return this._toneMappingEnabled;
  76950. },
  76951. /**
  76952. * Sets wether the tone mapping effect is enabled.
  76953. */
  76954. set: function (value) {
  76955. if (this._toneMappingEnabled === value) {
  76956. return;
  76957. }
  76958. this._toneMappingEnabled = value;
  76959. this._updateParameters();
  76960. },
  76961. enumerable: true,
  76962. configurable: true
  76963. });
  76964. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76965. /**
  76966. * Gets the contrast used in the effect.
  76967. */
  76968. get: function () {
  76969. return this._contrast;
  76970. },
  76971. /**
  76972. * Sets the contrast used in the effect.
  76973. */
  76974. set: function (value) {
  76975. if (this._contrast === value) {
  76976. return;
  76977. }
  76978. this._contrast = value;
  76979. this._updateParameters();
  76980. },
  76981. enumerable: true,
  76982. configurable: true
  76983. });
  76984. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76985. /**
  76986. * Gets the vignette blend mode allowing different kind of effect.
  76987. */
  76988. get: function () {
  76989. return this._vignetteBlendMode;
  76990. },
  76991. /**
  76992. * Sets the vignette blend mode allowing different kind of effect.
  76993. */
  76994. set: function (value) {
  76995. if (this._vignetteBlendMode === value) {
  76996. return;
  76997. }
  76998. this._vignetteBlendMode = value;
  76999. this._updateParameters();
  77000. },
  77001. enumerable: true,
  77002. configurable: true
  77003. });
  77004. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77005. /**
  77006. * Gets wether the vignette effect is enabled.
  77007. */
  77008. get: function () {
  77009. return this._vignetteEnabled;
  77010. },
  77011. /**
  77012. * Sets wether the vignette effect is enabled.
  77013. */
  77014. set: function (value) {
  77015. if (this._vignetteEnabled === value) {
  77016. return;
  77017. }
  77018. this._vignetteEnabled = value;
  77019. this._updateParameters();
  77020. },
  77021. enumerable: true,
  77022. configurable: true
  77023. });
  77024. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77025. /**
  77026. * Gets wether the image processing is applied through a post process or not.
  77027. */
  77028. get: function () {
  77029. return this._applyByPostProcess;
  77030. },
  77031. /**
  77032. * Sets wether the image processing is applied through a post process or not.
  77033. */
  77034. set: function (value) {
  77035. if (this._applyByPostProcess === value) {
  77036. return;
  77037. }
  77038. this._applyByPostProcess = value;
  77039. this._updateParameters();
  77040. },
  77041. enumerable: true,
  77042. configurable: true
  77043. });
  77044. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77045. /**
  77046. * Gets wether the image processing is enabled or not.
  77047. */
  77048. get: function () {
  77049. return this._isEnabled;
  77050. },
  77051. /**
  77052. * Sets wether the image processing is enabled or not.
  77053. */
  77054. set: function (value) {
  77055. if (this._isEnabled === value) {
  77056. return;
  77057. }
  77058. this._isEnabled = value;
  77059. this._updateParameters();
  77060. },
  77061. enumerable: true,
  77062. configurable: true
  77063. });
  77064. /**
  77065. * Method called each time the image processing information changes requires to recompile the effect.
  77066. */
  77067. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77068. this.onUpdateParameters.notifyObservers(this);
  77069. };
  77070. ImageProcessingConfiguration.prototype.getClassName = function () {
  77071. return "ImageProcessingConfiguration";
  77072. };
  77073. /**
  77074. * Prepare the list of uniforms associated with the Image Processing effects.
  77075. * @param uniformsList The list of uniforms used in the effect
  77076. * @param defines the list of defines currently in use
  77077. */
  77078. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77079. if (defines.EXPOSURE) {
  77080. uniforms.push("exposureLinear");
  77081. }
  77082. if (defines.CONTRAST) {
  77083. uniforms.push("contrast");
  77084. }
  77085. if (defines.COLORGRADING) {
  77086. uniforms.push("colorTransformSettings");
  77087. }
  77088. if (defines.VIGNETTE) {
  77089. uniforms.push("vInverseScreenSize");
  77090. uniforms.push("vignetteSettings1");
  77091. uniforms.push("vignetteSettings2");
  77092. }
  77093. if (defines.COLORCURVES) {
  77094. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77095. }
  77096. };
  77097. /**
  77098. * Prepare the list of samplers associated with the Image Processing effects.
  77099. * @param uniformsList The list of uniforms used in the effect
  77100. * @param defines the list of defines currently in use
  77101. */
  77102. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77103. if (defines.COLORGRADING) {
  77104. samplersList.push("txColorTransform");
  77105. }
  77106. };
  77107. /**
  77108. * Prepare the list of defines associated to the shader.
  77109. * @param defines the list of defines to complete
  77110. */
  77111. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77112. if (forPostProcess === void 0) { forPostProcess = false; }
  77113. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77114. defines.VIGNETTE = false;
  77115. defines.TONEMAPPING = false;
  77116. defines.CONTRAST = false;
  77117. defines.EXPOSURE = false;
  77118. defines.COLORCURVES = false;
  77119. defines.COLORGRADING = false;
  77120. defines.COLORGRADING3D = false;
  77121. defines.IMAGEPROCESSING = false;
  77122. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77123. return;
  77124. }
  77125. defines.VIGNETTE = this.vignetteEnabled;
  77126. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77127. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77128. defines.TONEMAPPING = this.toneMappingEnabled;
  77129. defines.CONTRAST = (this.contrast !== 1.0);
  77130. defines.EXPOSURE = (this.exposure !== 1.0);
  77131. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77132. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77133. if (defines.COLORGRADING) {
  77134. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77135. }
  77136. else {
  77137. defines.COLORGRADING3D = false;
  77138. }
  77139. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77140. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77141. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77142. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77143. };
  77144. /**
  77145. * Returns true if all the image processing information are ready.
  77146. */
  77147. ImageProcessingConfiguration.prototype.isReady = function () {
  77148. // Color Grading texure can not be none blocking.
  77149. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77150. };
  77151. /**
  77152. * Binds the image processing to the shader.
  77153. * @param effect The effect to bind to
  77154. */
  77155. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77156. if (aspectRatio === void 0) { aspectRatio = 1; }
  77157. // Color Curves
  77158. if (this._colorCurvesEnabled && this.colorCurves) {
  77159. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77160. }
  77161. // Vignette
  77162. if (this._vignetteEnabled) {
  77163. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77164. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77165. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77166. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77167. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77168. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77169. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77170. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77171. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77172. var vignettePower = -2.0 * this.vignetteWeight;
  77173. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77174. }
  77175. // Exposure
  77176. effect.setFloat("exposureLinear", this.exposure);
  77177. // Contrast
  77178. effect.setFloat("contrast", this.contrast);
  77179. // Color transform settings
  77180. if (this.colorGradingTexture) {
  77181. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77182. var textureSize = this.colorGradingTexture.getSize().height;
  77183. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77184. 0.5 / textureSize, // textureOffset
  77185. textureSize, // textureSize
  77186. this.colorGradingTexture.level // weight
  77187. );
  77188. }
  77189. };
  77190. /**
  77191. * Clones the current image processing instance.
  77192. * @return The cloned image processing
  77193. */
  77194. ImageProcessingConfiguration.prototype.clone = function () {
  77195. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77196. };
  77197. /**
  77198. * Serializes the current image processing instance to a json representation.
  77199. * @return a JSON representation
  77200. */
  77201. ImageProcessingConfiguration.prototype.serialize = function () {
  77202. return BABYLON.SerializationHelper.Serialize(this);
  77203. };
  77204. /**
  77205. * Parses the image processing from a json representation.
  77206. * @param source the JSON source to parse
  77207. * @return The parsed image processing
  77208. */
  77209. ImageProcessingConfiguration.Parse = function (source) {
  77210. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77211. };
  77212. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77213. /**
  77214. * Used to apply the vignette as a mix with the pixel color.
  77215. */
  77216. get: function () {
  77217. return this._VIGNETTEMODE_MULTIPLY;
  77218. },
  77219. enumerable: true,
  77220. configurable: true
  77221. });
  77222. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77223. /**
  77224. * Used to apply the vignette as a replacement of the pixel color.
  77225. */
  77226. get: function () {
  77227. return this._VIGNETTEMODE_OPAQUE;
  77228. },
  77229. enumerable: true,
  77230. configurable: true
  77231. });
  77232. // Static constants associated to the image processing.
  77233. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77234. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77235. __decorate([
  77236. BABYLON.serializeAsColorCurves()
  77237. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77238. __decorate([
  77239. BABYLON.serialize()
  77240. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77241. __decorate([
  77242. BABYLON.serializeAsTexture()
  77243. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77244. __decorate([
  77245. BABYLON.serialize()
  77246. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77247. __decorate([
  77248. BABYLON.serialize()
  77249. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77250. __decorate([
  77251. BABYLON.serialize()
  77252. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77253. __decorate([
  77254. BABYLON.serialize()
  77255. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77256. __decorate([
  77257. BABYLON.serialize()
  77258. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77259. __decorate([
  77260. BABYLON.serialize()
  77261. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77262. __decorate([
  77263. BABYLON.serialize()
  77264. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77265. __decorate([
  77266. BABYLON.serialize()
  77267. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77268. __decorate([
  77269. BABYLON.serialize()
  77270. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77271. __decorate([
  77272. BABYLON.serialize()
  77273. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77274. __decorate([
  77275. BABYLON.serializeAsColor4()
  77276. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77277. __decorate([
  77278. BABYLON.serialize()
  77279. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77280. __decorate([
  77281. BABYLON.serialize()
  77282. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77283. __decorate([
  77284. BABYLON.serialize()
  77285. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77286. __decorate([
  77287. BABYLON.serialize()
  77288. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77289. __decorate([
  77290. BABYLON.serialize()
  77291. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77292. return ImageProcessingConfiguration;
  77293. }());
  77294. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77295. })(BABYLON || (BABYLON = {}));
  77296. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77297. var BABYLON;
  77298. (function (BABYLON) {
  77299. /**
  77300. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77301. * It can help converting any input color in a desired output one. This can then be used to create effects
  77302. * from sepia, black and white to sixties or futuristic rendering...
  77303. *
  77304. * The only supported format is currently 3dl.
  77305. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77306. */
  77307. var ColorGradingTexture = /** @class */ (function (_super) {
  77308. __extends(ColorGradingTexture, _super);
  77309. /**
  77310. * Instantiates a ColorGradingTexture from the following parameters.
  77311. *
  77312. * @param url The location of the color gradind data (currently only supporting 3dl)
  77313. * @param scene The scene the texture will be used in
  77314. */
  77315. function ColorGradingTexture(url, scene) {
  77316. var _this = _super.call(this, scene) || this;
  77317. if (!url) {
  77318. return _this;
  77319. }
  77320. _this._engine = scene.getEngine();
  77321. _this._textureMatrix = BABYLON.Matrix.Identity();
  77322. _this.name = url;
  77323. _this.url = url;
  77324. _this.hasAlpha = false;
  77325. _this.isCube = false;
  77326. _this.is3D = _this._engine.webGLVersion > 1;
  77327. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77328. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77329. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77330. _this.anisotropicFilteringLevel = 1;
  77331. _this._texture = _this._getFromCache(url, true);
  77332. if (!_this._texture) {
  77333. if (!scene.useDelayedTextureLoading) {
  77334. _this.loadTexture();
  77335. }
  77336. else {
  77337. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77338. }
  77339. }
  77340. return _this;
  77341. }
  77342. /**
  77343. * Returns the texture matrix used in most of the material.
  77344. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77345. */
  77346. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77347. return this._textureMatrix;
  77348. };
  77349. /**
  77350. * Occurs when the file being loaded is a .3dl LUT file.
  77351. */
  77352. ColorGradingTexture.prototype.load3dlTexture = function () {
  77353. var engine = this._engine;
  77354. var texture;
  77355. if (engine.webGLVersion === 1) {
  77356. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77357. }
  77358. else {
  77359. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77360. }
  77361. this._texture = texture;
  77362. var callback = function (text) {
  77363. if (typeof text !== "string") {
  77364. return;
  77365. }
  77366. var data = null;
  77367. var tempData = null;
  77368. var line;
  77369. var lines = text.split('\n');
  77370. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77371. var maxColor = 0;
  77372. for (var i = 0; i < lines.length; i++) {
  77373. line = lines[i];
  77374. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77375. continue;
  77376. if (line.indexOf('#') === 0)
  77377. continue;
  77378. var words = line.split(" ");
  77379. if (size === 0) {
  77380. // Number of space + one
  77381. size = words.length;
  77382. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77383. tempData = new Float32Array(size * size * size * 4);
  77384. continue;
  77385. }
  77386. if (size != 0) {
  77387. var r = Math.max(parseInt(words[0]), 0);
  77388. var g = Math.max(parseInt(words[1]), 0);
  77389. var b = Math.max(parseInt(words[2]), 0);
  77390. maxColor = Math.max(r, maxColor);
  77391. maxColor = Math.max(g, maxColor);
  77392. maxColor = Math.max(b, maxColor);
  77393. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77394. if (tempData) {
  77395. tempData[pixelStorageIndex + 0] = r;
  77396. tempData[pixelStorageIndex + 1] = g;
  77397. tempData[pixelStorageIndex + 2] = b;
  77398. }
  77399. pixelIndexSlice++;
  77400. if (pixelIndexSlice % size == 0) {
  77401. pixelIndexH++;
  77402. pixelIndexSlice = 0;
  77403. if (pixelIndexH % size == 0) {
  77404. pixelIndexW++;
  77405. pixelIndexH = 0;
  77406. }
  77407. }
  77408. }
  77409. }
  77410. if (tempData && data) {
  77411. for (var i = 0; i < tempData.length; i++) {
  77412. if (i > 0 && (i + 1) % 4 === 0) {
  77413. data[i] = 255;
  77414. }
  77415. else {
  77416. var value = tempData[i];
  77417. data[i] = (value / maxColor * 255);
  77418. }
  77419. }
  77420. }
  77421. if (texture.is3D) {
  77422. texture.updateSize(size, size, size);
  77423. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77424. }
  77425. else {
  77426. texture.updateSize(size * size, size);
  77427. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77428. }
  77429. };
  77430. var scene = this.getScene();
  77431. if (scene) {
  77432. scene._loadFile(this.url, callback);
  77433. }
  77434. else {
  77435. this._engine._loadFile(this.url, callback);
  77436. }
  77437. return this._texture;
  77438. };
  77439. /**
  77440. * Starts the loading process of the texture.
  77441. */
  77442. ColorGradingTexture.prototype.loadTexture = function () {
  77443. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77444. this.load3dlTexture();
  77445. }
  77446. };
  77447. /**
  77448. * Clones the color gradind texture.
  77449. */
  77450. ColorGradingTexture.prototype.clone = function () {
  77451. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77452. // Base texture
  77453. newTexture.level = this.level;
  77454. return newTexture;
  77455. };
  77456. /**
  77457. * Called during delayed load for textures.
  77458. */
  77459. ColorGradingTexture.prototype.delayLoad = function () {
  77460. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77461. return;
  77462. }
  77463. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77464. this._texture = this._getFromCache(this.url, true);
  77465. if (!this._texture) {
  77466. this.loadTexture();
  77467. }
  77468. };
  77469. /**
  77470. * Parses a color grading texture serialized by Babylon.
  77471. * @param parsedTexture The texture information being parsedTexture
  77472. * @param scene The scene to load the texture in
  77473. * @param rootUrl The root url of the data assets to load
  77474. * @return A color gradind texture
  77475. */
  77476. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77477. var texture = null;
  77478. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77479. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77480. texture.name = parsedTexture.name;
  77481. texture.level = parsedTexture.level;
  77482. }
  77483. return texture;
  77484. };
  77485. /**
  77486. * Serializes the LUT texture to json format.
  77487. */
  77488. ColorGradingTexture.prototype.serialize = function () {
  77489. if (!this.name) {
  77490. return null;
  77491. }
  77492. var serializationObject = {};
  77493. serializationObject.name = this.name;
  77494. serializationObject.level = this.level;
  77495. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77496. return serializationObject;
  77497. };
  77498. /**
  77499. * Empty line regex stored for GC.
  77500. */
  77501. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77502. return ColorGradingTexture;
  77503. }(BABYLON.BaseTexture));
  77504. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77505. })(BABYLON || (BABYLON = {}));
  77506. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77507. var BABYLON;
  77508. (function (BABYLON) {
  77509. /**
  77510. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77511. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77512. * 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;
  77513. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77514. */
  77515. var ColorCurves = /** @class */ (function () {
  77516. function ColorCurves() {
  77517. this._dirty = true;
  77518. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77519. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77520. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77521. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77522. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77523. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77524. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77525. this._globalHue = 30;
  77526. this._globalDensity = 0;
  77527. this._globalSaturation = 0;
  77528. this._globalExposure = 0;
  77529. this._highlightsHue = 30;
  77530. this._highlightsDensity = 0;
  77531. this._highlightsSaturation = 0;
  77532. this._highlightsExposure = 0;
  77533. this._midtonesHue = 30;
  77534. this._midtonesDensity = 0;
  77535. this._midtonesSaturation = 0;
  77536. this._midtonesExposure = 0;
  77537. this._shadowsHue = 30;
  77538. this._shadowsDensity = 0;
  77539. this._shadowsSaturation = 0;
  77540. this._shadowsExposure = 0;
  77541. }
  77542. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77543. /**
  77544. * Gets the global Hue value.
  77545. * 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).
  77546. */
  77547. get: function () {
  77548. return this._globalHue;
  77549. },
  77550. /**
  77551. * Sets the global Hue value.
  77552. * 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).
  77553. */
  77554. set: function (value) {
  77555. this._globalHue = value;
  77556. this._dirty = true;
  77557. },
  77558. enumerable: true,
  77559. configurable: true
  77560. });
  77561. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77562. /**
  77563. * Gets the global Density value.
  77564. * 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.
  77565. * Values less than zero provide a filter of opposite hue.
  77566. */
  77567. get: function () {
  77568. return this._globalDensity;
  77569. },
  77570. /**
  77571. * Sets the global Density value.
  77572. * 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.
  77573. * Values less than zero provide a filter of opposite hue.
  77574. */
  77575. set: function (value) {
  77576. this._globalDensity = value;
  77577. this._dirty = true;
  77578. },
  77579. enumerable: true,
  77580. configurable: true
  77581. });
  77582. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77583. /**
  77584. * Gets the global Saturation value.
  77585. * 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.
  77586. */
  77587. get: function () {
  77588. return this._globalSaturation;
  77589. },
  77590. /**
  77591. * Sets the global Saturation value.
  77592. * 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.
  77593. */
  77594. set: function (value) {
  77595. this._globalSaturation = value;
  77596. this._dirty = true;
  77597. },
  77598. enumerable: true,
  77599. configurable: true
  77600. });
  77601. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77602. /**
  77603. * Gets the global Exposure value.
  77604. * 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.
  77605. */
  77606. get: function () {
  77607. return this._globalExposure;
  77608. },
  77609. /**
  77610. * Sets the global Exposure value.
  77611. * 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.
  77612. */
  77613. set: function (value) {
  77614. this._globalExposure = value;
  77615. this._dirty = true;
  77616. },
  77617. enumerable: true,
  77618. configurable: true
  77619. });
  77620. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77621. /**
  77622. * Gets the highlights Hue value.
  77623. * 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).
  77624. */
  77625. get: function () {
  77626. return this._highlightsHue;
  77627. },
  77628. /**
  77629. * Sets the highlights Hue value.
  77630. * 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).
  77631. */
  77632. set: function (value) {
  77633. this._highlightsHue = value;
  77634. this._dirty = true;
  77635. },
  77636. enumerable: true,
  77637. configurable: true
  77638. });
  77639. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77640. /**
  77641. * Gets the highlights Density value.
  77642. * 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.
  77643. * Values less than zero provide a filter of opposite hue.
  77644. */
  77645. get: function () {
  77646. return this._highlightsDensity;
  77647. },
  77648. /**
  77649. * Sets the highlights Density value.
  77650. * 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.
  77651. * Values less than zero provide a filter of opposite hue.
  77652. */
  77653. set: function (value) {
  77654. this._highlightsDensity = value;
  77655. this._dirty = true;
  77656. },
  77657. enumerable: true,
  77658. configurable: true
  77659. });
  77660. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77661. /**
  77662. * Gets the highlights Saturation value.
  77663. * 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.
  77664. */
  77665. get: function () {
  77666. return this._highlightsSaturation;
  77667. },
  77668. /**
  77669. * Sets the highlights Saturation value.
  77670. * 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.
  77671. */
  77672. set: function (value) {
  77673. this._highlightsSaturation = value;
  77674. this._dirty = true;
  77675. },
  77676. enumerable: true,
  77677. configurable: true
  77678. });
  77679. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77680. /**
  77681. * Gets the highlights Exposure value.
  77682. * 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.
  77683. */
  77684. get: function () {
  77685. return this._highlightsExposure;
  77686. },
  77687. /**
  77688. * Sets the highlights Exposure value.
  77689. * 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.
  77690. */
  77691. set: function (value) {
  77692. this._highlightsExposure = value;
  77693. this._dirty = true;
  77694. },
  77695. enumerable: true,
  77696. configurable: true
  77697. });
  77698. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77699. /**
  77700. * Gets the midtones Hue value.
  77701. * 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).
  77702. */
  77703. get: function () {
  77704. return this._midtonesHue;
  77705. },
  77706. /**
  77707. * Sets the midtones Hue value.
  77708. * 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).
  77709. */
  77710. set: function (value) {
  77711. this._midtonesHue = value;
  77712. this._dirty = true;
  77713. },
  77714. enumerable: true,
  77715. configurable: true
  77716. });
  77717. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77718. /**
  77719. * Gets the midtones Density value.
  77720. * 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.
  77721. * Values less than zero provide a filter of opposite hue.
  77722. */
  77723. get: function () {
  77724. return this._midtonesDensity;
  77725. },
  77726. /**
  77727. * Sets the midtones Density value.
  77728. * 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.
  77729. * Values less than zero provide a filter of opposite hue.
  77730. */
  77731. set: function (value) {
  77732. this._midtonesDensity = value;
  77733. this._dirty = true;
  77734. },
  77735. enumerable: true,
  77736. configurable: true
  77737. });
  77738. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77739. /**
  77740. * Gets the midtones Saturation value.
  77741. * 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.
  77742. */
  77743. get: function () {
  77744. return this._midtonesSaturation;
  77745. },
  77746. /**
  77747. * Sets the midtones Saturation value.
  77748. * 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.
  77749. */
  77750. set: function (value) {
  77751. this._midtonesSaturation = value;
  77752. this._dirty = true;
  77753. },
  77754. enumerable: true,
  77755. configurable: true
  77756. });
  77757. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77758. /**
  77759. * Gets the midtones Exposure value.
  77760. * 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.
  77761. */
  77762. get: function () {
  77763. return this._midtonesExposure;
  77764. },
  77765. /**
  77766. * Sets the midtones Exposure value.
  77767. * 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.
  77768. */
  77769. set: function (value) {
  77770. this._midtonesExposure = value;
  77771. this._dirty = true;
  77772. },
  77773. enumerable: true,
  77774. configurable: true
  77775. });
  77776. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77777. /**
  77778. * Gets the shadows Hue value.
  77779. * 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).
  77780. */
  77781. get: function () {
  77782. return this._shadowsHue;
  77783. },
  77784. /**
  77785. * Sets the shadows Hue value.
  77786. * 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).
  77787. */
  77788. set: function (value) {
  77789. this._shadowsHue = value;
  77790. this._dirty = true;
  77791. },
  77792. enumerable: true,
  77793. configurable: true
  77794. });
  77795. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77796. /**
  77797. * Gets the shadows Density value.
  77798. * 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.
  77799. * Values less than zero provide a filter of opposite hue.
  77800. */
  77801. get: function () {
  77802. return this._shadowsDensity;
  77803. },
  77804. /**
  77805. * Sets the shadows Density value.
  77806. * 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.
  77807. * Values less than zero provide a filter of opposite hue.
  77808. */
  77809. set: function (value) {
  77810. this._shadowsDensity = value;
  77811. this._dirty = true;
  77812. },
  77813. enumerable: true,
  77814. configurable: true
  77815. });
  77816. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77817. /**
  77818. * Gets the shadows Saturation value.
  77819. * 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.
  77820. */
  77821. get: function () {
  77822. return this._shadowsSaturation;
  77823. },
  77824. /**
  77825. * Sets the shadows Saturation value.
  77826. * 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.
  77827. */
  77828. set: function (value) {
  77829. this._shadowsSaturation = value;
  77830. this._dirty = true;
  77831. },
  77832. enumerable: true,
  77833. configurable: true
  77834. });
  77835. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77836. /**
  77837. * Gets the shadows Exposure value.
  77838. * 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.
  77839. */
  77840. get: function () {
  77841. return this._shadowsExposure;
  77842. },
  77843. /**
  77844. * Sets the shadows Exposure value.
  77845. * 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.
  77846. */
  77847. set: function (value) {
  77848. this._shadowsExposure = value;
  77849. this._dirty = true;
  77850. },
  77851. enumerable: true,
  77852. configurable: true
  77853. });
  77854. ColorCurves.prototype.getClassName = function () {
  77855. return "ColorCurves";
  77856. };
  77857. /**
  77858. * Binds the color curves to the shader.
  77859. * @param colorCurves The color curve to bind
  77860. * @param effect The effect to bind to
  77861. */
  77862. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77863. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77864. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77865. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77866. if (colorCurves._dirty) {
  77867. colorCurves._dirty = false;
  77868. // Fill in global info.
  77869. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77870. // Compute highlights info.
  77871. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77872. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77873. // Compute midtones info.
  77874. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77875. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77876. // Compute shadows info.
  77877. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77878. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77879. // Compute deltas (neutral is midtones).
  77880. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77881. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77882. }
  77883. if (effect) {
  77884. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77885. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77886. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77887. }
  77888. };
  77889. /**
  77890. * Prepare the list of uniforms associated with the ColorCurves effects.
  77891. * @param uniformsList The list of uniforms used in the effect
  77892. */
  77893. ColorCurves.PrepareUniforms = function (uniformsList) {
  77894. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77895. };
  77896. /**
  77897. * Returns color grading data based on a hue, density, saturation and exposure value.
  77898. * @param filterHue The hue of the color filter.
  77899. * @param filterDensity The density of the color filter.
  77900. * @param saturation The saturation.
  77901. * @param exposure The exposure.
  77902. * @param result The result data container.
  77903. */
  77904. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77905. if (hue == null) {
  77906. return;
  77907. }
  77908. hue = ColorCurves.clamp(hue, 0, 360);
  77909. density = ColorCurves.clamp(density, -100, 100);
  77910. saturation = ColorCurves.clamp(saturation, -100, 100);
  77911. exposure = ColorCurves.clamp(exposure, -100, 100);
  77912. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77913. // so that the maximum filter density is only 50% control. This provides fine control
  77914. // for small values and reasonable range.
  77915. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77916. density *= 0.5;
  77917. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77918. if (density < 0) {
  77919. density *= -1;
  77920. hue = (hue + 180) % 360;
  77921. }
  77922. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77923. result.scaleToRef(2, result);
  77924. result.a = 1 + 0.01 * saturation;
  77925. };
  77926. /**
  77927. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77928. * @param value The input slider value in range [-100,100].
  77929. * @returns Adjusted value.
  77930. */
  77931. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77932. value /= 100;
  77933. var x = Math.abs(value);
  77934. x = Math.pow(x, 2);
  77935. if (value < 0) {
  77936. x *= -1;
  77937. }
  77938. x *= 100;
  77939. return x;
  77940. };
  77941. /**
  77942. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77943. * @param hue The hue (H) input.
  77944. * @param saturation The saturation (S) input.
  77945. * @param brightness The brightness (B) input.
  77946. * @result An RGBA color represented as Vector4.
  77947. */
  77948. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77949. var h = ColorCurves.clamp(hue, 0, 360);
  77950. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77951. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77952. if (s === 0) {
  77953. result.r = v;
  77954. result.g = v;
  77955. result.b = v;
  77956. }
  77957. else {
  77958. // sector 0 to 5
  77959. h /= 60;
  77960. var i = Math.floor(h);
  77961. // fractional part of h
  77962. var f = h - i;
  77963. var p = v * (1 - s);
  77964. var q = v * (1 - s * f);
  77965. var t = v * (1 - s * (1 - f));
  77966. switch (i) {
  77967. case 0:
  77968. result.r = v;
  77969. result.g = t;
  77970. result.b = p;
  77971. break;
  77972. case 1:
  77973. result.r = q;
  77974. result.g = v;
  77975. result.b = p;
  77976. break;
  77977. case 2:
  77978. result.r = p;
  77979. result.g = v;
  77980. result.b = t;
  77981. break;
  77982. case 3:
  77983. result.r = p;
  77984. result.g = q;
  77985. result.b = v;
  77986. break;
  77987. case 4:
  77988. result.r = t;
  77989. result.g = p;
  77990. result.b = v;
  77991. break;
  77992. default: // case 5:
  77993. result.r = v;
  77994. result.g = p;
  77995. result.b = q;
  77996. break;
  77997. }
  77998. }
  77999. result.a = 1;
  78000. };
  78001. /**
  78002. * Returns a value clamped between min and max
  78003. * @param value The value to clamp
  78004. * @param min The minimum of value
  78005. * @param max The maximum of value
  78006. * @returns The clamped value.
  78007. */
  78008. ColorCurves.clamp = function (value, min, max) {
  78009. return Math.min(Math.max(value, min), max);
  78010. };
  78011. /**
  78012. * Clones the current color curve instance.
  78013. * @return The cloned curves
  78014. */
  78015. ColorCurves.prototype.clone = function () {
  78016. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78017. };
  78018. /**
  78019. * Serializes the current color curve instance to a json representation.
  78020. * @return a JSON representation
  78021. */
  78022. ColorCurves.prototype.serialize = function () {
  78023. return BABYLON.SerializationHelper.Serialize(this);
  78024. };
  78025. /**
  78026. * Parses the color curve from a json representation.
  78027. * @param source the JSON source to parse
  78028. * @return The parsed curves
  78029. */
  78030. ColorCurves.Parse = function (source) {
  78031. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78032. };
  78033. __decorate([
  78034. BABYLON.serialize()
  78035. ], ColorCurves.prototype, "_globalHue", void 0);
  78036. __decorate([
  78037. BABYLON.serialize()
  78038. ], ColorCurves.prototype, "_globalDensity", void 0);
  78039. __decorate([
  78040. BABYLON.serialize()
  78041. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78042. __decorate([
  78043. BABYLON.serialize()
  78044. ], ColorCurves.prototype, "_globalExposure", void 0);
  78045. __decorate([
  78046. BABYLON.serialize()
  78047. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78048. __decorate([
  78049. BABYLON.serialize()
  78050. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78051. __decorate([
  78052. BABYLON.serialize()
  78053. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78054. __decorate([
  78055. BABYLON.serialize()
  78056. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78057. __decorate([
  78058. BABYLON.serialize()
  78059. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78060. __decorate([
  78061. BABYLON.serialize()
  78062. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78063. __decorate([
  78064. BABYLON.serialize()
  78065. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78066. __decorate([
  78067. BABYLON.serialize()
  78068. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78069. return ColorCurves;
  78070. }());
  78071. BABYLON.ColorCurves = ColorCurves;
  78072. })(BABYLON || (BABYLON = {}));
  78073. //# sourceMappingURL=babylon.colorCurves.js.map
  78074. var BABYLON;
  78075. (function (BABYLON) {
  78076. var RefractionPostProcess = /** @class */ (function (_super) {
  78077. __extends(RefractionPostProcess, _super);
  78078. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78079. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78080. _this.color = color;
  78081. _this.depth = depth;
  78082. _this.colorLevel = colorLevel;
  78083. _this._ownRefractionTexture = true;
  78084. _this.onActivateObservable.add(function (cam) {
  78085. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78086. });
  78087. _this.onApplyObservable.add(function (effect) {
  78088. effect.setColor3("baseColor", _this.color);
  78089. effect.setFloat("depth", _this.depth);
  78090. effect.setFloat("colorLevel", _this.colorLevel);
  78091. effect.setTexture("refractionSampler", _this._refTexture);
  78092. });
  78093. return _this;
  78094. }
  78095. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78096. /**
  78097. * Gets or sets the refraction texture
  78098. * Please note that you are responsible for disposing the texture if you set it manually
  78099. */
  78100. get: function () {
  78101. return this._refTexture;
  78102. },
  78103. set: function (value) {
  78104. if (this._refTexture && this._ownRefractionTexture) {
  78105. this._refTexture.dispose();
  78106. }
  78107. this._refTexture = value;
  78108. this._ownRefractionTexture = false;
  78109. },
  78110. enumerable: true,
  78111. configurable: true
  78112. });
  78113. // Methods
  78114. RefractionPostProcess.prototype.dispose = function (camera) {
  78115. if (this._refTexture && this._ownRefractionTexture) {
  78116. this._refTexture.dispose();
  78117. this._refTexture = null;
  78118. }
  78119. _super.prototype.dispose.call(this, camera);
  78120. };
  78121. return RefractionPostProcess;
  78122. }(BABYLON.PostProcess));
  78123. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78124. })(BABYLON || (BABYLON = {}));
  78125. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78126. var BABYLON;
  78127. (function (BABYLON) {
  78128. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78129. __extends(BlackAndWhitePostProcess, _super);
  78130. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78131. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78132. _this.degree = 1;
  78133. _this.onApplyObservable.add(function (effect) {
  78134. effect.setFloat("degree", _this.degree);
  78135. });
  78136. return _this;
  78137. }
  78138. return BlackAndWhitePostProcess;
  78139. }(BABYLON.PostProcess));
  78140. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78141. })(BABYLON || (BABYLON = {}));
  78142. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78143. var BABYLON;
  78144. (function (BABYLON) {
  78145. /**
  78146. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78147. * input texture to perform effects such as edge detection or sharpening
  78148. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78149. */
  78150. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78151. __extends(ConvolutionPostProcess, _super);
  78152. /**
  78153. * Creates a new instance ConvolutionPostProcess
  78154. * @param name The name of the effect.
  78155. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78156. * @param options The required width/height ratio to downsize to before computing the render pass.
  78157. * @param camera The camera to apply the render pass to.
  78158. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78159. * @param engine The engine which the post process will be applied. (default: current engine)
  78160. * @param reusable If the post process can be reused on the same frame. (default: false)
  78161. * @param textureType Type of textures used when performing the post process. (default: 0)
  78162. */
  78163. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78164. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78165. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78166. _this.kernel = kernel;
  78167. _this.onApply = function (effect) {
  78168. effect.setFloat2("screenSize", _this.width, _this.height);
  78169. effect.setArray("kernel", _this.kernel);
  78170. };
  78171. return _this;
  78172. }
  78173. // Statics
  78174. /**
  78175. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78176. */
  78177. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78178. /**
  78179. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78180. */
  78181. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78182. /**
  78183. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78184. */
  78185. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78186. /**
  78187. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78188. */
  78189. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78190. /**
  78191. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78192. */
  78193. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78194. /**
  78195. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78196. */
  78197. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78198. return ConvolutionPostProcess;
  78199. }(BABYLON.PostProcess));
  78200. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78201. })(BABYLON || (BABYLON = {}));
  78202. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78203. var BABYLON;
  78204. (function (BABYLON) {
  78205. var FilterPostProcess = /** @class */ (function (_super) {
  78206. __extends(FilterPostProcess, _super);
  78207. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78208. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78209. _this.kernelMatrix = kernelMatrix;
  78210. _this.onApply = function (effect) {
  78211. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78212. };
  78213. return _this;
  78214. }
  78215. return FilterPostProcess;
  78216. }(BABYLON.PostProcess));
  78217. BABYLON.FilterPostProcess = FilterPostProcess;
  78218. })(BABYLON || (BABYLON = {}));
  78219. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78220. var BABYLON;
  78221. (function (BABYLON) {
  78222. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78223. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78224. __extends(VolumetricLightScatteringPostProcess, _super);
  78225. /**
  78226. * @constructor
  78227. * @param {string} name - The post-process name
  78228. * @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)
  78229. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78230. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78231. * @param {number} samples - The post-process quality, default 100
  78232. * @param {number} samplingMode - The post-process filtering mode
  78233. * @param {BABYLON.Engine} engine - The babylon engine
  78234. * @param {boolean} reusable - If the post-process is reusable
  78235. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78236. */
  78237. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78238. if (samples === void 0) { samples = 100; }
  78239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78240. 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;
  78241. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78242. /**
  78243. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78244. */
  78245. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78246. /**
  78247. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78248. */
  78249. _this.useCustomMeshPosition = false;
  78250. /**
  78251. * If the post-process should inverse the light scattering direction
  78252. */
  78253. _this.invert = true;
  78254. /**
  78255. * Array containing the excluded meshes not rendered in the internal pass
  78256. */
  78257. _this.excludedMeshes = new Array();
  78258. /**
  78259. * Controls the overall intensity of the post-process
  78260. */
  78261. _this.exposure = 0.3;
  78262. /**
  78263. * Dissipates each sample's contribution in range [0, 1]
  78264. */
  78265. _this.decay = 0.96815;
  78266. /**
  78267. * Controls the overall intensity of each sample
  78268. */
  78269. _this.weight = 0.58767;
  78270. /**
  78271. * Controls the density of each sample
  78272. */
  78273. _this.density = 0.926;
  78274. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78275. engine = scene.getEngine();
  78276. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78277. // Configure mesh
  78278. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78279. // Configure
  78280. _this._createPass(scene, ratio.passRatio || ratio);
  78281. _this.onActivate = function (camera) {
  78282. if (!_this.isSupported) {
  78283. _this.dispose(camera);
  78284. }
  78285. _this.onActivate = null;
  78286. };
  78287. _this.onApplyObservable.add(function (effect) {
  78288. _this._updateMeshScreenCoordinates(scene);
  78289. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78290. effect.setFloat("exposure", _this.exposure);
  78291. effect.setFloat("decay", _this.decay);
  78292. effect.setFloat("weight", _this.weight);
  78293. effect.setFloat("density", _this.density);
  78294. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78295. });
  78296. return _this;
  78297. }
  78298. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78299. get: function () {
  78300. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78301. return false;
  78302. },
  78303. set: function (useDiffuseColor) {
  78304. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78305. },
  78306. enumerable: true,
  78307. configurable: true
  78308. });
  78309. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78310. return "VolumetricLightScatteringPostProcess";
  78311. };
  78312. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78313. var mesh = subMesh.getMesh();
  78314. // Render this.mesh as default
  78315. if (mesh === this.mesh && mesh.material) {
  78316. return mesh.material.isReady(mesh);
  78317. }
  78318. var defines = [];
  78319. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78320. var material = subMesh.getMaterial();
  78321. // Alpha test
  78322. if (material) {
  78323. if (material.needAlphaTesting()) {
  78324. defines.push("#define ALPHATEST");
  78325. }
  78326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78327. attribs.push(BABYLON.VertexBuffer.UVKind);
  78328. defines.push("#define UV1");
  78329. }
  78330. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78331. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78332. defines.push("#define UV2");
  78333. }
  78334. }
  78335. // Bones
  78336. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78337. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78338. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78339. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78340. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78341. }
  78342. else {
  78343. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78344. }
  78345. // Instances
  78346. if (useInstances) {
  78347. defines.push("#define INSTANCES");
  78348. attribs.push("world0");
  78349. attribs.push("world1");
  78350. attribs.push("world2");
  78351. attribs.push("world3");
  78352. }
  78353. // Get correct effect
  78354. var join = defines.join("\n");
  78355. if (this._cachedDefines !== join) {
  78356. this._cachedDefines = join;
  78357. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78358. }
  78359. return this._volumetricLightScatteringPass.isReady();
  78360. };
  78361. /**
  78362. * Sets the new light position for light scattering effect
  78363. * @param {BABYLON.Vector3} The new custom light position
  78364. */
  78365. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78366. this.customMeshPosition = position;
  78367. };
  78368. /**
  78369. * Returns the light position for light scattering effect
  78370. * @return {BABYLON.Vector3} The custom light position
  78371. */
  78372. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78373. return this.customMeshPosition;
  78374. };
  78375. /**
  78376. * Disposes the internal assets and detaches the post-process from the camera
  78377. */
  78378. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78379. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78380. if (rttIndex !== -1) {
  78381. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78382. }
  78383. this._volumetricLightScatteringRTT.dispose();
  78384. _super.prototype.dispose.call(this, camera);
  78385. };
  78386. /**
  78387. * Returns the render target texture used by the post-process
  78388. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78389. */
  78390. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78391. return this._volumetricLightScatteringRTT;
  78392. };
  78393. // Private methods
  78394. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78395. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78396. return true;
  78397. }
  78398. return false;
  78399. };
  78400. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78401. var _this = this;
  78402. var engine = scene.getEngine();
  78403. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78404. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78405. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78406. this._volumetricLightScatteringRTT.renderList = null;
  78407. this._volumetricLightScatteringRTT.renderParticles = false;
  78408. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78409. var camera = this.getCamera();
  78410. if (camera) {
  78411. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78412. }
  78413. else {
  78414. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78415. }
  78416. // Custom render function for submeshes
  78417. var renderSubMesh = function (subMesh) {
  78418. var mesh = subMesh.getRenderingMesh();
  78419. if (_this._meshExcluded(mesh)) {
  78420. return;
  78421. }
  78422. var material = subMesh.getMaterial();
  78423. if (!material) {
  78424. return;
  78425. }
  78426. var scene = mesh.getScene();
  78427. var engine = scene.getEngine();
  78428. // Culling
  78429. engine.setState(material.backFaceCulling);
  78430. // Managing instances
  78431. var batch = mesh._getInstancesRenderList(subMesh._id);
  78432. if (batch.mustReturn) {
  78433. return;
  78434. }
  78435. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78436. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78437. var effect = _this._volumetricLightScatteringPass;
  78438. if (mesh === _this.mesh) {
  78439. if (subMesh.effect) {
  78440. effect = subMesh.effect;
  78441. }
  78442. else {
  78443. effect = material.getEffect();
  78444. }
  78445. }
  78446. engine.enableEffect(effect);
  78447. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78448. if (mesh === _this.mesh) {
  78449. material.bind(mesh.getWorldMatrix(), mesh);
  78450. }
  78451. else {
  78452. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78453. // Alpha test
  78454. if (material && material.needAlphaTesting()) {
  78455. var alphaTexture = material.getAlphaTestTexture();
  78456. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78457. if (alphaTexture) {
  78458. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78459. }
  78460. }
  78461. // Bones
  78462. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78463. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78464. }
  78465. }
  78466. // Draw
  78467. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78468. }
  78469. };
  78470. // Render target texture callbacks
  78471. var savedSceneClearColor;
  78472. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78473. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78474. savedSceneClearColor = scene.clearColor;
  78475. scene.clearColor = sceneClearColor;
  78476. });
  78477. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78478. scene.clearColor = savedSceneClearColor;
  78479. });
  78480. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78481. var engine = scene.getEngine();
  78482. var index;
  78483. if (depthOnlySubMeshes.length) {
  78484. engine.setColorWrite(false);
  78485. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78486. renderSubMesh(depthOnlySubMeshes.data[index]);
  78487. }
  78488. engine.setColorWrite(true);
  78489. }
  78490. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78491. renderSubMesh(opaqueSubMeshes.data[index]);
  78492. }
  78493. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78494. renderSubMesh(alphaTestSubMeshes.data[index]);
  78495. }
  78496. if (transparentSubMeshes.length) {
  78497. // Sort sub meshes
  78498. for (index = 0; index < transparentSubMeshes.length; index++) {
  78499. var submesh = transparentSubMeshes.data[index];
  78500. var boundingInfo = submesh.getBoundingInfo();
  78501. if (boundingInfo && scene.activeCamera) {
  78502. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78503. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78504. }
  78505. }
  78506. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78507. sortedArray.sort(function (a, b) {
  78508. // Alpha index first
  78509. if (a._alphaIndex > b._alphaIndex) {
  78510. return 1;
  78511. }
  78512. if (a._alphaIndex < b._alphaIndex) {
  78513. return -1;
  78514. }
  78515. // Then distance to camera
  78516. if (a._distanceToCamera < b._distanceToCamera) {
  78517. return 1;
  78518. }
  78519. if (a._distanceToCamera > b._distanceToCamera) {
  78520. return -1;
  78521. }
  78522. return 0;
  78523. });
  78524. // Render sub meshes
  78525. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78526. for (index = 0; index < sortedArray.length; index++) {
  78527. renderSubMesh(sortedArray[index]);
  78528. }
  78529. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78530. }
  78531. };
  78532. };
  78533. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78534. var transform = scene.getTransformMatrix();
  78535. var meshPosition;
  78536. if (this.useCustomMeshPosition) {
  78537. meshPosition = this.customMeshPosition;
  78538. }
  78539. else if (this.attachedNode) {
  78540. meshPosition = this.attachedNode.position;
  78541. }
  78542. else {
  78543. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78544. }
  78545. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78546. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78547. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78548. if (this.invert)
  78549. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78550. };
  78551. // Static methods
  78552. /**
  78553. * Creates a default mesh for the Volumeric Light Scattering post-process
  78554. * @param {string} The mesh name
  78555. * @param {BABYLON.Scene} The scene where to create the mesh
  78556. * @return {BABYLON.Mesh} the default mesh
  78557. */
  78558. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78559. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78560. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78561. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78562. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78563. mesh.material = material;
  78564. return mesh;
  78565. };
  78566. __decorate([
  78567. BABYLON.serializeAsVector3()
  78568. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78569. __decorate([
  78570. BABYLON.serialize()
  78571. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78572. __decorate([
  78573. BABYLON.serialize()
  78574. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78575. __decorate([
  78576. BABYLON.serializeAsMeshReference()
  78577. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78578. __decorate([
  78579. BABYLON.serialize()
  78580. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78581. __decorate([
  78582. BABYLON.serialize()
  78583. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78584. __decorate([
  78585. BABYLON.serialize()
  78586. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78587. __decorate([
  78588. BABYLON.serialize()
  78589. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78590. __decorate([
  78591. BABYLON.serialize()
  78592. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78593. return VolumetricLightScatteringPostProcess;
  78594. }(BABYLON.PostProcess));
  78595. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78596. })(BABYLON || (BABYLON = {}));
  78597. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78598. //
  78599. // This post-process allows the modification of rendered colors by using
  78600. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78601. //
  78602. // The object needs to be provided an url to a texture containing the color
  78603. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78604. // Use an image editing software to tweak the LUT to match your needs.
  78605. //
  78606. // For an example of a color LUT, see here:
  78607. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78608. // For explanations on color grading, see here:
  78609. // http://udn.epicgames.com/Three/ColorGrading.html
  78610. //
  78611. var BABYLON;
  78612. (function (BABYLON) {
  78613. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78614. __extends(ColorCorrectionPostProcess, _super);
  78615. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78616. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78617. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78618. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78619. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78620. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78621. _this.onApply = function (effect) {
  78622. effect.setTexture("colorTable", _this._colorTableTexture);
  78623. };
  78624. return _this;
  78625. }
  78626. return ColorCorrectionPostProcess;
  78627. }(BABYLON.PostProcess));
  78628. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78629. })(BABYLON || (BABYLON = {}));
  78630. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78631. var BABYLON;
  78632. (function (BABYLON) {
  78633. /** Defines operator used for tonemapping */
  78634. var TonemappingOperator;
  78635. (function (TonemappingOperator) {
  78636. /** Hable */
  78637. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78638. /** Reinhard */
  78639. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78640. /** HejiDawson */
  78641. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78642. /** Photographic */
  78643. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78644. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78645. ;
  78646. /**
  78647. * Defines a post process to apply tone mapping
  78648. */
  78649. var TonemapPostProcess = /** @class */ (function (_super) {
  78650. __extends(TonemapPostProcess, _super);
  78651. /**
  78652. * Creates a new TonemapPostProcess
  78653. * @param name defines the name of the postprocess
  78654. * @param _operator defines the operator to use
  78655. * @param exposureAdjustment defines the required exposure adjustement
  78656. * @param camera defines the camera to use (can be null)
  78657. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78658. * @param engine defines the hosting engine (can be ignore if camera is set)
  78659. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78660. */
  78661. function TonemapPostProcess(name, _operator,
  78662. /** Defines the required exposure adjustement */
  78663. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78665. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78666. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78667. _this._operator = _operator;
  78668. _this.exposureAdjustment = exposureAdjustment;
  78669. var defines = "#define ";
  78670. if (_this._operator === TonemappingOperator.Hable)
  78671. defines += "HABLE_TONEMAPPING";
  78672. else if (_this._operator === TonemappingOperator.Reinhard)
  78673. defines += "REINHARD_TONEMAPPING";
  78674. else if (_this._operator === TonemappingOperator.HejiDawson)
  78675. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78676. else if (_this._operator === TonemappingOperator.Photographic)
  78677. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78678. //sadly a second call to create the effect.
  78679. _this.updateEffect(defines);
  78680. _this.onApply = function (effect) {
  78681. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78682. };
  78683. return _this;
  78684. }
  78685. return TonemapPostProcess;
  78686. }(BABYLON.PostProcess));
  78687. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78688. })(BABYLON || (BABYLON = {}));
  78689. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78690. var BABYLON;
  78691. (function (BABYLON) {
  78692. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78693. __extends(DisplayPassPostProcess, _super);
  78694. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78695. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78696. }
  78697. return DisplayPassPostProcess;
  78698. }(BABYLON.PostProcess));
  78699. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78700. })(BABYLON || (BABYLON = {}));
  78701. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78702. var BABYLON;
  78703. (function (BABYLON) {
  78704. var HighlightsPostProcess = /** @class */ (function (_super) {
  78705. __extends(HighlightsPostProcess, _super);
  78706. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78707. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78708. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78709. }
  78710. return HighlightsPostProcess;
  78711. }(BABYLON.PostProcess));
  78712. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78713. })(BABYLON || (BABYLON = {}));
  78714. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78715. var BABYLON;
  78716. (function (BABYLON) {
  78717. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78718. __extends(ImageProcessingPostProcess, _super);
  78719. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78720. if (camera === void 0) { camera = null; }
  78721. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78722. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78723. _this._fromLinearSpace = true;
  78724. /**
  78725. * Defines cache preventing GC.
  78726. */
  78727. _this._defines = {
  78728. IMAGEPROCESSING: false,
  78729. VIGNETTE: false,
  78730. VIGNETTEBLENDMODEMULTIPLY: false,
  78731. VIGNETTEBLENDMODEOPAQUE: false,
  78732. TONEMAPPING: false,
  78733. CONTRAST: false,
  78734. COLORCURVES: false,
  78735. COLORGRADING: false,
  78736. COLORGRADING3D: false,
  78737. FROMLINEARSPACE: false,
  78738. SAMPLER3DGREENDEPTH: false,
  78739. SAMPLER3DBGRMAP: false,
  78740. IMAGEPROCESSINGPOSTPROCESS: false,
  78741. EXPOSURE: false,
  78742. };
  78743. // Setup the configuration as forced by the constructor. This would then not force the
  78744. // scene materials output in linear space and let untouched the default forward pass.
  78745. if (imageProcessingConfiguration) {
  78746. imageProcessingConfiguration.applyByPostProcess = true;
  78747. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78748. // This will cause the shader to be compiled
  78749. _this.fromLinearSpace = false;
  78750. }
  78751. // Setup the default processing configuration to the scene.
  78752. else {
  78753. _this._attachImageProcessingConfiguration(null, true);
  78754. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78755. }
  78756. _this.onApply = function (effect) {
  78757. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78758. };
  78759. return _this;
  78760. }
  78761. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78762. /**
  78763. * Gets the image processing configuration used either in this material.
  78764. */
  78765. get: function () {
  78766. return this._imageProcessingConfiguration;
  78767. },
  78768. /**
  78769. * Sets the Default image processing configuration used either in the this material.
  78770. *
  78771. * If sets to null, the scene one is in use.
  78772. */
  78773. set: function (value) {
  78774. this._attachImageProcessingConfiguration(value);
  78775. },
  78776. enumerable: true,
  78777. configurable: true
  78778. });
  78779. /**
  78780. * Attaches a new image processing configuration to the PBR Material.
  78781. * @param configuration
  78782. */
  78783. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78784. var _this = this;
  78785. if (doNotBuild === void 0) { doNotBuild = false; }
  78786. if (configuration === this._imageProcessingConfiguration) {
  78787. return;
  78788. }
  78789. // Detaches observer.
  78790. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78791. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78792. }
  78793. // Pick the scene configuration if needed.
  78794. if (!configuration) {
  78795. var scene = null;
  78796. var engine = this.getEngine();
  78797. var camera = this.getCamera();
  78798. if (camera) {
  78799. scene = camera.getScene();
  78800. }
  78801. else if (engine && engine.scenes) {
  78802. var scenes = engine.scenes;
  78803. scene = scenes[scenes.length - 1];
  78804. }
  78805. else {
  78806. scene = BABYLON.Engine.LastCreatedScene;
  78807. }
  78808. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78809. }
  78810. else {
  78811. this._imageProcessingConfiguration = configuration;
  78812. }
  78813. // Attaches observer.
  78814. if (this._imageProcessingConfiguration) {
  78815. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78816. _this._updateParameters();
  78817. });
  78818. }
  78819. // Ensure the effect will be rebuilt.
  78820. if (!doNotBuild) {
  78821. this._updateParameters();
  78822. }
  78823. };
  78824. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78825. /**
  78826. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78827. */
  78828. get: function () {
  78829. return this.imageProcessingConfiguration.colorCurves;
  78830. },
  78831. /**
  78832. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78833. */
  78834. set: function (value) {
  78835. this.imageProcessingConfiguration.colorCurves = value;
  78836. },
  78837. enumerable: true,
  78838. configurable: true
  78839. });
  78840. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78841. /**
  78842. * Gets wether the color curves effect is enabled.
  78843. */
  78844. get: function () {
  78845. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78846. },
  78847. /**
  78848. * Sets wether the color curves effect is enabled.
  78849. */
  78850. set: function (value) {
  78851. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78852. },
  78853. enumerable: true,
  78854. configurable: true
  78855. });
  78856. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78857. /**
  78858. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78859. */
  78860. get: function () {
  78861. return this.imageProcessingConfiguration.colorGradingTexture;
  78862. },
  78863. /**
  78864. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78865. */
  78866. set: function (value) {
  78867. this.imageProcessingConfiguration.colorGradingTexture = value;
  78868. },
  78869. enumerable: true,
  78870. configurable: true
  78871. });
  78872. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78873. /**
  78874. * Gets wether the color grading effect is enabled.
  78875. */
  78876. get: function () {
  78877. return this.imageProcessingConfiguration.colorGradingEnabled;
  78878. },
  78879. /**
  78880. * Gets wether the color grading effect is enabled.
  78881. */
  78882. set: function (value) {
  78883. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78884. },
  78885. enumerable: true,
  78886. configurable: true
  78887. });
  78888. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78889. /**
  78890. * Gets exposure used in the effect.
  78891. */
  78892. get: function () {
  78893. return this.imageProcessingConfiguration.exposure;
  78894. },
  78895. /**
  78896. * Sets exposure used in the effect.
  78897. */
  78898. set: function (value) {
  78899. this.imageProcessingConfiguration.exposure = value;
  78900. },
  78901. enumerable: true,
  78902. configurable: true
  78903. });
  78904. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78905. /**
  78906. * Gets wether tonemapping is enabled or not.
  78907. */
  78908. get: function () {
  78909. return this._imageProcessingConfiguration.toneMappingEnabled;
  78910. },
  78911. /**
  78912. * Sets wether tonemapping is enabled or not
  78913. */
  78914. set: function (value) {
  78915. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78916. },
  78917. enumerable: true,
  78918. configurable: true
  78919. });
  78920. ;
  78921. ;
  78922. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78923. /**
  78924. * Gets contrast used in the effect.
  78925. */
  78926. get: function () {
  78927. return this.imageProcessingConfiguration.contrast;
  78928. },
  78929. /**
  78930. * Sets contrast used in the effect.
  78931. */
  78932. set: function (value) {
  78933. this.imageProcessingConfiguration.contrast = value;
  78934. },
  78935. enumerable: true,
  78936. configurable: true
  78937. });
  78938. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78939. /**
  78940. * Gets Vignette stretch size.
  78941. */
  78942. get: function () {
  78943. return this.imageProcessingConfiguration.vignetteStretch;
  78944. },
  78945. /**
  78946. * Sets Vignette stretch size.
  78947. */
  78948. set: function (value) {
  78949. this.imageProcessingConfiguration.vignetteStretch = value;
  78950. },
  78951. enumerable: true,
  78952. configurable: true
  78953. });
  78954. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78955. /**
  78956. * Gets Vignette centre X Offset.
  78957. */
  78958. get: function () {
  78959. return this.imageProcessingConfiguration.vignetteCentreX;
  78960. },
  78961. /**
  78962. * Sets Vignette centre X Offset.
  78963. */
  78964. set: function (value) {
  78965. this.imageProcessingConfiguration.vignetteCentreX = value;
  78966. },
  78967. enumerable: true,
  78968. configurable: true
  78969. });
  78970. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78971. /**
  78972. * Gets Vignette centre Y Offset.
  78973. */
  78974. get: function () {
  78975. return this.imageProcessingConfiguration.vignetteCentreY;
  78976. },
  78977. /**
  78978. * Sets Vignette centre Y Offset.
  78979. */
  78980. set: function (value) {
  78981. this.imageProcessingConfiguration.vignetteCentreY = value;
  78982. },
  78983. enumerable: true,
  78984. configurable: true
  78985. });
  78986. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78987. /**
  78988. * Gets Vignette weight or intensity of the vignette effect.
  78989. */
  78990. get: function () {
  78991. return this.imageProcessingConfiguration.vignetteWeight;
  78992. },
  78993. /**
  78994. * Sets Vignette weight or intensity of the vignette effect.
  78995. */
  78996. set: function (value) {
  78997. this.imageProcessingConfiguration.vignetteWeight = value;
  78998. },
  78999. enumerable: true,
  79000. configurable: true
  79001. });
  79002. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79003. /**
  79004. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79005. * if vignetteEnabled is set to true.
  79006. */
  79007. get: function () {
  79008. return this.imageProcessingConfiguration.vignetteColor;
  79009. },
  79010. /**
  79011. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79012. * if vignetteEnabled is set to true.
  79013. */
  79014. set: function (value) {
  79015. this.imageProcessingConfiguration.vignetteColor = value;
  79016. },
  79017. enumerable: true,
  79018. configurable: true
  79019. });
  79020. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79021. /**
  79022. * Gets Camera field of view used by the Vignette effect.
  79023. */
  79024. get: function () {
  79025. return this.imageProcessingConfiguration.vignetteCameraFov;
  79026. },
  79027. /**
  79028. * Sets Camera field of view used by the Vignette effect.
  79029. */
  79030. set: function (value) {
  79031. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79032. },
  79033. enumerable: true,
  79034. configurable: true
  79035. });
  79036. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79037. /**
  79038. * Gets the vignette blend mode allowing different kind of effect.
  79039. */
  79040. get: function () {
  79041. return this.imageProcessingConfiguration.vignetteBlendMode;
  79042. },
  79043. /**
  79044. * Sets the vignette blend mode allowing different kind of effect.
  79045. */
  79046. set: function (value) {
  79047. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79048. },
  79049. enumerable: true,
  79050. configurable: true
  79051. });
  79052. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79053. /**
  79054. * Gets wether the vignette effect is enabled.
  79055. */
  79056. get: function () {
  79057. return this.imageProcessingConfiguration.vignetteEnabled;
  79058. },
  79059. /**
  79060. * Sets wether the vignette effect is enabled.
  79061. */
  79062. set: function (value) {
  79063. this.imageProcessingConfiguration.vignetteEnabled = value;
  79064. },
  79065. enumerable: true,
  79066. configurable: true
  79067. });
  79068. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79069. /**
  79070. * Gets wether the input of the processing is in Gamma or Linear Space.
  79071. */
  79072. get: function () {
  79073. return this._fromLinearSpace;
  79074. },
  79075. /**
  79076. * Sets wether the input of the processing is in Gamma or Linear Space.
  79077. */
  79078. set: function (value) {
  79079. if (this._fromLinearSpace === value) {
  79080. return;
  79081. }
  79082. this._fromLinearSpace = value;
  79083. this._updateParameters();
  79084. },
  79085. enumerable: true,
  79086. configurable: true
  79087. });
  79088. ImageProcessingPostProcess.prototype.getClassName = function () {
  79089. return "ImageProcessingPostProcess";
  79090. };
  79091. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79092. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79093. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79094. var defines = "";
  79095. for (var define in this._defines) {
  79096. if (this._defines[define]) {
  79097. defines += "#define " + define + ";\r\n";
  79098. }
  79099. }
  79100. var samplers = ["textureSampler"];
  79101. var uniforms = ["scale"];
  79102. if (BABYLON.ImageProcessingConfiguration) {
  79103. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79104. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79105. }
  79106. this.updateEffect(defines, uniforms, samplers);
  79107. };
  79108. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79109. _super.prototype.dispose.call(this, camera);
  79110. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79111. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79112. }
  79113. if (this._imageProcessingConfiguration) {
  79114. this.imageProcessingConfiguration.applyByPostProcess = false;
  79115. }
  79116. };
  79117. __decorate([
  79118. BABYLON.serialize()
  79119. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79120. return ImageProcessingPostProcess;
  79121. }(BABYLON.PostProcess));
  79122. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79123. })(BABYLON || (BABYLON = {}));
  79124. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79125. var BABYLON;
  79126. (function (BABYLON) {
  79127. /**
  79128. * Class used to store bone information
  79129. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79130. */
  79131. var Bone = /** @class */ (function (_super) {
  79132. __extends(Bone, _super);
  79133. /**
  79134. * Create a new bone
  79135. * @param name defines the bone name
  79136. * @param skeleton defines the parent skeleton
  79137. * @param parentBone defines the parent (can be null if the bone is the root)
  79138. * @param localMatrix defines the local matrix
  79139. * @param restPose defines the rest pose matrix
  79140. * @param baseMatrix defines the base matrix
  79141. * @param index defines index of the bone in the hiearchy
  79142. */
  79143. function Bone(
  79144. /**
  79145. * defines the bone name
  79146. */
  79147. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79148. if (parentBone === void 0) { parentBone = null; }
  79149. if (localMatrix === void 0) { localMatrix = null; }
  79150. if (restPose === void 0) { restPose = null; }
  79151. if (baseMatrix === void 0) { baseMatrix = null; }
  79152. if (index === void 0) { index = null; }
  79153. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79154. _this.name = name;
  79155. /**
  79156. * Gets the list of child bones
  79157. */
  79158. _this.children = new Array();
  79159. /** Gets the animations associated with this bone */
  79160. _this.animations = new Array();
  79161. /**
  79162. * @hidden Internal only
  79163. * Set this value to map this bone to a different index in the transform matrices
  79164. * Set this value to -1 to exclude the bone from the transform matrices
  79165. */
  79166. _this._index = null;
  79167. _this._absoluteTransform = new BABYLON.Matrix();
  79168. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79169. _this._scalingDeterminant = 1;
  79170. _this._worldTransform = new BABYLON.Matrix();
  79171. _this._needToDecompose = true;
  79172. _this._needToCompose = false;
  79173. _this._skeleton = skeleton;
  79174. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79175. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79176. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79177. _this._index = index;
  79178. skeleton.bones.push(_this);
  79179. _this.setParent(parentBone, false);
  79180. if (baseMatrix || localMatrix) {
  79181. _this._updateDifferenceMatrix();
  79182. }
  79183. return _this;
  79184. }
  79185. Object.defineProperty(Bone.prototype, "_matrix", {
  79186. /** @hidden */
  79187. get: function () {
  79188. this._compose();
  79189. return this._localMatrix;
  79190. },
  79191. /** @hidden */
  79192. set: function (value) {
  79193. this._localMatrix.copyFrom(value);
  79194. this._needToDecompose = true;
  79195. },
  79196. enumerable: true,
  79197. configurable: true
  79198. });
  79199. // Members
  79200. /**
  79201. * Gets the parent skeleton
  79202. * @returns a skeleton
  79203. */
  79204. Bone.prototype.getSkeleton = function () {
  79205. return this._skeleton;
  79206. };
  79207. /**
  79208. * Gets parent bone
  79209. * @returns a bone or null if the bone is the root of the bone hierarchy
  79210. */
  79211. Bone.prototype.getParent = function () {
  79212. return this._parent;
  79213. };
  79214. /**
  79215. * Sets the parent bone
  79216. * @param parent defines the parent (can be null if the bone is the root)
  79217. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79218. */
  79219. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79220. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79221. if (this._parent === parent) {
  79222. return;
  79223. }
  79224. if (this._parent) {
  79225. var index = this._parent.children.indexOf(this);
  79226. if (index !== -1) {
  79227. this._parent.children.splice(index, 1);
  79228. }
  79229. }
  79230. this._parent = parent;
  79231. if (this._parent) {
  79232. this._parent.children.push(this);
  79233. }
  79234. if (updateDifferenceMatrix) {
  79235. this._updateDifferenceMatrix();
  79236. }
  79237. this.markAsDirty();
  79238. };
  79239. /**
  79240. * Gets the local matrix
  79241. * @returns a matrix
  79242. */
  79243. Bone.prototype.getLocalMatrix = function () {
  79244. this._compose();
  79245. return this._localMatrix;
  79246. };
  79247. /**
  79248. * Gets the base matrix (initial matrix which remains unchanged)
  79249. * @returns a matrix
  79250. */
  79251. Bone.prototype.getBaseMatrix = function () {
  79252. return this._baseMatrix;
  79253. };
  79254. /**
  79255. * Gets the rest pose matrix
  79256. * @returns a matrix
  79257. */
  79258. Bone.prototype.getRestPose = function () {
  79259. return this._restPose;
  79260. };
  79261. /**
  79262. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79263. */
  79264. Bone.prototype.getWorldMatrix = function () {
  79265. return this._worldTransform;
  79266. };
  79267. /**
  79268. * Sets the local matrix to rest pose matrix
  79269. */
  79270. Bone.prototype.returnToRest = function () {
  79271. this.updateMatrix(this._restPose.clone());
  79272. };
  79273. /**
  79274. * Gets the inverse of the absolute transform matrix.
  79275. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79276. * @returns a matrix
  79277. */
  79278. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79279. return this._invertedAbsoluteTransform;
  79280. };
  79281. /**
  79282. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79283. * @returns a matrix
  79284. */
  79285. Bone.prototype.getAbsoluteTransform = function () {
  79286. return this._absoluteTransform;
  79287. };
  79288. Object.defineProperty(Bone.prototype, "position", {
  79289. // Properties (matches AbstractMesh properties)
  79290. /** Gets or sets current position (in local space) */
  79291. get: function () {
  79292. this._decompose();
  79293. return this._localPosition;
  79294. },
  79295. set: function (newPosition) {
  79296. this._decompose();
  79297. this._localPosition.copyFrom(newPosition);
  79298. this._markAsDirtyAndCompose();
  79299. },
  79300. enumerable: true,
  79301. configurable: true
  79302. });
  79303. Object.defineProperty(Bone.prototype, "rotation", {
  79304. /** Gets or sets current rotation (in local space) */
  79305. get: function () {
  79306. return this.getRotation();
  79307. },
  79308. set: function (newRotation) {
  79309. this.setRotation(newRotation);
  79310. },
  79311. enumerable: true,
  79312. configurable: true
  79313. });
  79314. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79315. /** Gets or sets current rotation quaternion (in local space) */
  79316. get: function () {
  79317. this._decompose();
  79318. return this._localRotation;
  79319. },
  79320. set: function (newRotation) {
  79321. this.setRotationQuaternion(newRotation);
  79322. },
  79323. enumerable: true,
  79324. configurable: true
  79325. });
  79326. Object.defineProperty(Bone.prototype, "scaling", {
  79327. /** Gets or sets current scaling (in local space) */
  79328. get: function () {
  79329. return this.getScale();
  79330. },
  79331. set: function (newScaling) {
  79332. this.setScale(newScaling);
  79333. },
  79334. enumerable: true,
  79335. configurable: true
  79336. });
  79337. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79338. /**
  79339. * Gets the animation properties override
  79340. */
  79341. get: function () {
  79342. return this._skeleton.animationPropertiesOverride;
  79343. },
  79344. enumerable: true,
  79345. configurable: true
  79346. });
  79347. // Methods
  79348. Bone.prototype._decompose = function () {
  79349. if (!this._needToDecompose) {
  79350. return;
  79351. }
  79352. this._needToDecompose = false;
  79353. if (!this._localScaling) {
  79354. this._localScaling = BABYLON.Vector3.Zero();
  79355. this._localRotation = BABYLON.Quaternion.Zero();
  79356. this._localPosition = BABYLON.Vector3.Zero();
  79357. }
  79358. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79359. };
  79360. Bone.prototype._compose = function () {
  79361. if (!this._needToCompose) {
  79362. return;
  79363. }
  79364. this._needToCompose = false;
  79365. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79366. };
  79367. /**
  79368. * Update the base and local matrices
  79369. * @param matrix defines the new base or local matrix
  79370. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79371. * @param updateLocalMatrix defines if the local matrix should be updated
  79372. */
  79373. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79374. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79375. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79376. this._baseMatrix.copyFrom(matrix);
  79377. if (updateDifferenceMatrix) {
  79378. this._updateDifferenceMatrix();
  79379. }
  79380. if (updateLocalMatrix) {
  79381. this._localMatrix.copyFrom(matrix);
  79382. this._markAsDirtyAndDecompose();
  79383. }
  79384. else {
  79385. this.markAsDirty();
  79386. }
  79387. };
  79388. /** @hidden */
  79389. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79390. if (updateChildren === void 0) { updateChildren = true; }
  79391. if (!rootMatrix) {
  79392. rootMatrix = this._baseMatrix;
  79393. }
  79394. if (this._parent) {
  79395. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79396. }
  79397. else {
  79398. this._absoluteTransform.copyFrom(rootMatrix);
  79399. }
  79400. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79401. if (updateChildren) {
  79402. for (var index = 0; index < this.children.length; index++) {
  79403. this.children[index]._updateDifferenceMatrix();
  79404. }
  79405. }
  79406. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79407. };
  79408. /**
  79409. * Flag the bone as dirty (Forcing it to update everything)
  79410. */
  79411. Bone.prototype.markAsDirty = function () {
  79412. this._currentRenderId++;
  79413. this._childRenderId++;
  79414. this._skeleton._markAsDirty();
  79415. };
  79416. Bone.prototype._markAsDirtyAndCompose = function () {
  79417. this.markAsDirty();
  79418. this._needToCompose = true;
  79419. };
  79420. Bone.prototype._markAsDirtyAndDecompose = function () {
  79421. this.markAsDirty();
  79422. this._needToDecompose = true;
  79423. };
  79424. /**
  79425. * Copy an animation range from another bone
  79426. * @param source defines the source bone
  79427. * @param rangeName defines the range name to copy
  79428. * @param frameOffset defines the frame offset
  79429. * @param rescaleAsRequired defines if rescaling must be applied if required
  79430. * @param skelDimensionsRatio defines the scaling ratio
  79431. * @returns true if operation was successful
  79432. */
  79433. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79434. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79435. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79436. // all animation may be coming from a library skeleton, so may need to create animation
  79437. if (this.animations.length === 0) {
  79438. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79439. this.animations[0].setKeys([]);
  79440. }
  79441. // get animation info / verify there is such a range from the source bone
  79442. var sourceRange = source.animations[0].getRange(rangeName);
  79443. if (!sourceRange) {
  79444. return false;
  79445. }
  79446. var from = sourceRange.from;
  79447. var to = sourceRange.to;
  79448. var sourceKeys = source.animations[0].getKeys();
  79449. // rescaling prep
  79450. var sourceBoneLength = source.length;
  79451. var sourceParent = source.getParent();
  79452. var parent = this.getParent();
  79453. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79454. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79455. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79456. var destKeys = this.animations[0].getKeys();
  79457. // loop vars declaration
  79458. var orig;
  79459. var origTranslation;
  79460. var mat;
  79461. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79462. orig = sourceKeys[key];
  79463. if (orig.frame >= from && orig.frame <= to) {
  79464. if (rescaleAsRequired) {
  79465. mat = orig.value.clone();
  79466. // scale based on parent ratio, when bone has parent
  79467. if (parentScalingReqd) {
  79468. origTranslation = mat.getTranslation();
  79469. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79470. // scale based on skeleton dimension ratio when root bone, and value is passed
  79471. }
  79472. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79473. origTranslation = mat.getTranslation();
  79474. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79475. // use original when root bone, and no data for skelDimensionsRatio
  79476. }
  79477. else {
  79478. mat = orig.value;
  79479. }
  79480. }
  79481. else {
  79482. mat = orig.value;
  79483. }
  79484. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79485. }
  79486. }
  79487. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79488. return true;
  79489. };
  79490. /**
  79491. * Translate the bone in local or world space
  79492. * @param vec The amount to translate the bone
  79493. * @param space The space that the translation is in
  79494. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79495. */
  79496. Bone.prototype.translate = function (vec, space, mesh) {
  79497. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79498. var lm = this.getLocalMatrix();
  79499. if (space == BABYLON.Space.LOCAL) {
  79500. lm.m[12] += vec.x;
  79501. lm.m[13] += vec.y;
  79502. lm.m[14] += vec.z;
  79503. }
  79504. else {
  79505. var wm = null;
  79506. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79507. if (mesh) {
  79508. wm = mesh.getWorldMatrix();
  79509. }
  79510. this._skeleton.computeAbsoluteTransforms();
  79511. var tmat = Bone._tmpMats[0];
  79512. var tvec = Bone._tmpVecs[0];
  79513. if (this._parent) {
  79514. if (mesh && wm) {
  79515. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79516. tmat.multiplyToRef(wm, tmat);
  79517. }
  79518. else {
  79519. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79520. }
  79521. }
  79522. tmat.m[12] = 0;
  79523. tmat.m[13] = 0;
  79524. tmat.m[14] = 0;
  79525. tmat.invert();
  79526. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79527. lm.m[12] += tvec.x;
  79528. lm.m[13] += tvec.y;
  79529. lm.m[14] += tvec.z;
  79530. }
  79531. this._markAsDirtyAndDecompose();
  79532. };
  79533. /**
  79534. * Set the postion of the bone in local or world space
  79535. * @param position The position to set the bone
  79536. * @param space The space that the position is in
  79537. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79538. */
  79539. Bone.prototype.setPosition = function (position, space, mesh) {
  79540. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79541. var lm = this.getLocalMatrix();
  79542. if (space == BABYLON.Space.LOCAL) {
  79543. lm.m[12] = position.x;
  79544. lm.m[13] = position.y;
  79545. lm.m[14] = position.z;
  79546. }
  79547. else {
  79548. var wm = null;
  79549. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79550. if (mesh) {
  79551. wm = mesh.getWorldMatrix();
  79552. }
  79553. this._skeleton.computeAbsoluteTransforms();
  79554. var tmat = Bone._tmpMats[0];
  79555. var vec = Bone._tmpVecs[0];
  79556. if (this._parent) {
  79557. if (mesh && wm) {
  79558. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79559. tmat.multiplyToRef(wm, tmat);
  79560. }
  79561. else {
  79562. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79563. }
  79564. }
  79565. tmat.invert();
  79566. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79567. lm.m[12] = vec.x;
  79568. lm.m[13] = vec.y;
  79569. lm.m[14] = vec.z;
  79570. }
  79571. this._markAsDirtyAndDecompose();
  79572. };
  79573. /**
  79574. * Set the absolute position of the bone (world space)
  79575. * @param position The position to set the bone
  79576. * @param mesh The mesh that this bone is attached to
  79577. */
  79578. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79579. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79580. };
  79581. /**
  79582. * Scale the bone on the x, y and z axes (in local space)
  79583. * @param x The amount to scale the bone on the x axis
  79584. * @param y The amount to scale the bone on the y axis
  79585. * @param z The amount to scale the bone on the z axis
  79586. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79587. */
  79588. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79589. if (scaleChildren === void 0) { scaleChildren = false; }
  79590. var locMat = this.getLocalMatrix();
  79591. // Apply new scaling on top of current local matrix
  79592. var scaleMat = Bone._tmpMats[0];
  79593. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79594. scaleMat.multiplyToRef(locMat, locMat);
  79595. // Invert scaling matrix and apply the inverse to all children
  79596. scaleMat.invert();
  79597. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79598. var child = _a[_i];
  79599. var cm = child.getLocalMatrix();
  79600. cm.multiplyToRef(scaleMat, cm);
  79601. cm.m[12] *= x;
  79602. cm.m[13] *= y;
  79603. cm.m[14] *= z;
  79604. child._markAsDirtyAndDecompose();
  79605. }
  79606. this._markAsDirtyAndDecompose();
  79607. if (scaleChildren) {
  79608. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79609. var child = _c[_b];
  79610. child.scale(x, y, z, scaleChildren);
  79611. }
  79612. }
  79613. };
  79614. /**
  79615. * Set the bone scaling in local space
  79616. * @param scale defines the scaling vector
  79617. */
  79618. Bone.prototype.setScale = function (scale) {
  79619. this._decompose();
  79620. this._localScaling.copyFrom(scale);
  79621. this._markAsDirtyAndCompose();
  79622. };
  79623. /**
  79624. * Gets the current scaling in local space
  79625. * @returns the current scaling vector
  79626. */
  79627. Bone.prototype.getScale = function () {
  79628. this._decompose();
  79629. return this._localScaling;
  79630. };
  79631. /**
  79632. * Gets the current scaling in local space and stores it in a target vector
  79633. * @param result defines the target vector
  79634. */
  79635. Bone.prototype.getScaleToRef = function (result) {
  79636. this._decompose();
  79637. result.copyFrom(this._localScaling);
  79638. };
  79639. /**
  79640. * Set the yaw, pitch, and roll of the bone in local or world space
  79641. * @param yaw The rotation of the bone on the y axis
  79642. * @param pitch The rotation of the bone on the x axis
  79643. * @param roll The rotation of the bone on the z axis
  79644. * @param space The space that the axes of rotation are in
  79645. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79646. */
  79647. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79649. if (space === BABYLON.Space.LOCAL) {
  79650. var quat = Bone._tmpQuat;
  79651. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79652. this.setRotationQuaternion(quat, space, mesh);
  79653. return;
  79654. }
  79655. var rotMatInv = Bone._tmpMats[0];
  79656. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79657. return;
  79658. }
  79659. var rotMat = Bone._tmpMats[1];
  79660. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79661. rotMatInv.multiplyToRef(rotMat, rotMat);
  79662. this._rotateWithMatrix(rotMat, space, mesh);
  79663. };
  79664. /**
  79665. * Add a rotation to the bone on an axis in local or world space
  79666. * @param axis The axis to rotate the bone on
  79667. * @param amount The amount to rotate the bone
  79668. * @param space The space that the axis is in
  79669. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79670. */
  79671. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79673. var rmat = Bone._tmpMats[0];
  79674. rmat.m[12] = 0;
  79675. rmat.m[13] = 0;
  79676. rmat.m[14] = 0;
  79677. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79678. this._rotateWithMatrix(rmat, space, mesh);
  79679. };
  79680. /**
  79681. * Set the rotation of the bone to a particular axis angle in local or world space
  79682. * @param axis The axis to rotate the bone on
  79683. * @param angle The angle that the bone should be rotated to
  79684. * @param space The space that the axis is in
  79685. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79686. */
  79687. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79689. if (space === BABYLON.Space.LOCAL) {
  79690. var quat = Bone._tmpQuat;
  79691. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79692. this.setRotationQuaternion(quat, space, mesh);
  79693. return;
  79694. }
  79695. var rotMatInv = Bone._tmpMats[0];
  79696. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79697. return;
  79698. }
  79699. var rotMat = Bone._tmpMats[1];
  79700. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79701. rotMatInv.multiplyToRef(rotMat, rotMat);
  79702. this._rotateWithMatrix(rotMat, space, mesh);
  79703. };
  79704. /**
  79705. * Set the euler rotation of the bone in local of world space
  79706. * @param rotation The euler rotation that the bone should be set to
  79707. * @param space The space that the rotation is in
  79708. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79709. */
  79710. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79711. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79712. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79713. };
  79714. /**
  79715. * Set the quaternion rotation of the bone in local of world space
  79716. * @param quat The quaternion rotation that the bone should be set to
  79717. * @param space The space that the rotation is in
  79718. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79719. */
  79720. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79722. if (space === BABYLON.Space.LOCAL) {
  79723. this._decompose();
  79724. this._localRotation.copyFrom(quat);
  79725. this._markAsDirtyAndCompose();
  79726. return;
  79727. }
  79728. var rotMatInv = Bone._tmpMats[0];
  79729. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79730. return;
  79731. }
  79732. var rotMat = Bone._tmpMats[1];
  79733. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79734. rotMatInv.multiplyToRef(rotMat, rotMat);
  79735. this._rotateWithMatrix(rotMat, space, mesh);
  79736. };
  79737. /**
  79738. * Set the rotation matrix of the bone in local of world space
  79739. * @param rotMat The rotation matrix that the bone should be set to
  79740. * @param space The space that the rotation is in
  79741. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79742. */
  79743. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79744. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79745. if (space === BABYLON.Space.LOCAL) {
  79746. var quat = Bone._tmpQuat;
  79747. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79748. this.setRotationQuaternion(quat, space, mesh);
  79749. return;
  79750. }
  79751. var rotMatInv = Bone._tmpMats[0];
  79752. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79753. return;
  79754. }
  79755. var rotMat2 = Bone._tmpMats[1];
  79756. rotMat2.copyFrom(rotMat);
  79757. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79758. this._rotateWithMatrix(rotMat2, space, mesh);
  79759. };
  79760. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79761. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79762. var lmat = this.getLocalMatrix();
  79763. var lx = lmat.m[12];
  79764. var ly = lmat.m[13];
  79765. var lz = lmat.m[14];
  79766. var parent = this.getParent();
  79767. var parentScale = Bone._tmpMats[3];
  79768. var parentScaleInv = Bone._tmpMats[4];
  79769. if (parent && space == BABYLON.Space.WORLD) {
  79770. if (mesh) {
  79771. parentScale.copyFrom(mesh.getWorldMatrix());
  79772. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79773. }
  79774. else {
  79775. parentScale.copyFrom(parent.getAbsoluteTransform());
  79776. }
  79777. parentScaleInv.copyFrom(parentScale);
  79778. parentScaleInv.invert();
  79779. lmat.multiplyToRef(parentScale, lmat);
  79780. lmat.multiplyToRef(rmat, lmat);
  79781. lmat.multiplyToRef(parentScaleInv, lmat);
  79782. }
  79783. else {
  79784. if (space == BABYLON.Space.WORLD && mesh) {
  79785. parentScale.copyFrom(mesh.getWorldMatrix());
  79786. parentScaleInv.copyFrom(parentScale);
  79787. parentScaleInv.invert();
  79788. lmat.multiplyToRef(parentScale, lmat);
  79789. lmat.multiplyToRef(rmat, lmat);
  79790. lmat.multiplyToRef(parentScaleInv, lmat);
  79791. }
  79792. else {
  79793. lmat.multiplyToRef(rmat, lmat);
  79794. }
  79795. }
  79796. lmat.m[12] = lx;
  79797. lmat.m[13] = ly;
  79798. lmat.m[14] = lz;
  79799. this.computeAbsoluteTransforms();
  79800. this._markAsDirtyAndDecompose();
  79801. };
  79802. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79803. var scaleMatrix = Bone._tmpMats[2];
  79804. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79805. if (mesh) {
  79806. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79807. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79808. }
  79809. rotMatInv.invert();
  79810. if (isNaN(rotMatInv.m[0])) {
  79811. // Matrix failed to invert.
  79812. // This can happen if scale is zero for example.
  79813. return false;
  79814. }
  79815. scaleMatrix.m[0] *= this._scalingDeterminant;
  79816. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79817. return true;
  79818. };
  79819. /**
  79820. * Get the position of the bone in local or world space
  79821. * @param space The space that the returned position is in
  79822. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79823. * @returns The position of the bone
  79824. */
  79825. Bone.prototype.getPosition = function (space, mesh) {
  79826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79827. if (mesh === void 0) { mesh = null; }
  79828. var pos = BABYLON.Vector3.Zero();
  79829. this.getPositionToRef(space, mesh, pos);
  79830. return pos;
  79831. };
  79832. /**
  79833. * Copy the position of the bone to a vector3 in local or world space
  79834. * @param space The space that the returned position is in
  79835. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79836. * @param result The vector3 to copy the position to
  79837. */
  79838. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79839. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79840. if (space == BABYLON.Space.LOCAL) {
  79841. var lm = this.getLocalMatrix();
  79842. result.x = lm.m[12];
  79843. result.y = lm.m[13];
  79844. result.z = lm.m[14];
  79845. }
  79846. else {
  79847. var wm = null;
  79848. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79849. if (mesh) {
  79850. wm = mesh.getWorldMatrix();
  79851. }
  79852. this._skeleton.computeAbsoluteTransforms();
  79853. var tmat = Bone._tmpMats[0];
  79854. if (mesh && wm) {
  79855. tmat.copyFrom(this.getAbsoluteTransform());
  79856. tmat.multiplyToRef(wm, tmat);
  79857. }
  79858. else {
  79859. tmat = this.getAbsoluteTransform();
  79860. }
  79861. result.x = tmat.m[12];
  79862. result.y = tmat.m[13];
  79863. result.z = tmat.m[14];
  79864. }
  79865. };
  79866. /**
  79867. * Get the absolute position of the bone (world space)
  79868. * @param mesh The mesh that this bone is attached to
  79869. * @returns The absolute position of the bone
  79870. */
  79871. Bone.prototype.getAbsolutePosition = function (mesh) {
  79872. if (mesh === void 0) { mesh = null; }
  79873. var pos = BABYLON.Vector3.Zero();
  79874. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79875. return pos;
  79876. };
  79877. /**
  79878. * Copy the absolute position of the bone (world space) to the result param
  79879. * @param mesh The mesh that this bone is attached to
  79880. * @param result The vector3 to copy the absolute position to
  79881. */
  79882. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79883. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79884. };
  79885. /**
  79886. * Compute the absolute transforms of this bone and its children
  79887. */
  79888. Bone.prototype.computeAbsoluteTransforms = function () {
  79889. this._compose();
  79890. if (this._parent) {
  79891. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79892. }
  79893. else {
  79894. this._absoluteTransform.copyFrom(this._localMatrix);
  79895. var poseMatrix = this._skeleton.getPoseMatrix();
  79896. if (poseMatrix) {
  79897. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79898. }
  79899. }
  79900. var children = this.children;
  79901. var len = children.length;
  79902. for (var i = 0; i < len; i++) {
  79903. children[i].computeAbsoluteTransforms();
  79904. }
  79905. };
  79906. /**
  79907. * Get the world direction from an axis that is in the local space of the bone
  79908. * @param localAxis The local direction that is used to compute the world direction
  79909. * @param mesh The mesh that this bone is attached to
  79910. * @returns The world direction
  79911. */
  79912. Bone.prototype.getDirection = function (localAxis, mesh) {
  79913. if (mesh === void 0) { mesh = null; }
  79914. var result = BABYLON.Vector3.Zero();
  79915. this.getDirectionToRef(localAxis, mesh, result);
  79916. return result;
  79917. };
  79918. /**
  79919. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79920. * @param localAxis The local direction that is used to compute the world direction
  79921. * @param mesh The mesh that this bone is attached to
  79922. * @param result The vector3 that the world direction will be copied to
  79923. */
  79924. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79925. if (mesh === void 0) { mesh = null; }
  79926. var wm = null;
  79927. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79928. if (mesh) {
  79929. wm = mesh.getWorldMatrix();
  79930. }
  79931. this._skeleton.computeAbsoluteTransforms();
  79932. var mat = Bone._tmpMats[0];
  79933. mat.copyFrom(this.getAbsoluteTransform());
  79934. if (mesh && wm) {
  79935. mat.multiplyToRef(wm, mat);
  79936. }
  79937. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79938. result.normalize();
  79939. };
  79940. /**
  79941. * Get the euler rotation of the bone in local or world space
  79942. * @param space The space that the rotation should be in
  79943. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79944. * @returns The euler rotation
  79945. */
  79946. Bone.prototype.getRotation = function (space, mesh) {
  79947. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79948. if (mesh === void 0) { mesh = null; }
  79949. var result = BABYLON.Vector3.Zero();
  79950. this.getRotationToRef(space, mesh, result);
  79951. return result;
  79952. };
  79953. /**
  79954. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79955. * @param space The space that the rotation should be in
  79956. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79957. * @param result The vector3 that the rotation should be copied to
  79958. */
  79959. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79961. if (mesh === void 0) { mesh = null; }
  79962. var quat = Bone._tmpQuat;
  79963. this.getRotationQuaternionToRef(space, mesh, quat);
  79964. quat.toEulerAnglesToRef(result);
  79965. };
  79966. /**
  79967. * Get the quaternion rotation of the bone in either local or world space
  79968. * @param space The space that the rotation should be in
  79969. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79970. * @returns The quaternion rotation
  79971. */
  79972. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79974. if (mesh === void 0) { mesh = null; }
  79975. var result = BABYLON.Quaternion.Identity();
  79976. this.getRotationQuaternionToRef(space, mesh, result);
  79977. return result;
  79978. };
  79979. /**
  79980. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79981. * @param space The space that the rotation should be in
  79982. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79983. * @param result The quaternion that the rotation should be copied to
  79984. */
  79985. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79986. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79987. if (mesh === void 0) { mesh = null; }
  79988. if (space == BABYLON.Space.LOCAL) {
  79989. this._decompose();
  79990. result.copyFrom(this._localRotation);
  79991. }
  79992. else {
  79993. var mat = Bone._tmpMats[0];
  79994. var amat = this.getAbsoluteTransform();
  79995. if (mesh) {
  79996. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79997. }
  79998. else {
  79999. mat.copyFrom(amat);
  80000. }
  80001. mat.m[0] *= this._scalingDeterminant;
  80002. mat.m[1] *= this._scalingDeterminant;
  80003. mat.m[2] *= this._scalingDeterminant;
  80004. mat.decompose(undefined, result, undefined);
  80005. }
  80006. };
  80007. /**
  80008. * Get the rotation matrix of the bone in local or world space
  80009. * @param space The space that the rotation should be in
  80010. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80011. * @returns The rotation matrix
  80012. */
  80013. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80015. var result = BABYLON.Matrix.Identity();
  80016. this.getRotationMatrixToRef(space, mesh, result);
  80017. return result;
  80018. };
  80019. /**
  80020. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80021. * @param space The space that the rotation should be in
  80022. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80023. * @param result The quaternion that the rotation should be copied to
  80024. */
  80025. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80027. if (space == BABYLON.Space.LOCAL) {
  80028. this.getLocalMatrix().getRotationMatrixToRef(result);
  80029. }
  80030. else {
  80031. var mat = Bone._tmpMats[0];
  80032. var amat = this.getAbsoluteTransform();
  80033. if (mesh) {
  80034. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80035. }
  80036. else {
  80037. mat.copyFrom(amat);
  80038. }
  80039. mat.m[0] *= this._scalingDeterminant;
  80040. mat.m[1] *= this._scalingDeterminant;
  80041. mat.m[2] *= this._scalingDeterminant;
  80042. mat.getRotationMatrixToRef(result);
  80043. }
  80044. };
  80045. /**
  80046. * Get the world position of a point that is in the local space of the bone
  80047. * @param position The local position
  80048. * @param mesh The mesh that this bone is attached to
  80049. * @returns The world position
  80050. */
  80051. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80052. if (mesh === void 0) { mesh = null; }
  80053. var result = BABYLON.Vector3.Zero();
  80054. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80055. return result;
  80056. };
  80057. /**
  80058. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80059. * @param position The local position
  80060. * @param mesh The mesh that this bone is attached to
  80061. * @param result The vector3 that the world position should be copied to
  80062. */
  80063. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80064. if (mesh === void 0) { mesh = null; }
  80065. var wm = null;
  80066. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80067. if (mesh) {
  80068. wm = mesh.getWorldMatrix();
  80069. }
  80070. this._skeleton.computeAbsoluteTransforms();
  80071. var tmat = Bone._tmpMats[0];
  80072. if (mesh && wm) {
  80073. tmat.copyFrom(this.getAbsoluteTransform());
  80074. tmat.multiplyToRef(wm, tmat);
  80075. }
  80076. else {
  80077. tmat = this.getAbsoluteTransform();
  80078. }
  80079. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80080. };
  80081. /**
  80082. * Get the local position of a point that is in world space
  80083. * @param position The world position
  80084. * @param mesh The mesh that this bone is attached to
  80085. * @returns The local position
  80086. */
  80087. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80088. if (mesh === void 0) { mesh = null; }
  80089. var result = BABYLON.Vector3.Zero();
  80090. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80091. return result;
  80092. };
  80093. /**
  80094. * Get the local position of a point that is in world space and copy it to the result param
  80095. * @param position The world position
  80096. * @param mesh The mesh that this bone is attached to
  80097. * @param result The vector3 that the local position should be copied to
  80098. */
  80099. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80100. if (mesh === void 0) { mesh = null; }
  80101. var wm = null;
  80102. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80103. if (mesh) {
  80104. wm = mesh.getWorldMatrix();
  80105. }
  80106. this._skeleton.computeAbsoluteTransforms();
  80107. var tmat = Bone._tmpMats[0];
  80108. tmat.copyFrom(this.getAbsoluteTransform());
  80109. if (mesh && wm) {
  80110. tmat.multiplyToRef(wm, tmat);
  80111. }
  80112. tmat.invert();
  80113. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80114. };
  80115. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80116. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80117. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80118. return Bone;
  80119. }(BABYLON.Node));
  80120. BABYLON.Bone = Bone;
  80121. })(BABYLON || (BABYLON = {}));
  80122. //# sourceMappingURL=babylon.bone.js.map
  80123. var BABYLON;
  80124. (function (BABYLON) {
  80125. /**
  80126. * Class used to apply inverse kinematics to bones
  80127. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80128. */
  80129. var BoneIKController = /** @class */ (function () {
  80130. /**
  80131. * Creates a new BoneIKController
  80132. * @param mesh defines the mesh to control
  80133. * @param bone defines the bone to control
  80134. * @param options defines options to set up the controller
  80135. */
  80136. function BoneIKController(mesh, bone, options) {
  80137. /**
  80138. * Gets or sets the target position
  80139. */
  80140. this.targetPosition = BABYLON.Vector3.Zero();
  80141. /**
  80142. * Gets or sets the pole target position
  80143. */
  80144. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80145. /**
  80146. * Gets or sets the pole target local offset
  80147. */
  80148. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80149. /**
  80150. * Gets or sets the pole angle
  80151. */
  80152. this.poleAngle = 0;
  80153. /**
  80154. * 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)
  80155. */
  80156. this.slerpAmount = 1;
  80157. this._bone1Quat = BABYLON.Quaternion.Identity();
  80158. this._bone1Mat = BABYLON.Matrix.Identity();
  80159. this._bone2Ang = Math.PI;
  80160. this._maxAngle = Math.PI;
  80161. this._rightHandedSystem = false;
  80162. this._bendAxis = BABYLON.Vector3.Right();
  80163. this._slerping = false;
  80164. this._adjustRoll = 0;
  80165. this._bone2 = bone;
  80166. this._bone1 = bone.getParent();
  80167. if (!this._bone1) {
  80168. return;
  80169. }
  80170. this.mesh = mesh;
  80171. var bonePos = bone.getPosition();
  80172. if (bone.getAbsoluteTransform().determinant() > 0) {
  80173. this._rightHandedSystem = true;
  80174. this._bendAxis.x = 0;
  80175. this._bendAxis.y = 0;
  80176. this._bendAxis.z = -1;
  80177. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80178. this._adjustRoll = Math.PI * .5;
  80179. this._bendAxis.z = 1;
  80180. }
  80181. }
  80182. if (this._bone1.length) {
  80183. var boneScale1 = this._bone1.getScale();
  80184. var boneScale2 = this._bone2.getScale();
  80185. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80186. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80187. }
  80188. else if (this._bone1.children[0]) {
  80189. mesh.computeWorldMatrix(true);
  80190. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80191. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80192. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80193. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80194. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80195. }
  80196. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80197. this.maxAngle = Math.PI;
  80198. if (options) {
  80199. if (options.targetMesh) {
  80200. this.targetMesh = options.targetMesh;
  80201. this.targetMesh.computeWorldMatrix(true);
  80202. }
  80203. if (options.poleTargetMesh) {
  80204. this.poleTargetMesh = options.poleTargetMesh;
  80205. this.poleTargetMesh.computeWorldMatrix(true);
  80206. }
  80207. else if (options.poleTargetBone) {
  80208. this.poleTargetBone = options.poleTargetBone;
  80209. }
  80210. else if (this._bone1.getParent()) {
  80211. this.poleTargetBone = this._bone1.getParent();
  80212. }
  80213. if (options.poleTargetLocalOffset) {
  80214. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80215. }
  80216. if (options.poleAngle) {
  80217. this.poleAngle = options.poleAngle;
  80218. }
  80219. if (options.bendAxis) {
  80220. this._bendAxis.copyFrom(options.bendAxis);
  80221. }
  80222. if (options.maxAngle) {
  80223. this.maxAngle = options.maxAngle;
  80224. }
  80225. if (options.slerpAmount) {
  80226. this.slerpAmount = options.slerpAmount;
  80227. }
  80228. }
  80229. }
  80230. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80231. /**
  80232. * Gets or sets maximum allowed angle
  80233. */
  80234. get: function () {
  80235. return this._maxAngle;
  80236. },
  80237. set: function (value) {
  80238. this._setMaxAngle(value);
  80239. },
  80240. enumerable: true,
  80241. configurable: true
  80242. });
  80243. BoneIKController.prototype._setMaxAngle = function (ang) {
  80244. if (ang < 0) {
  80245. ang = 0;
  80246. }
  80247. if (ang > Math.PI || ang == undefined) {
  80248. ang = Math.PI;
  80249. }
  80250. this._maxAngle = ang;
  80251. var a = this._bone1Length;
  80252. var b = this._bone2Length;
  80253. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80254. };
  80255. /**
  80256. * Force the controller to update the bones
  80257. */
  80258. BoneIKController.prototype.update = function () {
  80259. var bone1 = this._bone1;
  80260. if (!bone1) {
  80261. return;
  80262. }
  80263. var target = this.targetPosition;
  80264. var poleTarget = this.poleTargetPosition;
  80265. var mat1 = BoneIKController._tmpMats[0];
  80266. var mat2 = BoneIKController._tmpMats[1];
  80267. if (this.targetMesh) {
  80268. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80269. }
  80270. if (this.poleTargetBone) {
  80271. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80272. }
  80273. else if (this.poleTargetMesh) {
  80274. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80275. }
  80276. var bonePos = BoneIKController._tmpVecs[0];
  80277. var zaxis = BoneIKController._tmpVecs[1];
  80278. var xaxis = BoneIKController._tmpVecs[2];
  80279. var yaxis = BoneIKController._tmpVecs[3];
  80280. var upAxis = BoneIKController._tmpVecs[4];
  80281. var _tmpQuat = BoneIKController._tmpQuat;
  80282. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80283. poleTarget.subtractToRef(bonePos, upAxis);
  80284. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80285. upAxis.y = 1;
  80286. }
  80287. else {
  80288. upAxis.normalize();
  80289. }
  80290. target.subtractToRef(bonePos, yaxis);
  80291. yaxis.normalize();
  80292. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80293. zaxis.normalize();
  80294. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80295. xaxis.normalize();
  80296. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80297. var a = this._bone1Length;
  80298. var b = this._bone2Length;
  80299. var c = BABYLON.Vector3.Distance(bonePos, target);
  80300. if (this._maxReach > 0) {
  80301. c = Math.min(this._maxReach, c);
  80302. }
  80303. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80304. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80305. if (acosa > 1) {
  80306. acosa = 1;
  80307. }
  80308. if (acosb > 1) {
  80309. acosb = 1;
  80310. }
  80311. if (acosa < -1) {
  80312. acosa = -1;
  80313. }
  80314. if (acosb < -1) {
  80315. acosb = -1;
  80316. }
  80317. var angA = Math.acos(acosa);
  80318. var angB = Math.acos(acosb);
  80319. var angC = -angA - angB;
  80320. if (this._rightHandedSystem) {
  80321. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80322. mat2.multiplyToRef(mat1, mat1);
  80323. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80324. mat2.multiplyToRef(mat1, mat1);
  80325. }
  80326. else {
  80327. var _tmpVec = BoneIKController._tmpVecs[5];
  80328. _tmpVec.copyFrom(this._bendAxis);
  80329. _tmpVec.x *= -1;
  80330. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80331. mat2.multiplyToRef(mat1, mat1);
  80332. }
  80333. if (this.poleAngle) {
  80334. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80335. mat1.multiplyToRef(mat2, mat1);
  80336. }
  80337. if (this._bone1) {
  80338. if (this.slerpAmount < 1) {
  80339. if (!this._slerping) {
  80340. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80341. }
  80342. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80343. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80344. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80345. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80346. this._slerping = true;
  80347. }
  80348. else {
  80349. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80350. this._bone1Mat.copyFrom(mat1);
  80351. this._slerping = false;
  80352. }
  80353. }
  80354. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80355. this._bone2Ang = angC;
  80356. };
  80357. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80358. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80359. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80360. return BoneIKController;
  80361. }());
  80362. BABYLON.BoneIKController = BoneIKController;
  80363. })(BABYLON || (BABYLON = {}));
  80364. //# sourceMappingURL=babylon.boneIKController.js.map
  80365. var BABYLON;
  80366. (function (BABYLON) {
  80367. /**
  80368. * Class used to make a bone look toward a point in space
  80369. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80370. */
  80371. var BoneLookController = /** @class */ (function () {
  80372. /**
  80373. * Create a BoneLookController
  80374. * @param mesh the mesh that the bone belongs to
  80375. * @param bone the bone that will be looking to the target
  80376. * @param target the target Vector3 to look at
  80377. * @param settings optional settings:
  80378. * * maxYaw: the maximum angle the bone will yaw to
  80379. * * minYaw: the minimum angle the bone will yaw to
  80380. * * maxPitch: the maximum angle the bone will pitch to
  80381. * * minPitch: the minimum angle the bone will yaw to
  80382. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80383. * * upAxis: the up axis of the coordinate system
  80384. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80385. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80386. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80387. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80388. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80389. * * adjustRoll: used to make an adjustment to the roll of the bone
  80390. **/
  80391. function BoneLookController(mesh, bone, target, options) {
  80392. /**
  80393. * The up axis of the coordinate system that is used when the bone is rotated
  80394. */
  80395. this.upAxis = BABYLON.Vector3.Up();
  80396. /**
  80397. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80398. */
  80399. this.upAxisSpace = BABYLON.Space.LOCAL;
  80400. /**
  80401. * Used to make an adjustment to the yaw of the bone
  80402. */
  80403. this.adjustYaw = 0;
  80404. /**
  80405. * Used to make an adjustment to the pitch of the bone
  80406. */
  80407. this.adjustPitch = 0;
  80408. /**
  80409. * Used to make an adjustment to the roll of the bone
  80410. */
  80411. this.adjustRoll = 0;
  80412. /**
  80413. * 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)
  80414. */
  80415. this.slerpAmount = 1;
  80416. this._boneQuat = BABYLON.Quaternion.Identity();
  80417. this._slerping = false;
  80418. this._firstFrameSkipped = false;
  80419. this._fowardAxis = BABYLON.Vector3.Forward();
  80420. this.mesh = mesh;
  80421. this.bone = bone;
  80422. this.target = target;
  80423. if (options) {
  80424. if (options.adjustYaw) {
  80425. this.adjustYaw = options.adjustYaw;
  80426. }
  80427. if (options.adjustPitch) {
  80428. this.adjustPitch = options.adjustPitch;
  80429. }
  80430. if (options.adjustRoll) {
  80431. this.adjustRoll = options.adjustRoll;
  80432. }
  80433. if (options.maxYaw != null) {
  80434. this.maxYaw = options.maxYaw;
  80435. }
  80436. else {
  80437. this.maxYaw = Math.PI;
  80438. }
  80439. if (options.minYaw != null) {
  80440. this.minYaw = options.minYaw;
  80441. }
  80442. else {
  80443. this.minYaw = -Math.PI;
  80444. }
  80445. if (options.maxPitch != null) {
  80446. this.maxPitch = options.maxPitch;
  80447. }
  80448. else {
  80449. this.maxPitch = Math.PI;
  80450. }
  80451. if (options.minPitch != null) {
  80452. this.minPitch = options.minPitch;
  80453. }
  80454. else {
  80455. this.minPitch = -Math.PI;
  80456. }
  80457. if (options.slerpAmount != null) {
  80458. this.slerpAmount = options.slerpAmount;
  80459. }
  80460. if (options.upAxis != null) {
  80461. this.upAxis = options.upAxis;
  80462. }
  80463. if (options.upAxisSpace != null) {
  80464. this.upAxisSpace = options.upAxisSpace;
  80465. }
  80466. if (options.yawAxis != null || options.pitchAxis != null) {
  80467. var newYawAxis = BABYLON.Axis.Y;
  80468. var newPitchAxis = BABYLON.Axis.X;
  80469. if (options.yawAxis != null) {
  80470. newYawAxis = options.yawAxis.clone();
  80471. newYawAxis.normalize();
  80472. }
  80473. if (options.pitchAxis != null) {
  80474. newPitchAxis = options.pitchAxis.clone();
  80475. newPitchAxis.normalize();
  80476. }
  80477. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80478. this._transformYawPitch = BABYLON.Matrix.Identity();
  80479. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80480. this._transformYawPitchInv = this._transformYawPitch.clone();
  80481. this._transformYawPitch.invert();
  80482. }
  80483. }
  80484. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80485. this.upAxisSpace = BABYLON.Space.LOCAL;
  80486. }
  80487. }
  80488. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80489. /**
  80490. * Gets or sets the minimum yaw angle that the bone can look to
  80491. */
  80492. get: function () {
  80493. return this._minYaw;
  80494. },
  80495. set: function (value) {
  80496. this._minYaw = value;
  80497. this._minYawSin = Math.sin(value);
  80498. this._minYawCos = Math.cos(value);
  80499. if (this._maxYaw != null) {
  80500. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80501. this._yawRange = this._maxYaw - this._minYaw;
  80502. }
  80503. },
  80504. enumerable: true,
  80505. configurable: true
  80506. });
  80507. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80508. /**
  80509. * Gets or sets the maximum yaw angle that the bone can look to
  80510. */
  80511. get: function () {
  80512. return this._maxYaw;
  80513. },
  80514. set: function (value) {
  80515. this._maxYaw = value;
  80516. this._maxYawSin = Math.sin(value);
  80517. this._maxYawCos = Math.cos(value);
  80518. if (this._minYaw != null) {
  80519. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80520. this._yawRange = this._maxYaw - this._minYaw;
  80521. }
  80522. },
  80523. enumerable: true,
  80524. configurable: true
  80525. });
  80526. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80527. /**
  80528. * Gets or sets the minimum pitch angle that the bone can look to
  80529. */
  80530. get: function () {
  80531. return this._minPitch;
  80532. },
  80533. set: function (value) {
  80534. this._minPitch = value;
  80535. this._minPitchTan = Math.tan(value);
  80536. },
  80537. enumerable: true,
  80538. configurable: true
  80539. });
  80540. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80541. /**
  80542. * Gets or sets the maximum pitch angle that the bone can look to
  80543. */
  80544. get: function () {
  80545. return this._maxPitch;
  80546. },
  80547. set: function (value) {
  80548. this._maxPitch = value;
  80549. this._maxPitchTan = Math.tan(value);
  80550. },
  80551. enumerable: true,
  80552. configurable: true
  80553. });
  80554. /**
  80555. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80556. */
  80557. BoneLookController.prototype.update = function () {
  80558. //skip the first frame when slerping so that the mesh rotation is correct
  80559. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80560. this._firstFrameSkipped = true;
  80561. return;
  80562. }
  80563. var bone = this.bone;
  80564. var bonePos = BoneLookController._tmpVecs[0];
  80565. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80566. var target = this.target;
  80567. var _tmpMat1 = BoneLookController._tmpMats[0];
  80568. var _tmpMat2 = BoneLookController._tmpMats[1];
  80569. var mesh = this.mesh;
  80570. var parentBone = bone.getParent();
  80571. var upAxis = BoneLookController._tmpVecs[1];
  80572. upAxis.copyFrom(this.upAxis);
  80573. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80574. if (this._transformYawPitch) {
  80575. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80576. }
  80577. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80578. }
  80579. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80580. mesh.getDirectionToRef(upAxis, upAxis);
  80581. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80582. upAxis.normalize();
  80583. }
  80584. }
  80585. var checkYaw = false;
  80586. var checkPitch = false;
  80587. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80588. checkYaw = true;
  80589. }
  80590. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80591. checkPitch = true;
  80592. }
  80593. if (checkYaw || checkPitch) {
  80594. var spaceMat = BoneLookController._tmpMats[2];
  80595. var spaceMatInv = BoneLookController._tmpMats[3];
  80596. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80597. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80598. }
  80599. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80600. spaceMat.copyFrom(mesh.getWorldMatrix());
  80601. }
  80602. else {
  80603. var forwardAxis = BoneLookController._tmpVecs[2];
  80604. forwardAxis.copyFrom(this._fowardAxis);
  80605. if (this._transformYawPitch) {
  80606. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80607. }
  80608. if (parentBone) {
  80609. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80610. }
  80611. else {
  80612. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80613. }
  80614. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80615. rightAxis.normalize();
  80616. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80617. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80618. }
  80619. spaceMat.invertToRef(spaceMatInv);
  80620. var xzlen = null;
  80621. if (checkPitch) {
  80622. var localTarget = BoneLookController._tmpVecs[3];
  80623. target.subtractToRef(bonePos, localTarget);
  80624. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80625. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80626. var pitch = Math.atan2(localTarget.y, xzlen);
  80627. var newPitch = pitch;
  80628. if (pitch > this._maxPitch) {
  80629. localTarget.y = this._maxPitchTan * xzlen;
  80630. newPitch = this._maxPitch;
  80631. }
  80632. else if (pitch < this._minPitch) {
  80633. localTarget.y = this._minPitchTan * xzlen;
  80634. newPitch = this._minPitch;
  80635. }
  80636. if (pitch != newPitch) {
  80637. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80638. localTarget.addInPlace(bonePos);
  80639. target = localTarget;
  80640. }
  80641. }
  80642. if (checkYaw) {
  80643. var localTarget = BoneLookController._tmpVecs[4];
  80644. target.subtractToRef(bonePos, localTarget);
  80645. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80646. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80647. var newYaw = yaw;
  80648. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80649. if (xzlen == null) {
  80650. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80651. }
  80652. if (this._yawRange > Math.PI) {
  80653. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80654. localTarget.z = this._maxYawCos * xzlen;
  80655. localTarget.x = this._maxYawSin * xzlen;
  80656. newYaw = this._maxYaw;
  80657. }
  80658. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80659. localTarget.z = this._minYawCos * xzlen;
  80660. localTarget.x = this._minYawSin * xzlen;
  80661. newYaw = this._minYaw;
  80662. }
  80663. }
  80664. else {
  80665. if (yaw > this._maxYaw) {
  80666. localTarget.z = this._maxYawCos * xzlen;
  80667. localTarget.x = this._maxYawSin * xzlen;
  80668. newYaw = this._maxYaw;
  80669. }
  80670. else if (yaw < this._minYaw) {
  80671. localTarget.z = this._minYawCos * xzlen;
  80672. localTarget.x = this._minYawSin * xzlen;
  80673. newYaw = this._minYaw;
  80674. }
  80675. }
  80676. }
  80677. if (this._slerping && this._yawRange > Math.PI) {
  80678. //are we going to be crossing into the min/max region?
  80679. var boneFwd = BoneLookController._tmpVecs[8];
  80680. boneFwd.copyFrom(BABYLON.Axis.Z);
  80681. if (this._transformYawPitch) {
  80682. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80683. }
  80684. var boneRotMat = BoneLookController._tmpMats[4];
  80685. this._boneQuat.toRotationMatrix(boneRotMat);
  80686. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80687. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80688. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80689. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80690. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80691. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80692. if (angBtwTar > angBtwMidYaw) {
  80693. if (xzlen == null) {
  80694. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80695. }
  80696. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80697. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80698. if (angBtwMin < angBtwMax) {
  80699. newYaw = boneYaw + Math.PI * .75;
  80700. localTarget.z = Math.cos(newYaw) * xzlen;
  80701. localTarget.x = Math.sin(newYaw) * xzlen;
  80702. }
  80703. else {
  80704. newYaw = boneYaw - Math.PI * .75;
  80705. localTarget.z = Math.cos(newYaw) * xzlen;
  80706. localTarget.x = Math.sin(newYaw) * xzlen;
  80707. }
  80708. }
  80709. }
  80710. if (yaw != newYaw) {
  80711. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80712. localTarget.addInPlace(bonePos);
  80713. target = localTarget;
  80714. }
  80715. }
  80716. }
  80717. var zaxis = BoneLookController._tmpVecs[5];
  80718. var xaxis = BoneLookController._tmpVecs[6];
  80719. var yaxis = BoneLookController._tmpVecs[7];
  80720. var _tmpQuat = BoneLookController._tmpQuat;
  80721. target.subtractToRef(bonePos, zaxis);
  80722. zaxis.normalize();
  80723. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80724. xaxis.normalize();
  80725. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80726. yaxis.normalize();
  80727. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80728. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80729. return;
  80730. }
  80731. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80732. return;
  80733. }
  80734. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80735. return;
  80736. }
  80737. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80738. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80739. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80740. }
  80741. if (this.slerpAmount < 1) {
  80742. if (!this._slerping) {
  80743. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80744. }
  80745. if (this._transformYawPitch) {
  80746. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80747. }
  80748. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80749. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80750. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80751. this._slerping = true;
  80752. }
  80753. else {
  80754. if (this._transformYawPitch) {
  80755. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80756. }
  80757. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80758. this._slerping = false;
  80759. }
  80760. };
  80761. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80762. var angDiff = ang2 - ang1;
  80763. angDiff %= Math.PI * 2;
  80764. if (angDiff > Math.PI) {
  80765. angDiff -= Math.PI * 2;
  80766. }
  80767. else if (angDiff < -Math.PI) {
  80768. angDiff += Math.PI * 2;
  80769. }
  80770. return angDiff;
  80771. };
  80772. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80773. ang1 %= (2 * Math.PI);
  80774. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80775. ang2 %= (2 * Math.PI);
  80776. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80777. var ab = 0;
  80778. if (ang1 < ang2) {
  80779. ab = ang2 - ang1;
  80780. }
  80781. else {
  80782. ab = ang1 - ang2;
  80783. }
  80784. if (ab > Math.PI) {
  80785. ab = Math.PI * 2 - ab;
  80786. }
  80787. return ab;
  80788. };
  80789. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80790. ang %= (2 * Math.PI);
  80791. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80792. ang1 %= (2 * Math.PI);
  80793. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80794. ang2 %= (2 * Math.PI);
  80795. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80796. if (ang1 < ang2) {
  80797. if (ang > ang1 && ang < ang2) {
  80798. return true;
  80799. }
  80800. }
  80801. else {
  80802. if (ang > ang2 && ang < ang1) {
  80803. return true;
  80804. }
  80805. }
  80806. return false;
  80807. };
  80808. 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()];
  80809. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80810. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80811. return BoneLookController;
  80812. }());
  80813. BABYLON.BoneLookController = BoneLookController;
  80814. })(BABYLON || (BABYLON = {}));
  80815. //# sourceMappingURL=babylon.boneLookController.js.map
  80816. var BABYLON;
  80817. (function (BABYLON) {
  80818. /**
  80819. * Class used to handle skinning animations
  80820. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80821. */
  80822. var Skeleton = /** @class */ (function () {
  80823. /**
  80824. * Creates a new skeleton
  80825. * @param name defines the skeleton name
  80826. * @param id defines the skeleton Id
  80827. * @param scene defines the hosting scene
  80828. */
  80829. function Skeleton(
  80830. /** defines the skeleton name */
  80831. name,
  80832. /** defines the skeleton Id */
  80833. id, scene) {
  80834. this.name = name;
  80835. this.id = id;
  80836. /**
  80837. * Gets the list of child bones
  80838. */
  80839. this.bones = new Array();
  80840. /**
  80841. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80842. */
  80843. this.needInitialSkinMatrix = false;
  80844. this._isDirty = true;
  80845. this._meshesWithPoseMatrix = new Array();
  80846. this._identity = BABYLON.Matrix.Identity();
  80847. this._ranges = {};
  80848. this._lastAbsoluteTransformsUpdateId = -1;
  80849. /**
  80850. * Specifies if the skeleton should be serialized
  80851. */
  80852. this.doNotSerialize = false;
  80853. this._animationPropertiesOverride = null;
  80854. // Events
  80855. /**
  80856. * An observable triggered before computing the skeleton's matrices
  80857. */
  80858. this.onBeforeComputeObservable = new BABYLON.Observable();
  80859. this.bones = [];
  80860. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80861. scene.skeletons.push(this);
  80862. //make sure it will recalculate the matrix next time prepare is called.
  80863. this._isDirty = true;
  80864. }
  80865. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80866. /**
  80867. * Gets or sets the animation properties override
  80868. */
  80869. get: function () {
  80870. if (!this._animationPropertiesOverride) {
  80871. return this._scene.animationPropertiesOverride;
  80872. }
  80873. return this._animationPropertiesOverride;
  80874. },
  80875. set: function (value) {
  80876. this._animationPropertiesOverride = value;
  80877. },
  80878. enumerable: true,
  80879. configurable: true
  80880. });
  80881. // Members
  80882. /**
  80883. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80884. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80885. * @returns a Float32Array containing matrices data
  80886. */
  80887. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80888. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80889. return mesh._bonesTransformMatrices;
  80890. }
  80891. if (!this._transformMatrices) {
  80892. this.prepare();
  80893. }
  80894. return this._transformMatrices;
  80895. };
  80896. /**
  80897. * Gets the current hosting scene
  80898. * @returns a scene object
  80899. */
  80900. Skeleton.prototype.getScene = function () {
  80901. return this._scene;
  80902. };
  80903. // Methods
  80904. /**
  80905. * Gets a string representing the current skeleton data
  80906. * @param fullDetails defines a boolean indicating if we want a verbose version
  80907. * @returns a string representing the current skeleton data
  80908. */
  80909. Skeleton.prototype.toString = function (fullDetails) {
  80910. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80911. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80912. if (fullDetails) {
  80913. ret += ", Ranges: {";
  80914. var first = true;
  80915. for (var name_1 in this._ranges) {
  80916. if (first) {
  80917. ret += ", ";
  80918. first = false;
  80919. }
  80920. ret += name_1;
  80921. }
  80922. ret += "}";
  80923. }
  80924. return ret;
  80925. };
  80926. /**
  80927. * Get bone's index searching by name
  80928. * @param name defines bone's name to search for
  80929. * @return the indice of the bone. Returns -1 if not found
  80930. */
  80931. Skeleton.prototype.getBoneIndexByName = function (name) {
  80932. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80933. if (this.bones[boneIndex].name === name) {
  80934. return boneIndex;
  80935. }
  80936. }
  80937. return -1;
  80938. };
  80939. /**
  80940. * Creater a new animation range
  80941. * @param name defines the name of the range
  80942. * @param from defines the start key
  80943. * @param to defines the end key
  80944. */
  80945. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80946. // check name not already in use
  80947. if (!this._ranges[name]) {
  80948. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80949. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80950. if (this.bones[i].animations[0]) {
  80951. this.bones[i].animations[0].createRange(name, from, to);
  80952. }
  80953. }
  80954. }
  80955. };
  80956. /**
  80957. * Delete a specific animation range
  80958. * @param name defines the name of the range
  80959. * @param deleteFrames defines if frames must be removed as well
  80960. */
  80961. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80962. if (deleteFrames === void 0) { deleteFrames = true; }
  80963. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80964. if (this.bones[i].animations[0]) {
  80965. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80966. }
  80967. }
  80968. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80969. };
  80970. /**
  80971. * Gets a specific animation range
  80972. * @param name defines the name of the range to look for
  80973. * @returns the requested animation range or null if not found
  80974. */
  80975. Skeleton.prototype.getAnimationRange = function (name) {
  80976. return this._ranges[name];
  80977. };
  80978. /**
  80979. * Gets the list of all animation ranges defined on this skeleton
  80980. * @returns an array
  80981. */
  80982. Skeleton.prototype.getAnimationRanges = function () {
  80983. var animationRanges = [];
  80984. var name;
  80985. var i = 0;
  80986. for (name in this._ranges) {
  80987. animationRanges[i] = this._ranges[name];
  80988. i++;
  80989. }
  80990. return animationRanges;
  80991. };
  80992. /**
  80993. * Copy animation range from a source skeleton.
  80994. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80995. * @param source defines the source skeleton
  80996. * @param name defines the name of the range to copy
  80997. * @param rescaleAsRequired defines if rescaling must be applied if required
  80998. * @returns true if operation was successful
  80999. */
  81000. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81001. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81002. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81003. return false;
  81004. }
  81005. var ret = true;
  81006. var frameOffset = this._getHighestAnimationFrame() + 1;
  81007. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81008. var boneDict = {};
  81009. var sourceBones = source.bones;
  81010. var nBones;
  81011. var i;
  81012. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81013. boneDict[sourceBones[i].name] = sourceBones[i];
  81014. }
  81015. if (this.bones.length !== sourceBones.length) {
  81016. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81017. ret = false;
  81018. }
  81019. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81020. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81021. var boneName = this.bones[i].name;
  81022. var sourceBone = boneDict[boneName];
  81023. if (sourceBone) {
  81024. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81025. }
  81026. else {
  81027. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81028. ret = false;
  81029. }
  81030. }
  81031. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81032. var range = source.getAnimationRange(name);
  81033. if (range) {
  81034. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81035. }
  81036. return ret;
  81037. };
  81038. /**
  81039. * Forces the skeleton to go to rest pose
  81040. */
  81041. Skeleton.prototype.returnToRest = function () {
  81042. for (var index = 0; index < this.bones.length; index++) {
  81043. this.bones[index].returnToRest();
  81044. }
  81045. };
  81046. Skeleton.prototype._getHighestAnimationFrame = function () {
  81047. var ret = 0;
  81048. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81049. if (this.bones[i].animations[0]) {
  81050. var highest = this.bones[i].animations[0].getHighestFrame();
  81051. if (ret < highest) {
  81052. ret = highest;
  81053. }
  81054. }
  81055. }
  81056. return ret;
  81057. };
  81058. /**
  81059. * Begin a specific animation range
  81060. * @param name defines the name of the range to start
  81061. * @param loop defines if looping must be turned on (false by default)
  81062. * @param speedRatio defines the speed ratio to apply (1 by default)
  81063. * @param onAnimationEnd defines a callback which will be called when animation will end
  81064. * @returns a new animatable
  81065. */
  81066. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81067. var range = this.getAnimationRange(name);
  81068. if (!range) {
  81069. return null;
  81070. }
  81071. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81072. };
  81073. /** @hidden */
  81074. Skeleton.prototype._markAsDirty = function () {
  81075. this._isDirty = true;
  81076. };
  81077. /** @hidden */
  81078. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81079. this._meshesWithPoseMatrix.push(mesh);
  81080. };
  81081. /** @hidden */
  81082. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81083. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81084. if (index > -1) {
  81085. this._meshesWithPoseMatrix.splice(index, 1);
  81086. }
  81087. };
  81088. /** @hidden */
  81089. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81090. this.onBeforeComputeObservable.notifyObservers(this);
  81091. for (var index = 0; index < this.bones.length; index++) {
  81092. var bone = this.bones[index];
  81093. var parentBone = bone.getParent();
  81094. if (parentBone) {
  81095. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81096. }
  81097. else {
  81098. if (initialSkinMatrix) {
  81099. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81100. }
  81101. else {
  81102. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81103. }
  81104. }
  81105. if (bone._index !== -1) {
  81106. var mappedIndex = bone._index === null ? index : bone._index;
  81107. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81108. }
  81109. }
  81110. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81111. };
  81112. /**
  81113. * Build all resources required to render a skeleton
  81114. */
  81115. Skeleton.prototype.prepare = function () {
  81116. if (!this._isDirty) {
  81117. return;
  81118. }
  81119. if (this.needInitialSkinMatrix) {
  81120. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81121. var mesh = this._meshesWithPoseMatrix[index];
  81122. var poseMatrix = mesh.getPoseMatrix();
  81123. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81124. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81125. }
  81126. if (this._synchronizedWithMesh !== mesh) {
  81127. this._synchronizedWithMesh = mesh;
  81128. // Prepare bones
  81129. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81130. var bone = this.bones[boneIndex];
  81131. if (!bone.getParent()) {
  81132. var matrix = bone.getBaseMatrix();
  81133. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81134. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81135. }
  81136. }
  81137. }
  81138. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81139. }
  81140. }
  81141. else {
  81142. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81143. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81144. }
  81145. this._computeTransformMatrices(this._transformMatrices, null);
  81146. }
  81147. this._isDirty = false;
  81148. this._scene._activeBones.addCount(this.bones.length, false);
  81149. };
  81150. /**
  81151. * Gets the list of animatables currently running for this skeleton
  81152. * @returns an array of animatables
  81153. */
  81154. Skeleton.prototype.getAnimatables = function () {
  81155. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81156. this._animatables = [];
  81157. for (var index = 0; index < this.bones.length; index++) {
  81158. this._animatables.push(this.bones[index]);
  81159. }
  81160. }
  81161. return this._animatables;
  81162. };
  81163. /**
  81164. * Clone the current skeleton
  81165. * @param name defines the name of the new skeleton
  81166. * @param id defines the id of the enw skeleton
  81167. * @returns the new skeleton
  81168. */
  81169. Skeleton.prototype.clone = function (name, id) {
  81170. var result = new Skeleton(name, id || name, this._scene);
  81171. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81172. for (var index = 0; index < this.bones.length; index++) {
  81173. var source = this.bones[index];
  81174. var parentBone = null;
  81175. var parent_1 = source.getParent();
  81176. if (parent_1) {
  81177. var parentIndex = this.bones.indexOf(parent_1);
  81178. parentBone = result.bones[parentIndex];
  81179. }
  81180. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81181. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81182. }
  81183. if (this._ranges) {
  81184. result._ranges = {};
  81185. for (var rangeName in this._ranges) {
  81186. var range = this._ranges[rangeName];
  81187. if (range) {
  81188. result._ranges[rangeName] = range.clone();
  81189. }
  81190. }
  81191. }
  81192. this._isDirty = true;
  81193. return result;
  81194. };
  81195. /**
  81196. * Enable animation blending for this skeleton
  81197. * @param blendingSpeed defines the blending speed to apply
  81198. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81199. */
  81200. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81201. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81202. this.bones.forEach(function (bone) {
  81203. bone.animations.forEach(function (animation) {
  81204. animation.enableBlending = true;
  81205. animation.blendingSpeed = blendingSpeed;
  81206. });
  81207. });
  81208. };
  81209. /**
  81210. * Releases all resources associated with the current skeleton
  81211. */
  81212. Skeleton.prototype.dispose = function () {
  81213. this._meshesWithPoseMatrix = [];
  81214. // Animations
  81215. this.getScene().stopAnimation(this);
  81216. // Remove from scene
  81217. this.getScene().removeSkeleton(this);
  81218. };
  81219. /**
  81220. * Serialize the skeleton in a JSON object
  81221. * @returns a JSON object
  81222. */
  81223. Skeleton.prototype.serialize = function () {
  81224. var serializationObject = {};
  81225. serializationObject.name = this.name;
  81226. serializationObject.id = this.id;
  81227. if (this.dimensionsAtRest) {
  81228. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81229. }
  81230. serializationObject.bones = [];
  81231. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81232. for (var index = 0; index < this.bones.length; index++) {
  81233. var bone = this.bones[index];
  81234. var parent_2 = bone.getParent();
  81235. var serializedBone = {
  81236. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81237. name: bone.name,
  81238. matrix: bone.getBaseMatrix().toArray(),
  81239. rest: bone.getRestPose().toArray()
  81240. };
  81241. serializationObject.bones.push(serializedBone);
  81242. if (bone.length) {
  81243. serializedBone.length = bone.length;
  81244. }
  81245. if (bone.metadata) {
  81246. serializedBone.metadata = bone.metadata;
  81247. }
  81248. if (bone.animations && bone.animations.length > 0) {
  81249. serializedBone.animation = bone.animations[0].serialize();
  81250. }
  81251. serializationObject.ranges = [];
  81252. for (var name in this._ranges) {
  81253. var source = this._ranges[name];
  81254. if (!source) {
  81255. continue;
  81256. }
  81257. var range = {};
  81258. range.name = name;
  81259. range.from = source.from;
  81260. range.to = source.to;
  81261. serializationObject.ranges.push(range);
  81262. }
  81263. }
  81264. return serializationObject;
  81265. };
  81266. /**
  81267. * Creates a new skeleton from serialized data
  81268. * @param parsedSkeleton defines the serialized data
  81269. * @param scene defines the hosting scene
  81270. * @returns a new skeleton
  81271. */
  81272. Skeleton.Parse = function (parsedSkeleton, scene) {
  81273. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81274. if (parsedSkeleton.dimensionsAtRest) {
  81275. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81276. }
  81277. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81278. var index;
  81279. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81280. var parsedBone = parsedSkeleton.bones[index];
  81281. var parentBone = null;
  81282. if (parsedBone.parentBoneIndex > -1) {
  81283. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81284. }
  81285. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81286. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81287. if (parsedBone.length) {
  81288. bone.length = parsedBone.length;
  81289. }
  81290. if (parsedBone.metadata) {
  81291. bone.metadata = parsedBone.metadata;
  81292. }
  81293. if (parsedBone.animation) {
  81294. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81295. }
  81296. }
  81297. // placed after bones, so createAnimationRange can cascade down
  81298. if (parsedSkeleton.ranges) {
  81299. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81300. var data = parsedSkeleton.ranges[index];
  81301. skeleton.createAnimationRange(data.name, data.from, data.to);
  81302. }
  81303. }
  81304. return skeleton;
  81305. };
  81306. /**
  81307. * Compute all node absolute transforms
  81308. * @param forceUpdate defines if computation must be done even if cache is up to date
  81309. */
  81310. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81311. if (forceUpdate === void 0) { forceUpdate = false; }
  81312. var renderId = this._scene.getRenderId();
  81313. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81314. this.bones[0].computeAbsoluteTransforms();
  81315. this._lastAbsoluteTransformsUpdateId = renderId;
  81316. }
  81317. };
  81318. /**
  81319. * Gets the root pose matrix
  81320. * @returns a matrix
  81321. */
  81322. Skeleton.prototype.getPoseMatrix = function () {
  81323. var poseMatrix = null;
  81324. if (this._meshesWithPoseMatrix.length > 0) {
  81325. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81326. }
  81327. return poseMatrix;
  81328. };
  81329. /**
  81330. * Sorts bones per internal index
  81331. */
  81332. Skeleton.prototype.sortBones = function () {
  81333. var bones = new Array();
  81334. var visited = new Array(this.bones.length);
  81335. for (var index = 0; index < this.bones.length; index++) {
  81336. this._sortBones(index, bones, visited);
  81337. }
  81338. this.bones = bones;
  81339. };
  81340. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81341. if (visited[index]) {
  81342. return;
  81343. }
  81344. visited[index] = true;
  81345. var bone = this.bones[index];
  81346. if (bone._index === undefined) {
  81347. bone._index = index;
  81348. }
  81349. var parentBone = bone.getParent();
  81350. if (parentBone) {
  81351. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81352. }
  81353. bones.push(bone);
  81354. };
  81355. return Skeleton;
  81356. }());
  81357. BABYLON.Skeleton = Skeleton;
  81358. })(BABYLON || (BABYLON = {}));
  81359. //# sourceMappingURL=babylon.skeleton.js.map
  81360. var BABYLON;
  81361. (function (BABYLON) {
  81362. var SphericalPolynomial = /** @class */ (function () {
  81363. function SphericalPolynomial() {
  81364. this.x = BABYLON.Vector3.Zero();
  81365. this.y = BABYLON.Vector3.Zero();
  81366. this.z = BABYLON.Vector3.Zero();
  81367. this.xx = BABYLON.Vector3.Zero();
  81368. this.yy = BABYLON.Vector3.Zero();
  81369. this.zz = BABYLON.Vector3.Zero();
  81370. this.xy = BABYLON.Vector3.Zero();
  81371. this.yz = BABYLON.Vector3.Zero();
  81372. this.zx = BABYLON.Vector3.Zero();
  81373. }
  81374. SphericalPolynomial.prototype.addAmbient = function (color) {
  81375. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81376. this.xx = this.xx.add(colorVector);
  81377. this.yy = this.yy.add(colorVector);
  81378. this.zz = this.zz.add(colorVector);
  81379. };
  81380. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81381. var result = new SphericalPolynomial();
  81382. result.x = harmonics.L11.scale(1.02333);
  81383. result.y = harmonics.L1_1.scale(1.02333);
  81384. result.z = harmonics.L10.scale(1.02333);
  81385. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81386. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81387. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81388. result.yz = harmonics.L2_1.scale(0.858086);
  81389. result.zx = harmonics.L21.scale(0.858086);
  81390. result.xy = harmonics.L2_2.scale(0.858086);
  81391. result.scale(1.0 / Math.PI);
  81392. return result;
  81393. };
  81394. SphericalPolynomial.prototype.scale = function (scale) {
  81395. this.x = this.x.scale(scale);
  81396. this.y = this.y.scale(scale);
  81397. this.z = this.z.scale(scale);
  81398. this.xx = this.xx.scale(scale);
  81399. this.yy = this.yy.scale(scale);
  81400. this.zz = this.zz.scale(scale);
  81401. this.yz = this.yz.scale(scale);
  81402. this.zx = this.zx.scale(scale);
  81403. this.xy = this.xy.scale(scale);
  81404. };
  81405. return SphericalPolynomial;
  81406. }());
  81407. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81408. var SphericalHarmonics = /** @class */ (function () {
  81409. function SphericalHarmonics() {
  81410. this.L00 = BABYLON.Vector3.Zero();
  81411. this.L1_1 = BABYLON.Vector3.Zero();
  81412. this.L10 = BABYLON.Vector3.Zero();
  81413. this.L11 = BABYLON.Vector3.Zero();
  81414. this.L2_2 = BABYLON.Vector3.Zero();
  81415. this.L2_1 = BABYLON.Vector3.Zero();
  81416. this.L20 = BABYLON.Vector3.Zero();
  81417. this.L21 = BABYLON.Vector3.Zero();
  81418. this.L22 = BABYLON.Vector3.Zero();
  81419. }
  81420. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81421. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81422. var c = colorVector.scale(deltaSolidAngle);
  81423. this.L00 = this.L00.add(c.scale(0.282095));
  81424. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81425. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81426. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81427. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81428. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81429. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81430. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81431. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81432. };
  81433. SphericalHarmonics.prototype.scale = function (scale) {
  81434. this.L00 = this.L00.scale(scale);
  81435. this.L1_1 = this.L1_1.scale(scale);
  81436. this.L10 = this.L10.scale(scale);
  81437. this.L11 = this.L11.scale(scale);
  81438. this.L2_2 = this.L2_2.scale(scale);
  81439. this.L2_1 = this.L2_1.scale(scale);
  81440. this.L20 = this.L20.scale(scale);
  81441. this.L21 = this.L21.scale(scale);
  81442. this.L22 = this.L22.scale(scale);
  81443. };
  81444. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81445. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81446. //
  81447. // E_lm = A_l * L_lm
  81448. //
  81449. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81450. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81451. // the scaling factors are given in equation 9.
  81452. // Constant (Band 0)
  81453. this.L00 = this.L00.scale(3.141593);
  81454. // Linear (Band 1)
  81455. this.L1_1 = this.L1_1.scale(2.094395);
  81456. this.L10 = this.L10.scale(2.094395);
  81457. this.L11 = this.L11.scale(2.094395);
  81458. // Quadratic (Band 2)
  81459. this.L2_2 = this.L2_2.scale(0.785398);
  81460. this.L2_1 = this.L2_1.scale(0.785398);
  81461. this.L20 = this.L20.scale(0.785398);
  81462. this.L21 = this.L21.scale(0.785398);
  81463. this.L22 = this.L22.scale(0.785398);
  81464. };
  81465. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81466. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81467. // L = (1/pi) * E * rho
  81468. //
  81469. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81470. this.scale(1.0 / Math.PI);
  81471. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81472. // (The pixel shader must apply albedo after texture fetches, etc).
  81473. };
  81474. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81475. var result = new SphericalHarmonics();
  81476. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81477. result.L1_1 = polynomial.y.scale(0.977204);
  81478. result.L10 = polynomial.z.scale(0.977204);
  81479. result.L11 = polynomial.x.scale(0.977204);
  81480. result.L2_2 = polynomial.xy.scale(1.16538);
  81481. result.L2_1 = polynomial.yz.scale(1.16538);
  81482. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81483. result.L21 = polynomial.zx.scale(1.16538);
  81484. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81485. result.scale(Math.PI);
  81486. return result;
  81487. };
  81488. return SphericalHarmonics;
  81489. }());
  81490. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81491. })(BABYLON || (BABYLON = {}));
  81492. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81493. var BABYLON;
  81494. (function (BABYLON) {
  81495. var FileFaceOrientation = /** @class */ (function () {
  81496. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81497. this.name = name;
  81498. this.worldAxisForNormal = worldAxisForNormal;
  81499. this.worldAxisForFileX = worldAxisForFileX;
  81500. this.worldAxisForFileY = worldAxisForFileY;
  81501. }
  81502. return FileFaceOrientation;
  81503. }());
  81504. ;
  81505. /**
  81506. * Helper class dealing with the extraction of spherical polynomial dataArray
  81507. * from a cube map.
  81508. */
  81509. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81510. function CubeMapToSphericalPolynomialTools() {
  81511. }
  81512. /**
  81513. * Converts a texture to the according Spherical Polynomial data.
  81514. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81515. *
  81516. * @param texture The texture to extract the information from.
  81517. * @return The Spherical Polynomial data.
  81518. */
  81519. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81520. if (!texture.isCube) {
  81521. // Only supports cube Textures currently.
  81522. return null;
  81523. }
  81524. var size = texture.getSize().width;
  81525. var right = texture.readPixels(0);
  81526. var left = texture.readPixels(1);
  81527. var up;
  81528. var down;
  81529. if (texture.isRenderTarget) {
  81530. up = texture.readPixels(3);
  81531. down = texture.readPixels(2);
  81532. }
  81533. else {
  81534. up = texture.readPixels(2);
  81535. down = texture.readPixels(3);
  81536. }
  81537. var front = texture.readPixels(4);
  81538. var back = texture.readPixels(5);
  81539. var gammaSpace = texture.gammaSpace;
  81540. // Always read as RGBA.
  81541. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81542. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81543. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81544. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81545. }
  81546. var cubeInfo = {
  81547. size: size,
  81548. right: right,
  81549. left: left,
  81550. up: up,
  81551. down: down,
  81552. front: front,
  81553. back: back,
  81554. format: format,
  81555. type: type,
  81556. gammaSpace: gammaSpace,
  81557. };
  81558. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81559. };
  81560. /**
  81561. * Converts a cubemap to the according Spherical Polynomial data.
  81562. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81563. *
  81564. * @param cubeInfo The Cube map to extract the information from.
  81565. * @return The Spherical Polynomial data.
  81566. */
  81567. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81568. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81569. var totalSolidAngle = 0.0;
  81570. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81571. var du = 2.0 / cubeInfo.size;
  81572. var dv = du;
  81573. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81574. var minUV = du * 0.5 - 1.0;
  81575. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81576. var fileFace = this.FileFaces[faceIndex];
  81577. var dataArray = cubeInfo[fileFace.name];
  81578. var v = minUV;
  81579. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81580. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81581. // Because SP is still linear, so summation is fine in that basis.
  81582. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81583. for (var y = 0; y < cubeInfo.size; y++) {
  81584. var u = minUV;
  81585. for (var x = 0; x < cubeInfo.size; x++) {
  81586. // World direction (not normalised)
  81587. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81588. worldDirection.normalize();
  81589. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81590. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81591. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81592. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81593. // Handle Integer types.
  81594. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81595. r /= 255;
  81596. g /= 255;
  81597. b /= 255;
  81598. }
  81599. // Handle Gamma space textures.
  81600. if (cubeInfo.gammaSpace) {
  81601. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81602. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81603. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81604. }
  81605. var color = new BABYLON.Color3(r, g, b);
  81606. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81607. totalSolidAngle += deltaSolidAngle;
  81608. u += du;
  81609. }
  81610. v += dv;
  81611. }
  81612. }
  81613. // Solid angle for entire sphere is 4*pi
  81614. var sphereSolidAngle = 4.0 * Math.PI;
  81615. // Adjust the solid angle to allow for how many faces we processed.
  81616. var facesProcessed = 6.0;
  81617. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81618. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81619. // This is needed because the numerical integration over the cube uses a
  81620. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81621. // and also to compensate for accumulative error due to float precision in the summation.
  81622. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81623. sphericalHarmonics.scale(correctionFactor);
  81624. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81625. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81626. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81627. };
  81628. CubeMapToSphericalPolynomialTools.FileFaces = [
  81629. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81630. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81631. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81632. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81633. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81634. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81635. ];
  81636. return CubeMapToSphericalPolynomialTools;
  81637. }());
  81638. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81639. })(BABYLON || (BABYLON = {}));
  81640. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81641. var BABYLON;
  81642. (function (BABYLON) {
  81643. /**
  81644. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81645. */
  81646. var PanoramaToCubeMapTools = /** @class */ (function () {
  81647. function PanoramaToCubeMapTools() {
  81648. }
  81649. /**
  81650. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81651. *
  81652. * @param float32Array The source data.
  81653. * @param inputWidth The width of the input panorama.
  81654. * @param inputhHeight The height of the input panorama.
  81655. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81656. * @return The cubemap data
  81657. */
  81658. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81659. if (!float32Array) {
  81660. throw "ConvertPanoramaToCubemap: input cannot be null";
  81661. }
  81662. if (float32Array.length != inputWidth * inputHeight * 3) {
  81663. throw "ConvertPanoramaToCubemap: input size is wrong";
  81664. }
  81665. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81666. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81667. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81668. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81669. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81670. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81671. return {
  81672. front: textureFront,
  81673. back: textureBack,
  81674. left: textureLeft,
  81675. right: textureRight,
  81676. up: textureUp,
  81677. down: textureDown,
  81678. size: size,
  81679. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81680. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81681. gammaSpace: false,
  81682. };
  81683. };
  81684. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81685. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81686. var textureArray = new Float32Array(buffer);
  81687. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81688. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81689. var dy = 1 / texSize;
  81690. var fy = 0;
  81691. for (var y = 0; y < texSize; y++) {
  81692. var xv1 = faceData[0];
  81693. var xv2 = faceData[2];
  81694. for (var x = 0; x < texSize; x++) {
  81695. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81696. v.normalize();
  81697. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81698. // 3 channels per pixels
  81699. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81700. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81701. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81702. xv1 = xv1.add(rotDX1);
  81703. xv2 = xv2.add(rotDX2);
  81704. }
  81705. fy += dy;
  81706. }
  81707. return textureArray;
  81708. };
  81709. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81710. var theta = Math.atan2(vDir.z, vDir.x);
  81711. var phi = Math.acos(vDir.y);
  81712. while (theta < -Math.PI)
  81713. theta += 2 * Math.PI;
  81714. while (theta > Math.PI)
  81715. theta -= 2 * Math.PI;
  81716. var dx = theta / Math.PI;
  81717. var dy = phi / Math.PI;
  81718. // recenter.
  81719. dx = dx * 0.5 + 0.5;
  81720. var px = Math.round(dx * inputWidth);
  81721. if (px < 0)
  81722. px = 0;
  81723. else if (px >= inputWidth)
  81724. px = inputWidth - 1;
  81725. var py = Math.round(dy * inputHeight);
  81726. if (py < 0)
  81727. py = 0;
  81728. else if (py >= inputHeight)
  81729. py = inputHeight - 1;
  81730. var inputY = (inputHeight - py - 1);
  81731. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81732. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81733. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81734. return {
  81735. r: r,
  81736. g: g,
  81737. b: b
  81738. };
  81739. };
  81740. PanoramaToCubeMapTools.FACE_FRONT = [
  81741. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81742. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81743. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81744. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81745. ];
  81746. PanoramaToCubeMapTools.FACE_BACK = [
  81747. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81748. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81749. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81750. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81751. ];
  81752. PanoramaToCubeMapTools.FACE_RIGHT = [
  81753. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81754. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81755. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81756. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81757. ];
  81758. PanoramaToCubeMapTools.FACE_LEFT = [
  81759. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81760. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81761. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81762. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81763. ];
  81764. PanoramaToCubeMapTools.FACE_DOWN = [
  81765. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81766. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81767. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81768. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81769. ];
  81770. PanoramaToCubeMapTools.FACE_UP = [
  81771. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81772. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81773. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81774. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81775. ];
  81776. return PanoramaToCubeMapTools;
  81777. }());
  81778. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81779. })(BABYLON || (BABYLON = {}));
  81780. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81781. var BABYLON;
  81782. (function (BABYLON) {
  81783. ;
  81784. /**
  81785. * This groups tools to convert HDR texture to native colors array.
  81786. */
  81787. var HDRTools = /** @class */ (function () {
  81788. function HDRTools() {
  81789. }
  81790. HDRTools.Ldexp = function (mantissa, exponent) {
  81791. if (exponent > 1023) {
  81792. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81793. }
  81794. if (exponent < -1074) {
  81795. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81796. }
  81797. return mantissa * Math.pow(2, exponent);
  81798. };
  81799. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81800. if (exponent > 0) { /*nonzero pixel*/
  81801. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81802. float32array[index + 0] = red * exponent;
  81803. float32array[index + 1] = green * exponent;
  81804. float32array[index + 2] = blue * exponent;
  81805. }
  81806. else {
  81807. float32array[index + 0] = 0;
  81808. float32array[index + 1] = 0;
  81809. float32array[index + 2] = 0;
  81810. }
  81811. };
  81812. HDRTools.readStringLine = function (uint8array, startIndex) {
  81813. var line = "";
  81814. var character = "";
  81815. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81816. character = String.fromCharCode(uint8array[i]);
  81817. if (character == "\n") {
  81818. break;
  81819. }
  81820. line += character;
  81821. }
  81822. return line;
  81823. };
  81824. /**
  81825. * Reads header information from an RGBE texture stored in a native array.
  81826. * More information on this format are available here:
  81827. * https://en.wikipedia.org/wiki/RGBE_image_format
  81828. *
  81829. * @param uint8array The binary file stored in native array.
  81830. * @return The header information.
  81831. */
  81832. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81833. var height = 0;
  81834. var width = 0;
  81835. var line = this.readStringLine(uint8array, 0);
  81836. if (line[0] != '#' || line[1] != '?') {
  81837. throw "Bad HDR Format.";
  81838. }
  81839. var endOfHeader = false;
  81840. var findFormat = false;
  81841. var lineIndex = 0;
  81842. do {
  81843. lineIndex += (line.length + 1);
  81844. line = this.readStringLine(uint8array, lineIndex);
  81845. if (line == "FORMAT=32-bit_rle_rgbe") {
  81846. findFormat = true;
  81847. }
  81848. else if (line.length == 0) {
  81849. endOfHeader = true;
  81850. }
  81851. } while (!endOfHeader);
  81852. if (!findFormat) {
  81853. throw "HDR Bad header format, unsupported FORMAT";
  81854. }
  81855. lineIndex += (line.length + 1);
  81856. line = this.readStringLine(uint8array, lineIndex);
  81857. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81858. var match = sizeRegexp.exec(line);
  81859. // TODO. Support +Y and -X if needed.
  81860. if (!match || match.length < 3) {
  81861. throw "HDR Bad header format, no size";
  81862. }
  81863. width = parseInt(match[2]);
  81864. height = parseInt(match[1]);
  81865. if (width < 8 || width > 0x7fff) {
  81866. throw "HDR Bad header format, unsupported size";
  81867. }
  81868. lineIndex += (line.length + 1);
  81869. return {
  81870. height: height,
  81871. width: width,
  81872. dataPosition: lineIndex
  81873. };
  81874. };
  81875. /**
  81876. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81877. * This RGBE texture needs to store the information as a panorama.
  81878. *
  81879. * More information on this format are available here:
  81880. * https://en.wikipedia.org/wiki/RGBE_image_format
  81881. *
  81882. * @param buffer The binary file stored in an array buffer.
  81883. * @param size The expected size of the extracted cubemap.
  81884. * @return The Cube Map information.
  81885. */
  81886. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81887. var uint8array = new Uint8Array(buffer);
  81888. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81889. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81890. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81891. return cubeMapData;
  81892. };
  81893. /**
  81894. * Returns the pixels data extracted from an RGBE texture.
  81895. * This pixels will be stored left to right up to down in the R G B order in one array.
  81896. *
  81897. * More information on this format are available here:
  81898. * https://en.wikipedia.org/wiki/RGBE_image_format
  81899. *
  81900. * @param uint8array The binary file stored in an array buffer.
  81901. * @param hdrInfo The header information of the file.
  81902. * @return The pixels data in RGB right to left up to down order.
  81903. */
  81904. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81905. // Keep for multi format supports.
  81906. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81907. };
  81908. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81909. var num_scanlines = hdrInfo.height;
  81910. var scanline_width = hdrInfo.width;
  81911. var a, b, c, d, count;
  81912. var dataIndex = hdrInfo.dataPosition;
  81913. var index = 0, endIndex = 0, i = 0;
  81914. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81915. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81916. // 3 channels of 4 bytes per pixel in float.
  81917. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81918. var resultArray = new Float32Array(resultBuffer);
  81919. // read in each successive scanline
  81920. while (num_scanlines > 0) {
  81921. a = uint8array[dataIndex++];
  81922. b = uint8array[dataIndex++];
  81923. c = uint8array[dataIndex++];
  81924. d = uint8array[dataIndex++];
  81925. if (a != 2 || b != 2 || (c & 0x80)) {
  81926. // this file is not run length encoded
  81927. throw "HDR Bad header format, not RLE";
  81928. }
  81929. if (((c << 8) | d) != scanline_width) {
  81930. throw "HDR Bad header format, wrong scan line width";
  81931. }
  81932. index = 0;
  81933. // read each of the four channels for the scanline into the buffer
  81934. for (i = 0; i < 4; i++) {
  81935. endIndex = (i + 1) * scanline_width;
  81936. while (index < endIndex) {
  81937. a = uint8array[dataIndex++];
  81938. b = uint8array[dataIndex++];
  81939. if (a > 128) {
  81940. // a run of the same value
  81941. count = a - 128;
  81942. if ((count == 0) || (count > endIndex - index)) {
  81943. throw "HDR Bad Format, bad scanline data (run)";
  81944. }
  81945. while (count-- > 0) {
  81946. scanLineArray[index++] = b;
  81947. }
  81948. }
  81949. else {
  81950. // a non-run
  81951. count = a;
  81952. if ((count == 0) || (count > endIndex - index)) {
  81953. throw "HDR Bad Format, bad scanline data (non-run)";
  81954. }
  81955. scanLineArray[index++] = b;
  81956. if (--count > 0) {
  81957. for (var j = 0; j < count; j++) {
  81958. scanLineArray[index++] = uint8array[dataIndex++];
  81959. }
  81960. }
  81961. }
  81962. }
  81963. }
  81964. // now convert data from buffer into floats
  81965. for (i = 0; i < scanline_width; i++) {
  81966. a = scanLineArray[i];
  81967. b = scanLineArray[i + scanline_width];
  81968. c = scanLineArray[i + 2 * scanline_width];
  81969. d = scanLineArray[i + 3 * scanline_width];
  81970. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81971. }
  81972. num_scanlines--;
  81973. }
  81974. return resultArray;
  81975. };
  81976. return HDRTools;
  81977. }());
  81978. BABYLON.HDRTools = HDRTools;
  81979. })(BABYLON || (BABYLON = {}));
  81980. //# sourceMappingURL=babylon.hdr.js.map
  81981. var BABYLON;
  81982. (function (BABYLON) {
  81983. /**
  81984. * Sets of helpers addressing the serialization and deserialization of environment texture
  81985. * stored in a BabylonJS env file.
  81986. * Those files are usually stored as .env files.
  81987. */
  81988. var EnvironmentTextureTools = /** @class */ (function () {
  81989. function EnvironmentTextureTools() {
  81990. }
  81991. /**
  81992. * Gets the environment info from an env file.
  81993. * @param data The array buffer containing the .env bytes.
  81994. * @returns the environment file info (the json header) if successfully parsed.
  81995. */
  81996. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81997. var dataView = new DataView(data);
  81998. var pos = 0;
  81999. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82000. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82001. BABYLON.Tools.Error('Not a babylon environment map');
  82002. return null;
  82003. }
  82004. }
  82005. // Read json manifest - collect characters up to null terminator
  82006. var manifestString = '';
  82007. var charCode = 0x00;
  82008. while ((charCode = dataView.getUint8(pos++))) {
  82009. manifestString += String.fromCharCode(charCode);
  82010. }
  82011. var manifest = JSON.parse(manifestString);
  82012. if (manifest.specular) {
  82013. // Extend the header with the position of the payload.
  82014. manifest.specular.specularDataPosition = pos;
  82015. }
  82016. return manifest;
  82017. };
  82018. /**
  82019. * Creates an environment texture from a loaded cube texture.
  82020. * @param texture defines the cube texture to convert in env file
  82021. * @return a promise containing the environment data if succesfull.
  82022. */
  82023. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82024. var _this = this;
  82025. var internalTexture = texture.getInternalTexture();
  82026. if (!internalTexture) {
  82027. return Promise.reject("The cube texture is invalid.");
  82028. }
  82029. if (!texture._prefiltered) {
  82030. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82031. }
  82032. var engine = internalTexture.getEngine();
  82033. if (engine && engine.premultipliedAlpha) {
  82034. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82035. }
  82036. var canvas = engine.getRenderingCanvas();
  82037. if (!canvas) {
  82038. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82039. }
  82040. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82041. if (!engine.getCaps().textureFloatRender) {
  82042. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82043. if (!engine.getCaps().textureHalfFloatRender) {
  82044. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82045. }
  82046. }
  82047. var cubeWidth = internalTexture.width;
  82048. var hostingScene = new BABYLON.Scene(engine);
  82049. var specularTextures = {};
  82050. var promises = [];
  82051. // Read and collect all mipmaps data from the cube.
  82052. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82053. mipmapsCount = Math.round(mipmapsCount);
  82054. var _loop_1 = function (i) {
  82055. var faceWidth = Math.pow(2, mipmapsCount - i);
  82056. var _loop_2 = function (face) {
  82057. var data = texture.readPixels(face, i);
  82058. // Creates a temp texture with the face data.
  82059. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82060. // And rgbdEncode them.
  82061. var promise = new Promise(function (resolve, reject) {
  82062. 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);
  82063. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82064. rgbdPostProcess.onApply = function (effect) {
  82065. effect._bindTexture("textureSampler", tempTexture);
  82066. };
  82067. // As the process needs to happen on the main canvas, keep track of the current size
  82068. var currentW = engine.getRenderWidth();
  82069. var currentH = engine.getRenderHeight();
  82070. // Set the desired size for the texture
  82071. engine.setSize(faceWidth, faceWidth);
  82072. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82073. // Reading datas from WebGL
  82074. canvas.toBlob(function (blob) {
  82075. var fileReader = new FileReader();
  82076. fileReader.onload = function (event) {
  82077. var arrayBuffer = event.target.result;
  82078. specularTextures[i * 6 + face] = arrayBuffer;
  82079. resolve();
  82080. };
  82081. fileReader.readAsArrayBuffer(blob);
  82082. });
  82083. // Reapply the previous canvas size
  82084. engine.setSize(currentW, currentH);
  82085. });
  82086. });
  82087. promises.push(promise);
  82088. };
  82089. // All faces of the cube.
  82090. for (var face = 0; face < 6; face++) {
  82091. _loop_2(face);
  82092. }
  82093. };
  82094. for (var i = 0; i <= mipmapsCount; i++) {
  82095. _loop_1(i);
  82096. }
  82097. // Once all the textures haves been collected as RGBD stored in PNGs
  82098. return Promise.all(promises).then(function () {
  82099. // We can delete the hosting scene keeping track of all the creation objects
  82100. hostingScene.dispose();
  82101. // Creates the json header for the env texture
  82102. var info = {
  82103. version: 1,
  82104. width: cubeWidth,
  82105. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82106. specular: {
  82107. mipmaps: []
  82108. }
  82109. };
  82110. // Sets the specular image data information
  82111. var position = 0;
  82112. for (var i = 0; i <= mipmapsCount; i++) {
  82113. for (var face = 0; face < 6; face++) {
  82114. var byteLength = specularTextures[i * 6 + face].byteLength;
  82115. info.specular.mipmaps.push({
  82116. length: byteLength,
  82117. position: position
  82118. });
  82119. position += byteLength;
  82120. }
  82121. }
  82122. // Encode the JSON as an array buffer
  82123. var infoString = JSON.stringify(info);
  82124. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82125. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82126. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82127. infoView[i] = infoString.charCodeAt(i);
  82128. }
  82129. // Ends up with a null terminator for easier parsing
  82130. infoView[infoString.length] = 0x00;
  82131. // Computes the final required size and creates the storage
  82132. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82133. var finalBuffer = new ArrayBuffer(totalSize);
  82134. var finalBufferView = new Uint8Array(finalBuffer);
  82135. var dataView = new DataView(finalBuffer);
  82136. // Copy the magic bytes identifying the file in
  82137. var pos = 0;
  82138. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82139. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82140. }
  82141. // Add the json info
  82142. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82143. pos += infoBuffer.byteLength;
  82144. // Finally inserts the texture data
  82145. for (var i = 0; i <= mipmapsCount; i++) {
  82146. for (var face = 0; face < 6; face++) {
  82147. var dataBuffer = specularTextures[i * 6 + face];
  82148. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82149. pos += dataBuffer.byteLength;
  82150. }
  82151. }
  82152. // Voila
  82153. return finalBuffer;
  82154. });
  82155. };
  82156. /**
  82157. * Creates a JSON representation of the spherical data.
  82158. * @param texture defines the texture containing the polynomials
  82159. * @return the JSON representation of the spherical info
  82160. */
  82161. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82162. var polynmials = texture.sphericalPolynomial;
  82163. if (polynmials == null) {
  82164. return null;
  82165. }
  82166. return {
  82167. polynomials: true,
  82168. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82169. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82170. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82171. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82172. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82173. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82174. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82175. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82176. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82177. };
  82178. };
  82179. /**
  82180. * Uploads the texture info contained in the env file to te GPU.
  82181. * @param texture defines the internal texture to upload to
  82182. * @param arrayBuffer defines the buffer cotaining the data to load
  82183. * @param info defines the texture info retrieved through the GetEnvInfo method
  82184. * @returns a promise
  82185. */
  82186. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82187. if (info.version !== 1) {
  82188. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82189. }
  82190. var specularInfo = info.specular;
  82191. if (!specularInfo) {
  82192. // Nothing else parsed so far
  82193. return Promise.resolve();
  82194. }
  82195. // Double checks the enclosed info
  82196. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82197. mipmapsCount = Math.round(mipmapsCount) + 1;
  82198. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82199. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82200. }
  82201. // Gets everything ready.
  82202. var engine = texture.getEngine();
  82203. var expandTexture = false;
  82204. var generateNonLODTextures = false;
  82205. var rgbdPostProcess = null;
  82206. var cubeRtt = null;
  82207. var lodTextures = null;
  82208. var caps = engine.getCaps();
  82209. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82210. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82211. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82212. // Add extra process if texture lod is not supported
  82213. if (!caps.textureLOD) {
  82214. expandTexture = false;
  82215. generateNonLODTextures = true;
  82216. lodTextures = {};
  82217. }
  82218. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82219. else if (engine.webGLVersion < 2) {
  82220. expandTexture = false;
  82221. }
  82222. // If half float available we can uncompress the texture
  82223. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82224. expandTexture = true;
  82225. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82226. }
  82227. // If full float available we can uncompress the texture
  82228. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82229. expandTexture = true;
  82230. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82231. }
  82232. // Expand the texture if possible
  82233. if (expandTexture) {
  82234. // Simply run through the decode PP
  82235. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82236. texture._isRGBD = false;
  82237. texture.invertY = false;
  82238. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82239. generateDepthBuffer: false,
  82240. generateMipMaps: true,
  82241. generateStencilBuffer: false,
  82242. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82243. type: texture.type,
  82244. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82245. });
  82246. }
  82247. else {
  82248. texture._isRGBD = true;
  82249. texture.invertY = true;
  82250. // In case of missing support, applies the same patch than DDS files.
  82251. if (generateNonLODTextures) {
  82252. var mipSlices = 3;
  82253. var scale = texture._lodGenerationScale;
  82254. var offset = texture._lodGenerationOffset;
  82255. for (var i = 0; i < mipSlices; i++) {
  82256. //compute LOD from even spacing in smoothness (matching shader calculation)
  82257. var smoothness = i / (mipSlices - 1);
  82258. var roughness = 1 - smoothness;
  82259. var minLODIndex = offset; // roughness = 0
  82260. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82261. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82262. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82263. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82264. glTextureFromLod.isCube = true;
  82265. glTextureFromLod.invertY = true;
  82266. glTextureFromLod.generateMipMaps = false;
  82267. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82268. // Wrap in a base texture for easy binding.
  82269. var lodTexture = new BABYLON.BaseTexture(null);
  82270. lodTexture.isCube = true;
  82271. lodTexture._texture = glTextureFromLod;
  82272. lodTextures[mipmapIndex] = lodTexture;
  82273. switch (i) {
  82274. case 0:
  82275. texture._lodTextureLow = lodTexture;
  82276. break;
  82277. case 1:
  82278. texture._lodTextureMid = lodTexture;
  82279. break;
  82280. case 2:
  82281. texture._lodTextureHigh = lodTexture;
  82282. break;
  82283. }
  82284. }
  82285. }
  82286. }
  82287. var promises = [];
  82288. var _loop_3 = function (i) {
  82289. var _loop_4 = function (face) {
  82290. // Retrieves the face data
  82291. var imageData = specularInfo.mipmaps[i * 6 + face];
  82292. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82293. // Constructs an image element from bytes
  82294. var blob = new Blob([bytes], { type: 'image/png' });
  82295. var url = URL.createObjectURL(blob);
  82296. var image = new Image();
  82297. image.src = url;
  82298. // Enqueue promise to upload to the texture.
  82299. var promise = new Promise(function (resolve, reject) {
  82300. ;
  82301. image.onload = function () {
  82302. if (expandTexture) {
  82303. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82304. reject(message);
  82305. }, image);
  82306. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82307. // Uncompress the data to a RTT
  82308. rgbdPostProcess.onApply = function (effect) {
  82309. effect._bindTexture("textureSampler", tempTexture_1);
  82310. effect.setFloat2("scale", 1, 1);
  82311. };
  82312. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82313. // Cleanup
  82314. engine.restoreDefaultFramebuffer();
  82315. tempTexture_1.dispose();
  82316. window.URL.revokeObjectURL(url);
  82317. resolve();
  82318. });
  82319. }
  82320. else {
  82321. engine._uploadImageToTexture(texture, face, i, image);
  82322. // Upload the face to the none lod texture support
  82323. if (generateNonLODTextures) {
  82324. var lodTexture = lodTextures[i];
  82325. if (lodTexture) {
  82326. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82327. }
  82328. }
  82329. resolve();
  82330. }
  82331. };
  82332. image.onerror = function (error) {
  82333. reject(error);
  82334. };
  82335. });
  82336. promises.push(promise);
  82337. };
  82338. // All faces
  82339. for (var face = 0; face < 6; face++) {
  82340. _loop_4(face);
  82341. }
  82342. };
  82343. // All mipmaps
  82344. for (var i = 0; i < mipmapsCount; i++) {
  82345. _loop_3(i);
  82346. }
  82347. // Once all done, finishes the cleanup and return
  82348. return Promise.all(promises).then(function () {
  82349. // Relase temp RTT.
  82350. if (cubeRtt) {
  82351. engine._releaseFramebufferObjects(cubeRtt);
  82352. cubeRtt._swapAndDie(texture);
  82353. }
  82354. // Relase temp Post Process.
  82355. if (rgbdPostProcess) {
  82356. rgbdPostProcess.dispose();
  82357. }
  82358. // Flag internal texture as ready in case they are in use.
  82359. if (generateNonLODTextures) {
  82360. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82361. texture._lodTextureHigh._texture.isReady = true;
  82362. }
  82363. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82364. texture._lodTextureMid._texture.isReady = true;
  82365. }
  82366. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82367. texture._lodTextureLow._texture.isReady = true;
  82368. }
  82369. }
  82370. });
  82371. };
  82372. /**
  82373. * Uploads spherical polynomials information to the texture.
  82374. * @param texture defines the texture we are trying to upload the information to
  82375. * @param arrayBuffer defines the array buffer holding the data
  82376. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82377. */
  82378. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82379. if (info.version !== 1) {
  82380. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82381. }
  82382. var irradianceInfo = info.irradiance;
  82383. if (!irradianceInfo) {
  82384. return;
  82385. }
  82386. //harmonics now represent radiance
  82387. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82388. if (irradianceInfo.polynomials) {
  82389. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82390. }
  82391. else {
  82392. // convert From SH to SP.
  82393. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82394. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82395. }
  82396. };
  82397. /**
  82398. * Upload spherical polynomial coefficients to the texture
  82399. * @param polynmials Spherical polynmial coefficients (9)
  82400. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82401. */
  82402. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82403. outPolynomialCoefficents.x.x = polynmials.x[0];
  82404. outPolynomialCoefficents.x.y = polynmials.x[1];
  82405. outPolynomialCoefficents.x.z = polynmials.x[2];
  82406. outPolynomialCoefficents.y.x = polynmials.y[0];
  82407. outPolynomialCoefficents.y.y = polynmials.y[1];
  82408. outPolynomialCoefficents.y.z = polynmials.y[2];
  82409. outPolynomialCoefficents.z.x = polynmials.z[0];
  82410. outPolynomialCoefficents.z.y = polynmials.z[1];
  82411. outPolynomialCoefficents.z.z = polynmials.z[2];
  82412. //xx
  82413. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82414. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82415. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82416. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82417. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82418. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82419. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82420. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82421. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82422. //yz
  82423. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82424. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82425. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82426. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82427. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82428. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82429. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82430. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82431. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82432. };
  82433. /**
  82434. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82435. * L = (1/pi) * E * rho
  82436. *
  82437. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82438. * @param harmonics Spherical harmonic coefficients (9)
  82439. */
  82440. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82441. var scaleFactor = 1 / Math.PI;
  82442. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82443. // (The pixel shader must apply albedo after texture fetches, etc).
  82444. harmonics.l00[0] *= scaleFactor;
  82445. harmonics.l00[1] *= scaleFactor;
  82446. harmonics.l00[2] *= scaleFactor;
  82447. harmonics.l1_1[0] *= scaleFactor;
  82448. harmonics.l1_1[1] *= scaleFactor;
  82449. harmonics.l1_1[2] *= scaleFactor;
  82450. harmonics.l10[0] *= scaleFactor;
  82451. harmonics.l10[1] *= scaleFactor;
  82452. harmonics.l10[2] *= scaleFactor;
  82453. harmonics.l11[0] *= scaleFactor;
  82454. harmonics.l11[1] *= scaleFactor;
  82455. harmonics.l11[2] *= scaleFactor;
  82456. harmonics.l2_2[0] *= scaleFactor;
  82457. harmonics.l2_2[1] *= scaleFactor;
  82458. harmonics.l2_2[2] *= scaleFactor;
  82459. harmonics.l2_1[0] *= scaleFactor;
  82460. harmonics.l2_1[1] *= scaleFactor;
  82461. harmonics.l2_1[2] *= scaleFactor;
  82462. harmonics.l20[0] *= scaleFactor;
  82463. harmonics.l20[1] *= scaleFactor;
  82464. harmonics.l20[2] *= scaleFactor;
  82465. harmonics.l21[0] *= scaleFactor;
  82466. harmonics.l21[1] *= scaleFactor;
  82467. harmonics.l21[2] *= scaleFactor;
  82468. harmonics.l22[0] *= scaleFactor;
  82469. harmonics.l22[1] *= scaleFactor;
  82470. harmonics.l22[2] *= scaleFactor;
  82471. };
  82472. /**
  82473. * Convert spherical harmonics to spherical polynomial coefficients
  82474. * @param harmonics Spherical harmonic coefficients (9)
  82475. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82476. */
  82477. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82478. var rPi = 1 / Math.PI;
  82479. //x
  82480. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82481. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82482. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82483. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82484. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82485. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82486. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82487. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82488. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82489. //xx
  82490. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82491. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82492. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82493. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82494. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82495. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82496. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82497. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82498. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82499. //yz
  82500. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82501. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82502. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82503. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82504. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82505. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82506. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82507. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82508. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82509. };
  82510. /**
  82511. * Magic number identifying the env file.
  82512. */
  82513. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82514. return EnvironmentTextureTools;
  82515. }());
  82516. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82517. })(BABYLON || (BABYLON = {}));
  82518. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82519. var BABYLON;
  82520. (function (BABYLON) {
  82521. /**
  82522. * This represents a texture coming from an HDR input.
  82523. *
  82524. * The only supported format is currently panorama picture stored in RGBE format.
  82525. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82526. */
  82527. var HDRCubeTexture = /** @class */ (function (_super) {
  82528. __extends(HDRCubeTexture, _super);
  82529. /**
  82530. * Instantiates an HDRTexture from the following parameters.
  82531. *
  82532. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82533. * @param scene The scene the texture will be used in
  82534. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82535. * @param noMipmap Forces to not generate the mipmap if true
  82536. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82537. * @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)
  82538. * @param reserved Reserved flag for internal use.
  82539. */
  82540. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82541. if (noMipmap === void 0) { noMipmap = false; }
  82542. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82543. if (gammaSpace === void 0) { gammaSpace = false; }
  82544. if (reserved === void 0) { reserved = false; }
  82545. if (onLoad === void 0) { onLoad = null; }
  82546. if (onError === void 0) { onError = null; }
  82547. var _this = _super.call(this, scene) || this;
  82548. _this._generateHarmonics = true;
  82549. _this._onLoad = null;
  82550. _this._onError = null;
  82551. /**
  82552. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82553. */
  82554. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82555. _this._isBlocking = true;
  82556. _this._rotationY = 0;
  82557. /**
  82558. * Gets or sets the center of the bounding box associated with the cube texture
  82559. * It must define where the camera used to render the texture was set
  82560. */
  82561. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82562. if (!url) {
  82563. return _this;
  82564. }
  82565. _this.name = url;
  82566. _this.url = url;
  82567. _this.hasAlpha = false;
  82568. _this.isCube = true;
  82569. _this._textureMatrix = BABYLON.Matrix.Identity();
  82570. _this._onLoad = onLoad;
  82571. _this._onError = onError;
  82572. _this.gammaSpace = gammaSpace;
  82573. _this._noMipmap = noMipmap;
  82574. _this._size = size;
  82575. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82576. if (!_this._texture) {
  82577. if (!scene.useDelayedTextureLoading) {
  82578. _this.loadTexture();
  82579. }
  82580. else {
  82581. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82582. }
  82583. }
  82584. return _this;
  82585. }
  82586. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82587. /**
  82588. * Gets wether or not the texture is blocking during loading.
  82589. */
  82590. get: function () {
  82591. return this._isBlocking;
  82592. },
  82593. /**
  82594. * Sets wether or not the texture is blocking during loading.
  82595. */
  82596. set: function (value) {
  82597. this._isBlocking = value;
  82598. },
  82599. enumerable: true,
  82600. configurable: true
  82601. });
  82602. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82603. /**
  82604. * Gets texture matrix rotation angle around Y axis radians.
  82605. */
  82606. get: function () {
  82607. return this._rotationY;
  82608. },
  82609. /**
  82610. * Sets texture matrix rotation angle around Y axis in radians.
  82611. */
  82612. set: function (value) {
  82613. this._rotationY = value;
  82614. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82615. },
  82616. enumerable: true,
  82617. configurable: true
  82618. });
  82619. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82620. get: function () {
  82621. return this._boundingBoxSize;
  82622. },
  82623. /**
  82624. * Gets or sets the size of the bounding box associated with the cube texture
  82625. * When defined, the cubemap will switch to local mode
  82626. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82627. * @example https://www.babylonjs-playground.com/#RNASML
  82628. */
  82629. set: function (value) {
  82630. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82631. return;
  82632. }
  82633. this._boundingBoxSize = value;
  82634. var scene = this.getScene();
  82635. if (scene) {
  82636. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82637. }
  82638. },
  82639. enumerable: true,
  82640. configurable: true
  82641. });
  82642. /**
  82643. * Occurs when the file is raw .hdr file.
  82644. */
  82645. HDRCubeTexture.prototype.loadTexture = function () {
  82646. var _this = this;
  82647. var callback = function (buffer) {
  82648. _this.lodGenerationOffset = 0.0;
  82649. _this.lodGenerationScale = 0.8;
  82650. var scene = _this.getScene();
  82651. if (!scene) {
  82652. return null;
  82653. }
  82654. // Extract the raw linear data.
  82655. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82656. // Generate harmonics if needed.
  82657. if (_this._generateHarmonics) {
  82658. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82659. _this.sphericalPolynomial = sphericalPolynomial;
  82660. }
  82661. var results = [];
  82662. var byteArray = null;
  82663. // Push each faces.
  82664. for (var j = 0; j < 6; j++) {
  82665. // Create uintarray fallback.
  82666. if (!scene.getEngine().getCaps().textureFloat) {
  82667. // 3 channels of 1 bytes per pixel in bytes.
  82668. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82669. byteArray = new Uint8Array(byteBuffer);
  82670. }
  82671. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82672. // If special cases.
  82673. if (_this.gammaSpace || byteArray) {
  82674. for (var i = 0; i < _this._size * _this._size; i++) {
  82675. // Put in gamma space if requested.
  82676. if (_this.gammaSpace) {
  82677. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82678. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82679. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82680. }
  82681. // Convert to int texture for fallback.
  82682. if (byteArray) {
  82683. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82684. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82685. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82686. // May use luminance instead if the result is not accurate.
  82687. var max = Math.max(Math.max(r, g), b);
  82688. if (max > 255) {
  82689. var scale = 255 / max;
  82690. r *= scale;
  82691. g *= scale;
  82692. b *= scale;
  82693. }
  82694. byteArray[(i * 3) + 0] = r;
  82695. byteArray[(i * 3) + 1] = g;
  82696. byteArray[(i * 3) + 2] = b;
  82697. }
  82698. }
  82699. }
  82700. if (byteArray) {
  82701. results.push(byteArray);
  82702. }
  82703. else {
  82704. results.push(dataFace);
  82705. }
  82706. }
  82707. return results;
  82708. };
  82709. var scene = this.getScene();
  82710. if (scene) {
  82711. 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);
  82712. }
  82713. };
  82714. HDRCubeTexture.prototype.clone = function () {
  82715. var scene = this.getScene();
  82716. if (!scene) {
  82717. return this;
  82718. }
  82719. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82720. // Base texture
  82721. newTexture.level = this.level;
  82722. newTexture.wrapU = this.wrapU;
  82723. newTexture.wrapV = this.wrapV;
  82724. newTexture.coordinatesIndex = this.coordinatesIndex;
  82725. newTexture.coordinatesMode = this.coordinatesMode;
  82726. return newTexture;
  82727. };
  82728. // Methods
  82729. HDRCubeTexture.prototype.delayLoad = function () {
  82730. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82731. return;
  82732. }
  82733. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82734. this._texture = this._getFromCache(this.url, this._noMipmap);
  82735. if (!this._texture) {
  82736. this.loadTexture();
  82737. }
  82738. };
  82739. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82740. return this._textureMatrix;
  82741. };
  82742. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82743. this._textureMatrix = value;
  82744. };
  82745. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82746. var texture = null;
  82747. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82748. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82749. texture.name = parsedTexture.name;
  82750. texture.hasAlpha = parsedTexture.hasAlpha;
  82751. texture.level = parsedTexture.level;
  82752. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82753. texture.isBlocking = parsedTexture.isBlocking;
  82754. }
  82755. if (texture) {
  82756. if (parsedTexture.boundingBoxPosition) {
  82757. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82758. }
  82759. if (parsedTexture.boundingBoxSize) {
  82760. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82761. }
  82762. if (parsedTexture.rotationY) {
  82763. texture.rotationY = parsedTexture.rotationY;
  82764. }
  82765. }
  82766. return texture;
  82767. };
  82768. HDRCubeTexture.prototype.serialize = function () {
  82769. if (!this.name) {
  82770. return null;
  82771. }
  82772. var serializationObject = {};
  82773. serializationObject.name = this.name;
  82774. serializationObject.hasAlpha = this.hasAlpha;
  82775. serializationObject.isCube = true;
  82776. serializationObject.level = this.level;
  82777. serializationObject.size = this._size;
  82778. serializationObject.coordinatesMode = this.coordinatesMode;
  82779. serializationObject.useInGammaSpace = this.gammaSpace;
  82780. serializationObject.generateHarmonics = this._generateHarmonics;
  82781. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82782. serializationObject.noMipmap = this._noMipmap;
  82783. serializationObject.isBlocking = this._isBlocking;
  82784. serializationObject.rotationY = this._rotationY;
  82785. return serializationObject;
  82786. };
  82787. HDRCubeTexture._facesMapping = [
  82788. "right",
  82789. "left",
  82790. "up",
  82791. "down",
  82792. "front",
  82793. "back"
  82794. ];
  82795. return HDRCubeTexture;
  82796. }(BABYLON.BaseTexture));
  82797. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82798. })(BABYLON || (BABYLON = {}));
  82799. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82800. var BABYLON;
  82801. (function (BABYLON) {
  82802. var IndexedVector2 = /** @class */ (function (_super) {
  82803. __extends(IndexedVector2, _super);
  82804. function IndexedVector2(original, index) {
  82805. var _this = _super.call(this, original.x, original.y) || this;
  82806. _this.index = index;
  82807. return _this;
  82808. }
  82809. return IndexedVector2;
  82810. }(BABYLON.Vector2));
  82811. var PolygonPoints = /** @class */ (function () {
  82812. function PolygonPoints() {
  82813. this.elements = new Array();
  82814. }
  82815. PolygonPoints.prototype.add = function (originalPoints) {
  82816. var _this = this;
  82817. var result = new Array();
  82818. originalPoints.forEach(function (point) {
  82819. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82820. var newPoint = new IndexedVector2(point, _this.elements.length);
  82821. result.push(newPoint);
  82822. _this.elements.push(newPoint);
  82823. }
  82824. });
  82825. return result;
  82826. };
  82827. PolygonPoints.prototype.computeBounds = function () {
  82828. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82829. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82830. this.elements.forEach(function (point) {
  82831. // x
  82832. if (point.x < lmin.x) {
  82833. lmin.x = point.x;
  82834. }
  82835. else if (point.x > lmax.x) {
  82836. lmax.x = point.x;
  82837. }
  82838. // y
  82839. if (point.y < lmin.y) {
  82840. lmin.y = point.y;
  82841. }
  82842. else if (point.y > lmax.y) {
  82843. lmax.y = point.y;
  82844. }
  82845. });
  82846. return {
  82847. min: lmin,
  82848. max: lmax,
  82849. width: lmax.x - lmin.x,
  82850. height: lmax.y - lmin.y
  82851. };
  82852. };
  82853. return PolygonPoints;
  82854. }());
  82855. var Polygon = /** @class */ (function () {
  82856. function Polygon() {
  82857. }
  82858. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82859. return [
  82860. new BABYLON.Vector2(xmin, ymin),
  82861. new BABYLON.Vector2(xmax, ymin),
  82862. new BABYLON.Vector2(xmax, ymax),
  82863. new BABYLON.Vector2(xmin, ymax)
  82864. ];
  82865. };
  82866. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82867. if (cx === void 0) { cx = 0; }
  82868. if (cy === void 0) { cy = 0; }
  82869. if (numberOfSides === void 0) { numberOfSides = 32; }
  82870. var result = new Array();
  82871. var angle = 0;
  82872. var increment = (Math.PI * 2) / numberOfSides;
  82873. for (var i = 0; i < numberOfSides; i++) {
  82874. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82875. angle -= increment;
  82876. }
  82877. return result;
  82878. };
  82879. Polygon.Parse = function (input) {
  82880. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82881. var i, result = [];
  82882. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82883. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82884. }
  82885. return result;
  82886. };
  82887. Polygon.StartingAt = function (x, y) {
  82888. return BABYLON.Path2.StartingAt(x, y);
  82889. };
  82890. return Polygon;
  82891. }());
  82892. BABYLON.Polygon = Polygon;
  82893. var PolygonMeshBuilder = /** @class */ (function () {
  82894. function PolygonMeshBuilder(name, contours, scene) {
  82895. this._points = new PolygonPoints();
  82896. this._outlinepoints = new PolygonPoints();
  82897. this._holes = new Array();
  82898. this._epoints = new Array();
  82899. this._eholes = new Array();
  82900. this._name = name;
  82901. this._scene = scene;
  82902. var points;
  82903. if (contours instanceof BABYLON.Path2) {
  82904. points = contours.getPoints();
  82905. }
  82906. else {
  82907. points = contours;
  82908. }
  82909. this._addToepoint(points);
  82910. this._points.add(points);
  82911. this._outlinepoints.add(points);
  82912. if (typeof earcut === 'undefined') {
  82913. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82914. }
  82915. }
  82916. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82917. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82918. var p = points_1[_i];
  82919. this._epoints.push(p.x, p.y);
  82920. }
  82921. };
  82922. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82923. this._points.add(hole);
  82924. var holepoints = new PolygonPoints();
  82925. holepoints.add(hole);
  82926. this._holes.push(holepoints);
  82927. this._eholes.push(this._epoints.length / 2);
  82928. this._addToepoint(hole);
  82929. return this;
  82930. };
  82931. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82932. var _this = this;
  82933. if (updatable === void 0) { updatable = false; }
  82934. if (depth === void 0) { depth = 0; }
  82935. var result = new BABYLON.Mesh(this._name, this._scene);
  82936. var normals = new Array();
  82937. var positions = new Array();
  82938. var uvs = new Array();
  82939. var bounds = this._points.computeBounds();
  82940. this._points.elements.forEach(function (p) {
  82941. normals.push(0, 1.0, 0);
  82942. positions.push(p.x, 0, p.y);
  82943. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82944. });
  82945. var indices = new Array();
  82946. var res = earcut(this._epoints, this._eholes, 2);
  82947. for (var i = 0; i < res.length; i++) {
  82948. indices.push(res[i]);
  82949. }
  82950. if (depth > 0) {
  82951. var positionscount = (positions.length / 3); //get the current pointcount
  82952. this._points.elements.forEach(function (p) {
  82953. normals.push(0, -1.0, 0);
  82954. positions.push(p.x, -depth, p.y);
  82955. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82956. });
  82957. var totalCount = indices.length;
  82958. for (var i = 0; i < totalCount; i += 3) {
  82959. var i0 = indices[i + 0];
  82960. var i1 = indices[i + 1];
  82961. var i2 = indices[i + 2];
  82962. indices.push(i2 + positionscount);
  82963. indices.push(i1 + positionscount);
  82964. indices.push(i0 + positionscount);
  82965. }
  82966. //Add the sides
  82967. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82968. this._holes.forEach(function (hole) {
  82969. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82970. });
  82971. }
  82972. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82973. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82974. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82975. result.setIndices(indices);
  82976. return result;
  82977. };
  82978. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82979. var StartIndex = positions.length / 3;
  82980. var ulength = 0;
  82981. for (var i = 0; i < points.elements.length; i++) {
  82982. var p = points.elements[i];
  82983. var p1;
  82984. if ((i + 1) > points.elements.length - 1) {
  82985. p1 = points.elements[0];
  82986. }
  82987. else {
  82988. p1 = points.elements[i + 1];
  82989. }
  82990. positions.push(p.x, 0, p.y);
  82991. positions.push(p.x, -depth, p.y);
  82992. positions.push(p1.x, 0, p1.y);
  82993. positions.push(p1.x, -depth, p1.y);
  82994. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82995. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82996. var v3 = v2.subtract(v1);
  82997. var v4 = new BABYLON.Vector3(0, 1, 0);
  82998. var vn = BABYLON.Vector3.Cross(v3, v4);
  82999. vn = vn.normalize();
  83000. uvs.push(ulength / bounds.width, 0);
  83001. uvs.push(ulength / bounds.width, 1);
  83002. ulength += v3.length();
  83003. uvs.push((ulength / bounds.width), 0);
  83004. uvs.push((ulength / bounds.width), 1);
  83005. if (!flip) {
  83006. normals.push(-vn.x, -vn.y, -vn.z);
  83007. normals.push(-vn.x, -vn.y, -vn.z);
  83008. normals.push(-vn.x, -vn.y, -vn.z);
  83009. normals.push(-vn.x, -vn.y, -vn.z);
  83010. indices.push(StartIndex);
  83011. indices.push(StartIndex + 1);
  83012. indices.push(StartIndex + 2);
  83013. indices.push(StartIndex + 1);
  83014. indices.push(StartIndex + 3);
  83015. indices.push(StartIndex + 2);
  83016. }
  83017. else {
  83018. normals.push(vn.x, vn.y, vn.z);
  83019. normals.push(vn.x, vn.y, vn.z);
  83020. normals.push(vn.x, vn.y, vn.z);
  83021. normals.push(vn.x, vn.y, vn.z);
  83022. indices.push(StartIndex);
  83023. indices.push(StartIndex + 2);
  83024. indices.push(StartIndex + 1);
  83025. indices.push(StartIndex + 1);
  83026. indices.push(StartIndex + 2);
  83027. indices.push(StartIndex + 3);
  83028. }
  83029. StartIndex += 4;
  83030. }
  83031. ;
  83032. };
  83033. return PolygonMeshBuilder;
  83034. }());
  83035. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83036. })(BABYLON || (BABYLON = {}));
  83037. //# sourceMappingURL=babylon.polygonMesh.js.map
  83038. var BABYLON;
  83039. (function (BABYLON) {
  83040. // Unique ID when we import meshes from Babylon to CSG
  83041. var currentCSGMeshId = 0;
  83042. // # class Vertex
  83043. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83044. // one to provide additional features like texture coordinates and vertex
  83045. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83046. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83047. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83048. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83049. // is not used anywhere else.
  83050. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83051. var Vertex = /** @class */ (function () {
  83052. function Vertex(pos, normal, uv) {
  83053. this.pos = pos;
  83054. this.normal = normal;
  83055. this.uv = uv;
  83056. }
  83057. Vertex.prototype.clone = function () {
  83058. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83059. };
  83060. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83061. // orientation of a polygon is flipped.
  83062. Vertex.prototype.flip = function () {
  83063. this.normal = this.normal.scale(-1);
  83064. };
  83065. // Create a new vertex between this vertex and `other` by linearly
  83066. // interpolating all properties using a parameter of `t`. Subclasses should
  83067. // override this to interpolate additional properties.
  83068. Vertex.prototype.interpolate = function (other, t) {
  83069. 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));
  83070. };
  83071. return Vertex;
  83072. }());
  83073. // # class Plane
  83074. // Represents a plane in 3D space.
  83075. var Plane = /** @class */ (function () {
  83076. function Plane(normal, w) {
  83077. this.normal = normal;
  83078. this.w = w;
  83079. }
  83080. Plane.FromPoints = function (a, b, c) {
  83081. var v0 = c.subtract(a);
  83082. var v1 = b.subtract(a);
  83083. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83084. return null;
  83085. }
  83086. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83087. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83088. };
  83089. Plane.prototype.clone = function () {
  83090. return new Plane(this.normal.clone(), this.w);
  83091. };
  83092. Plane.prototype.flip = function () {
  83093. this.normal.scaleInPlace(-1);
  83094. this.w = -this.w;
  83095. };
  83096. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83097. // fragments in the appropriate lists. Coplanar polygons go into either
  83098. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83099. // respect to this plane. Polygons in front or in back of this plane go into
  83100. // either `front` or `back`.
  83101. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83102. var COPLANAR = 0;
  83103. var FRONT = 1;
  83104. var BACK = 2;
  83105. var SPANNING = 3;
  83106. // Classify each point as well as the entire polygon into one of the above
  83107. // four classes.
  83108. var polygonType = 0;
  83109. var types = [];
  83110. var i;
  83111. var t;
  83112. for (i = 0; i < polygon.vertices.length; i++) {
  83113. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83114. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83115. polygonType |= type;
  83116. types.push(type);
  83117. }
  83118. // Put the polygon in the correct list, splitting it when necessary.
  83119. switch (polygonType) {
  83120. case COPLANAR:
  83121. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83122. break;
  83123. case FRONT:
  83124. front.push(polygon);
  83125. break;
  83126. case BACK:
  83127. back.push(polygon);
  83128. break;
  83129. case SPANNING:
  83130. var f = [], b = [];
  83131. for (i = 0; i < polygon.vertices.length; i++) {
  83132. var j = (i + 1) % polygon.vertices.length;
  83133. var ti = types[i], tj = types[j];
  83134. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83135. if (ti !== BACK)
  83136. f.push(vi);
  83137. if (ti !== FRONT)
  83138. b.push(ti !== BACK ? vi.clone() : vi);
  83139. if ((ti | tj) === SPANNING) {
  83140. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83141. var v = vi.interpolate(vj, t);
  83142. f.push(v);
  83143. b.push(v.clone());
  83144. }
  83145. }
  83146. var poly;
  83147. if (f.length >= 3) {
  83148. poly = new Polygon(f, polygon.shared);
  83149. if (poly.plane)
  83150. front.push(poly);
  83151. }
  83152. if (b.length >= 3) {
  83153. poly = new Polygon(b, polygon.shared);
  83154. if (poly.plane)
  83155. back.push(poly);
  83156. }
  83157. break;
  83158. }
  83159. };
  83160. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83161. // point is on the plane.
  83162. Plane.EPSILON = 1e-5;
  83163. return Plane;
  83164. }());
  83165. // # class Polygon
  83166. // Represents a convex polygon. The vertices used to initialize a polygon must
  83167. // be coplanar and form a convex loop.
  83168. //
  83169. // Each convex polygon has a `shared` property, which is shared between all
  83170. // polygons that are clones of each other or were split from the same polygon.
  83171. // This can be used to define per-polygon properties (such as surface color).
  83172. var Polygon = /** @class */ (function () {
  83173. function Polygon(vertices, shared) {
  83174. this.vertices = vertices;
  83175. this.shared = shared;
  83176. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83177. }
  83178. Polygon.prototype.clone = function () {
  83179. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83180. return new Polygon(vertices, this.shared);
  83181. };
  83182. Polygon.prototype.flip = function () {
  83183. this.vertices.reverse().map(function (v) { v.flip(); });
  83184. this.plane.flip();
  83185. };
  83186. return Polygon;
  83187. }());
  83188. // # class Node
  83189. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83190. // by picking a polygon to split along. That polygon (and all other coplanar
  83191. // polygons) are added directly to that node and the other polygons are added to
  83192. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83193. // no distinction between internal and leaf nodes.
  83194. var Node = /** @class */ (function () {
  83195. function Node(polygons) {
  83196. this.plane = null;
  83197. this.front = null;
  83198. this.back = null;
  83199. this.polygons = new Array();
  83200. if (polygons) {
  83201. this.build(polygons);
  83202. }
  83203. }
  83204. Node.prototype.clone = function () {
  83205. var node = new Node();
  83206. node.plane = this.plane && this.plane.clone();
  83207. node.front = this.front && this.front.clone();
  83208. node.back = this.back && this.back.clone();
  83209. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83210. return node;
  83211. };
  83212. // Convert solid space to empty space and empty space to solid space.
  83213. Node.prototype.invert = function () {
  83214. for (var i = 0; i < this.polygons.length; i++) {
  83215. this.polygons[i].flip();
  83216. }
  83217. if (this.plane) {
  83218. this.plane.flip();
  83219. }
  83220. if (this.front) {
  83221. this.front.invert();
  83222. }
  83223. if (this.back) {
  83224. this.back.invert();
  83225. }
  83226. var temp = this.front;
  83227. this.front = this.back;
  83228. this.back = temp;
  83229. };
  83230. // Recursively remove all polygons in `polygons` that are inside this BSP
  83231. // tree.
  83232. Node.prototype.clipPolygons = function (polygons) {
  83233. if (!this.plane)
  83234. return polygons.slice();
  83235. var front = new Array(), back = new Array();
  83236. for (var i = 0; i < polygons.length; i++) {
  83237. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83238. }
  83239. if (this.front) {
  83240. front = this.front.clipPolygons(front);
  83241. }
  83242. if (this.back) {
  83243. back = this.back.clipPolygons(back);
  83244. }
  83245. else {
  83246. back = [];
  83247. }
  83248. return front.concat(back);
  83249. };
  83250. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83251. // `bsp`.
  83252. Node.prototype.clipTo = function (bsp) {
  83253. this.polygons = bsp.clipPolygons(this.polygons);
  83254. if (this.front)
  83255. this.front.clipTo(bsp);
  83256. if (this.back)
  83257. this.back.clipTo(bsp);
  83258. };
  83259. // Return a list of all polygons in this BSP tree.
  83260. Node.prototype.allPolygons = function () {
  83261. var polygons = this.polygons.slice();
  83262. if (this.front)
  83263. polygons = polygons.concat(this.front.allPolygons());
  83264. if (this.back)
  83265. polygons = polygons.concat(this.back.allPolygons());
  83266. return polygons;
  83267. };
  83268. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83269. // new polygons are filtered down to the bottom of the tree and become new
  83270. // nodes there. Each set of polygons is partitioned using the first polygon
  83271. // (no heuristic is used to pick a good split).
  83272. Node.prototype.build = function (polygons) {
  83273. if (!polygons.length)
  83274. return;
  83275. if (!this.plane)
  83276. this.plane = polygons[0].plane.clone();
  83277. var front = new Array(), back = new Array();
  83278. for (var i = 0; i < polygons.length; i++) {
  83279. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83280. }
  83281. if (front.length) {
  83282. if (!this.front)
  83283. this.front = new Node();
  83284. this.front.build(front);
  83285. }
  83286. if (back.length) {
  83287. if (!this.back)
  83288. this.back = new Node();
  83289. this.back.build(back);
  83290. }
  83291. };
  83292. return Node;
  83293. }());
  83294. var CSG = /** @class */ (function () {
  83295. function CSG() {
  83296. this.polygons = new Array();
  83297. }
  83298. // Convert BABYLON.Mesh to BABYLON.CSG
  83299. CSG.FromMesh = function (mesh) {
  83300. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83301. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83302. if (mesh instanceof BABYLON.Mesh) {
  83303. mesh.computeWorldMatrix(true);
  83304. matrix = mesh.getWorldMatrix();
  83305. meshPosition = mesh.position.clone();
  83306. meshRotation = mesh.rotation.clone();
  83307. if (mesh.rotationQuaternion) {
  83308. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83309. }
  83310. meshScaling = mesh.scaling.clone();
  83311. }
  83312. else {
  83313. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83314. }
  83315. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83316. var subMeshes = mesh.subMeshes;
  83317. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83318. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83319. vertices = [];
  83320. for (var j = 0; j < 3; j++) {
  83321. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83322. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83323. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83324. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83325. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83326. vertex = new Vertex(position, normal, uv);
  83327. vertices.push(vertex);
  83328. }
  83329. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83330. // To handle the case of degenerated triangle
  83331. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83332. if (polygon.plane)
  83333. polygons.push(polygon);
  83334. }
  83335. }
  83336. var csg = CSG.FromPolygons(polygons);
  83337. csg.matrix = matrix;
  83338. csg.position = meshPosition;
  83339. csg.rotation = meshRotation;
  83340. csg.scaling = meshScaling;
  83341. csg.rotationQuaternion = meshRotationQuaternion;
  83342. currentCSGMeshId++;
  83343. return csg;
  83344. };
  83345. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83346. CSG.FromPolygons = function (polygons) {
  83347. var csg = new CSG();
  83348. csg.polygons = polygons;
  83349. return csg;
  83350. };
  83351. CSG.prototype.clone = function () {
  83352. var csg = new CSG();
  83353. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83354. csg.copyTransformAttributes(this);
  83355. return csg;
  83356. };
  83357. CSG.prototype.union = function (csg) {
  83358. var a = new Node(this.clone().polygons);
  83359. var b = new Node(csg.clone().polygons);
  83360. a.clipTo(b);
  83361. b.clipTo(a);
  83362. b.invert();
  83363. b.clipTo(a);
  83364. b.invert();
  83365. a.build(b.allPolygons());
  83366. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83367. };
  83368. CSG.prototype.unionInPlace = function (csg) {
  83369. var a = new Node(this.polygons);
  83370. var b = new Node(csg.polygons);
  83371. a.clipTo(b);
  83372. b.clipTo(a);
  83373. b.invert();
  83374. b.clipTo(a);
  83375. b.invert();
  83376. a.build(b.allPolygons());
  83377. this.polygons = a.allPolygons();
  83378. };
  83379. CSG.prototype.subtract = function (csg) {
  83380. var a = new Node(this.clone().polygons);
  83381. var b = new Node(csg.clone().polygons);
  83382. a.invert();
  83383. a.clipTo(b);
  83384. b.clipTo(a);
  83385. b.invert();
  83386. b.clipTo(a);
  83387. b.invert();
  83388. a.build(b.allPolygons());
  83389. a.invert();
  83390. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83391. };
  83392. CSG.prototype.subtractInPlace = function (csg) {
  83393. var a = new Node(this.polygons);
  83394. var b = new Node(csg.polygons);
  83395. a.invert();
  83396. a.clipTo(b);
  83397. b.clipTo(a);
  83398. b.invert();
  83399. b.clipTo(a);
  83400. b.invert();
  83401. a.build(b.allPolygons());
  83402. a.invert();
  83403. this.polygons = a.allPolygons();
  83404. };
  83405. CSG.prototype.intersect = function (csg) {
  83406. var a = new Node(this.clone().polygons);
  83407. var b = new Node(csg.clone().polygons);
  83408. a.invert();
  83409. b.clipTo(a);
  83410. b.invert();
  83411. a.clipTo(b);
  83412. b.clipTo(a);
  83413. a.build(b.allPolygons());
  83414. a.invert();
  83415. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83416. };
  83417. CSG.prototype.intersectInPlace = function (csg) {
  83418. var a = new Node(this.polygons);
  83419. var b = new Node(csg.polygons);
  83420. a.invert();
  83421. b.clipTo(a);
  83422. b.invert();
  83423. a.clipTo(b);
  83424. b.clipTo(a);
  83425. a.build(b.allPolygons());
  83426. a.invert();
  83427. this.polygons = a.allPolygons();
  83428. };
  83429. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83430. // not modified.
  83431. CSG.prototype.inverse = function () {
  83432. var csg = this.clone();
  83433. csg.inverseInPlace();
  83434. return csg;
  83435. };
  83436. CSG.prototype.inverseInPlace = function () {
  83437. this.polygons.map(function (p) { p.flip(); });
  83438. };
  83439. // This is used to keep meshes transformations so they can be restored
  83440. // when we build back a Babylon Mesh
  83441. // NB : All CSG operations are performed in world coordinates
  83442. CSG.prototype.copyTransformAttributes = function (csg) {
  83443. this.matrix = csg.matrix;
  83444. this.position = csg.position;
  83445. this.rotation = csg.rotation;
  83446. this.scaling = csg.scaling;
  83447. this.rotationQuaternion = csg.rotationQuaternion;
  83448. return this;
  83449. };
  83450. // Build Raw mesh from CSG
  83451. // Coordinates here are in world space
  83452. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83453. var matrix = this.matrix.clone();
  83454. matrix.invert();
  83455. 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;
  83456. if (keepSubMeshes) {
  83457. // Sort Polygons, since subMeshes are indices range
  83458. polygons.sort(function (a, b) {
  83459. if (a.shared.meshId === b.shared.meshId) {
  83460. return a.shared.subMeshId - b.shared.subMeshId;
  83461. }
  83462. else {
  83463. return a.shared.meshId - b.shared.meshId;
  83464. }
  83465. });
  83466. }
  83467. for (var i = 0, il = polygons.length; i < il; i++) {
  83468. polygon = polygons[i];
  83469. // Building SubMeshes
  83470. if (!subMesh_dict[polygon.shared.meshId]) {
  83471. subMesh_dict[polygon.shared.meshId] = {};
  83472. }
  83473. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83474. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83475. indexStart: +Infinity,
  83476. indexEnd: -Infinity,
  83477. materialIndex: polygon.shared.materialIndex
  83478. };
  83479. }
  83480. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83481. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83482. polygonIndices[0] = 0;
  83483. polygonIndices[1] = j - 1;
  83484. polygonIndices[2] = j;
  83485. for (var k = 0; k < 3; k++) {
  83486. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83487. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83488. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83489. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83490. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83491. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83492. // Check if 2 points can be merged
  83493. if (!(typeof vertex_idx !== 'undefined' &&
  83494. normals[vertex_idx * 3] === localNormal.x &&
  83495. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83496. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83497. uvs[vertex_idx * 2] === uv.x &&
  83498. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83499. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83500. uvs.push(uv.x, uv.y);
  83501. normals.push(normal.x, normal.y, normal.z);
  83502. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83503. }
  83504. indices.push(vertex_idx);
  83505. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83506. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83507. currentIndex++;
  83508. }
  83509. }
  83510. }
  83511. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83512. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83513. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83514. mesh.setIndices(indices, null);
  83515. if (keepSubMeshes) {
  83516. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83517. var materialIndexOffset = 0, materialMaxIndex;
  83518. mesh.subMeshes = new Array();
  83519. for (var m in subMesh_dict) {
  83520. materialMaxIndex = -1;
  83521. for (var sm in subMesh_dict[m]) {
  83522. subMesh_obj = subMesh_dict[m][sm];
  83523. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83524. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83525. }
  83526. materialIndexOffset += ++materialMaxIndex;
  83527. }
  83528. }
  83529. return mesh;
  83530. };
  83531. // Build Mesh from CSG taking material and transforms into account
  83532. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83533. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83534. mesh.material = material;
  83535. mesh.position.copyFrom(this.position);
  83536. mesh.rotation.copyFrom(this.rotation);
  83537. if (this.rotationQuaternion) {
  83538. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83539. }
  83540. mesh.scaling.copyFrom(this.scaling);
  83541. mesh.computeWorldMatrix(true);
  83542. return mesh;
  83543. };
  83544. return CSG;
  83545. }());
  83546. BABYLON.CSG = CSG;
  83547. })(BABYLON || (BABYLON = {}));
  83548. //# sourceMappingURL=babylon.csg.js.map
  83549. var BABYLON;
  83550. (function (BABYLON) {
  83551. var LensFlare = /** @class */ (function () {
  83552. function LensFlare(size, position, color, imgUrl, system) {
  83553. this.size = size;
  83554. this.position = position;
  83555. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83556. this.color = color || new BABYLON.Color3(1, 1, 1);
  83557. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83558. this._system = system;
  83559. system.lensFlares.push(this);
  83560. }
  83561. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83562. return new LensFlare(size, position, color, imgUrl, system);
  83563. };
  83564. LensFlare.prototype.dispose = function () {
  83565. if (this.texture) {
  83566. this.texture.dispose();
  83567. }
  83568. // Remove from scene
  83569. var index = this._system.lensFlares.indexOf(this);
  83570. this._system.lensFlares.splice(index, 1);
  83571. };
  83572. ;
  83573. return LensFlare;
  83574. }());
  83575. BABYLON.LensFlare = LensFlare;
  83576. })(BABYLON || (BABYLON = {}));
  83577. //# sourceMappingURL=babylon.lensFlare.js.map
  83578. var BABYLON;
  83579. (function (BABYLON) {
  83580. var LensFlareSystem = /** @class */ (function () {
  83581. function LensFlareSystem(name, emitter, scene) {
  83582. this.name = name;
  83583. this.lensFlares = new Array();
  83584. this.borderLimit = 300;
  83585. this.viewportBorder = 0;
  83586. this.layerMask = 0x0FFFFFFF;
  83587. this._vertexBuffers = {};
  83588. this._isEnabled = true;
  83589. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83590. this._emitter = emitter;
  83591. this.id = name;
  83592. scene.lensFlareSystems.push(this);
  83593. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83594. var engine = scene.getEngine();
  83595. // VBO
  83596. var vertices = [];
  83597. vertices.push(1, 1);
  83598. vertices.push(-1, 1);
  83599. vertices.push(-1, -1);
  83600. vertices.push(1, -1);
  83601. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83602. // Indices
  83603. var indices = [];
  83604. indices.push(0);
  83605. indices.push(1);
  83606. indices.push(2);
  83607. indices.push(0);
  83608. indices.push(2);
  83609. indices.push(3);
  83610. this._indexBuffer = engine.createIndexBuffer(indices);
  83611. // Effects
  83612. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83613. }
  83614. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83615. get: function () {
  83616. return this._isEnabled;
  83617. },
  83618. set: function (value) {
  83619. this._isEnabled = value;
  83620. },
  83621. enumerable: true,
  83622. configurable: true
  83623. });
  83624. LensFlareSystem.prototype.getScene = function () {
  83625. return this._scene;
  83626. };
  83627. LensFlareSystem.prototype.getEmitter = function () {
  83628. return this._emitter;
  83629. };
  83630. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83631. this._emitter = newEmitter;
  83632. };
  83633. LensFlareSystem.prototype.getEmitterPosition = function () {
  83634. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83635. };
  83636. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83637. var position = this.getEmitterPosition();
  83638. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83639. this._positionX = position.x;
  83640. this._positionY = position.y;
  83641. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83642. if (this.viewportBorder > 0) {
  83643. globalViewport.x -= this.viewportBorder;
  83644. globalViewport.y -= this.viewportBorder;
  83645. globalViewport.width += this.viewportBorder * 2;
  83646. globalViewport.height += this.viewportBorder * 2;
  83647. position.x += this.viewportBorder;
  83648. position.y += this.viewportBorder;
  83649. this._positionX += this.viewportBorder;
  83650. this._positionY += this.viewportBorder;
  83651. }
  83652. if (position.z > 0) {
  83653. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83654. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83655. return true;
  83656. }
  83657. return true;
  83658. }
  83659. return false;
  83660. };
  83661. LensFlareSystem.prototype._isVisible = function () {
  83662. if (!this._isEnabled || !this._scene.activeCamera) {
  83663. return false;
  83664. }
  83665. var emitterPosition = this.getEmitterPosition();
  83666. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83667. var distance = direction.length();
  83668. direction.normalize();
  83669. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83670. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83671. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83672. };
  83673. LensFlareSystem.prototype.render = function () {
  83674. if (!this._effect.isReady() || !this._scene.activeCamera)
  83675. return false;
  83676. var engine = this._scene.getEngine();
  83677. var viewport = this._scene.activeCamera.viewport;
  83678. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83679. // Position
  83680. if (!this.computeEffectivePosition(globalViewport)) {
  83681. return false;
  83682. }
  83683. // Visibility
  83684. if (!this._isVisible()) {
  83685. return false;
  83686. }
  83687. // Intensity
  83688. var awayX;
  83689. var awayY;
  83690. if (this._positionX < this.borderLimit + globalViewport.x) {
  83691. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83692. }
  83693. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83694. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83695. }
  83696. else {
  83697. awayX = 0;
  83698. }
  83699. if (this._positionY < this.borderLimit + globalViewport.y) {
  83700. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83701. }
  83702. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83703. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83704. }
  83705. else {
  83706. awayY = 0;
  83707. }
  83708. var away = (awayX > awayY) ? awayX : awayY;
  83709. away -= this.viewportBorder;
  83710. if (away > this.borderLimit) {
  83711. away = this.borderLimit;
  83712. }
  83713. var intensity = 1.0 - (away / this.borderLimit);
  83714. if (intensity < 0) {
  83715. return false;
  83716. }
  83717. if (intensity > 1.0) {
  83718. intensity = 1.0;
  83719. }
  83720. if (this.viewportBorder > 0) {
  83721. globalViewport.x += this.viewportBorder;
  83722. globalViewport.y += this.viewportBorder;
  83723. globalViewport.width -= this.viewportBorder * 2;
  83724. globalViewport.height -= this.viewportBorder * 2;
  83725. this._positionX -= this.viewportBorder;
  83726. this._positionY -= this.viewportBorder;
  83727. }
  83728. // Position
  83729. var centerX = globalViewport.x + globalViewport.width / 2;
  83730. var centerY = globalViewport.y + globalViewport.height / 2;
  83731. var distX = centerX - this._positionX;
  83732. var distY = centerY - this._positionY;
  83733. // Effects
  83734. engine.enableEffect(this._effect);
  83735. engine.setState(false);
  83736. engine.setDepthBuffer(false);
  83737. // VBOs
  83738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83739. // Flares
  83740. for (var index = 0; index < this.lensFlares.length; index++) {
  83741. var flare = this.lensFlares[index];
  83742. engine.setAlphaMode(flare.alphaMode);
  83743. var x = centerX - (distX * flare.position);
  83744. var y = centerY - (distY * flare.position);
  83745. var cw = flare.size;
  83746. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83747. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83748. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83749. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83750. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83751. // Texture
  83752. this._effect.setTexture("textureSampler", flare.texture);
  83753. // Color
  83754. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83755. // Draw order
  83756. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83757. }
  83758. engine.setDepthBuffer(true);
  83759. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83760. return true;
  83761. };
  83762. LensFlareSystem.prototype.dispose = function () {
  83763. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83764. if (vertexBuffer) {
  83765. vertexBuffer.dispose();
  83766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83767. }
  83768. if (this._indexBuffer) {
  83769. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83770. this._indexBuffer = null;
  83771. }
  83772. while (this.lensFlares.length) {
  83773. this.lensFlares[0].dispose();
  83774. }
  83775. // Remove from scene
  83776. var index = this._scene.lensFlareSystems.indexOf(this);
  83777. this._scene.lensFlareSystems.splice(index, 1);
  83778. };
  83779. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83780. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83781. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83782. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83783. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83784. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83785. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83786. var parsedFlare = parsedLensFlareSystem.flares[index];
  83787. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83788. }
  83789. return lensFlareSystem;
  83790. };
  83791. LensFlareSystem.prototype.serialize = function () {
  83792. var serializationObject = {};
  83793. serializationObject.id = this.id;
  83794. serializationObject.name = this.name;
  83795. serializationObject.emitterId = this.getEmitter().id;
  83796. serializationObject.borderLimit = this.borderLimit;
  83797. serializationObject.flares = [];
  83798. for (var index = 0; index < this.lensFlares.length; index++) {
  83799. var flare = this.lensFlares[index];
  83800. serializationObject.flares.push({
  83801. size: flare.size,
  83802. position: flare.position,
  83803. color: flare.color.asArray(),
  83804. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83805. });
  83806. }
  83807. return serializationObject;
  83808. };
  83809. return LensFlareSystem;
  83810. }());
  83811. BABYLON.LensFlareSystem = LensFlareSystem;
  83812. })(BABYLON || (BABYLON = {}));
  83813. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83814. var BABYLON;
  83815. (function (BABYLON) {
  83816. /**
  83817. * This is a holder class for the physics joint created by the physics plugin.
  83818. * It holds a set of functions to control the underlying joint.
  83819. */
  83820. var PhysicsJoint = /** @class */ (function () {
  83821. function PhysicsJoint(type, jointData) {
  83822. this.type = type;
  83823. this.jointData = jointData;
  83824. jointData.nativeParams = jointData.nativeParams || {};
  83825. }
  83826. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83827. get: function () {
  83828. return this._physicsJoint;
  83829. },
  83830. set: function (newJoint) {
  83831. if (this._physicsJoint) {
  83832. //remove from the wolrd
  83833. }
  83834. this._physicsJoint = newJoint;
  83835. },
  83836. enumerable: true,
  83837. configurable: true
  83838. });
  83839. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83840. set: function (physicsPlugin) {
  83841. this._physicsPlugin = physicsPlugin;
  83842. },
  83843. enumerable: true,
  83844. configurable: true
  83845. });
  83846. /**
  83847. * Execute a function that is physics-plugin specific.
  83848. * @param {Function} func the function that will be executed.
  83849. * It accepts two parameters: the physics world and the physics joint.
  83850. */
  83851. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83852. func(this._physicsPlugin.world, this._physicsJoint);
  83853. };
  83854. //TODO check if the native joints are the same
  83855. //Joint Types
  83856. PhysicsJoint.DistanceJoint = 0;
  83857. PhysicsJoint.HingeJoint = 1;
  83858. PhysicsJoint.BallAndSocketJoint = 2;
  83859. PhysicsJoint.WheelJoint = 3;
  83860. PhysicsJoint.SliderJoint = 4;
  83861. //OIMO
  83862. PhysicsJoint.PrismaticJoint = 5;
  83863. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83864. PhysicsJoint.UniversalJoint = 6;
  83865. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83866. //Cannon
  83867. //Similar to a Ball-Joint. Different in params
  83868. PhysicsJoint.PointToPointJoint = 8;
  83869. //Cannon only at the moment
  83870. PhysicsJoint.SpringJoint = 9;
  83871. PhysicsJoint.LockJoint = 10;
  83872. return PhysicsJoint;
  83873. }());
  83874. BABYLON.PhysicsJoint = PhysicsJoint;
  83875. /**
  83876. * A class representing a physics distance joint.
  83877. */
  83878. var DistanceJoint = /** @class */ (function (_super) {
  83879. __extends(DistanceJoint, _super);
  83880. function DistanceJoint(jointData) {
  83881. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83882. }
  83883. /**
  83884. * Update the predefined distance.
  83885. */
  83886. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83887. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83888. };
  83889. return DistanceJoint;
  83890. }(PhysicsJoint));
  83891. BABYLON.DistanceJoint = DistanceJoint;
  83892. var MotorEnabledJoint = /** @class */ (function (_super) {
  83893. __extends(MotorEnabledJoint, _super);
  83894. function MotorEnabledJoint(type, jointData) {
  83895. return _super.call(this, type, jointData) || this;
  83896. }
  83897. /**
  83898. * Set the motor values.
  83899. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83900. * @param {number} force the force to apply
  83901. * @param {number} maxForce max force for this motor.
  83902. */
  83903. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83904. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83905. };
  83906. /**
  83907. * Set the motor's limits.
  83908. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83909. */
  83910. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83911. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83912. };
  83913. return MotorEnabledJoint;
  83914. }(PhysicsJoint));
  83915. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83916. /**
  83917. * This class represents a single hinge physics joint
  83918. */
  83919. var HingeJoint = /** @class */ (function (_super) {
  83920. __extends(HingeJoint, _super);
  83921. function HingeJoint(jointData) {
  83922. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83923. }
  83924. /**
  83925. * Set the motor values.
  83926. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83927. * @param {number} force the force to apply
  83928. * @param {number} maxForce max force for this motor.
  83929. */
  83930. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83931. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83932. };
  83933. /**
  83934. * Set the motor's limits.
  83935. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83936. */
  83937. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83938. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83939. };
  83940. return HingeJoint;
  83941. }(MotorEnabledJoint));
  83942. BABYLON.HingeJoint = HingeJoint;
  83943. /**
  83944. * This class represents a dual hinge physics joint (same as wheel joint)
  83945. */
  83946. var Hinge2Joint = /** @class */ (function (_super) {
  83947. __extends(Hinge2Joint, _super);
  83948. function Hinge2Joint(jointData) {
  83949. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83950. }
  83951. /**
  83952. * Set the motor values.
  83953. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83954. * @param {number} force the force to apply
  83955. * @param {number} maxForce max force for this motor.
  83956. * @param {motorIndex} the motor's index, 0 or 1.
  83957. */
  83958. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83959. if (motorIndex === void 0) { motorIndex = 0; }
  83960. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83961. };
  83962. /**
  83963. * Set the motor limits.
  83964. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83965. * @param {number} upperLimit the upper limit
  83966. * @param {number} lowerLimit lower limit
  83967. * @param {motorIndex} the motor's index, 0 or 1.
  83968. */
  83969. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83970. if (motorIndex === void 0) { motorIndex = 0; }
  83971. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83972. };
  83973. return Hinge2Joint;
  83974. }(MotorEnabledJoint));
  83975. BABYLON.Hinge2Joint = Hinge2Joint;
  83976. })(BABYLON || (BABYLON = {}));
  83977. //# sourceMappingURL=babylon.physicsJoint.js.map
  83978. var BABYLON;
  83979. (function (BABYLON) {
  83980. var PhysicsImpostor = /** @class */ (function () {
  83981. function PhysicsImpostor(object, type, _options, _scene) {
  83982. if (_options === void 0) { _options = { mass: 0 }; }
  83983. var _this = this;
  83984. this.object = object;
  83985. this.type = type;
  83986. this._options = _options;
  83987. this._scene = _scene;
  83988. this._bodyUpdateRequired = false;
  83989. this._onBeforePhysicsStepCallbacks = new Array();
  83990. this._onAfterPhysicsStepCallbacks = new Array();
  83991. this._onPhysicsCollideCallbacks = [];
  83992. this._deltaPosition = BABYLON.Vector3.Zero();
  83993. this._isDisposed = false;
  83994. //temp variables for parent rotation calculations
  83995. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83996. this._tmpQuat = new BABYLON.Quaternion();
  83997. this._tmpQuat2 = new BABYLON.Quaternion();
  83998. /**
  83999. * this function is executed by the physics engine.
  84000. */
  84001. this.beforeStep = function () {
  84002. if (!_this._physicsEngine) {
  84003. return;
  84004. }
  84005. _this.object.translate(_this._deltaPosition, -1);
  84006. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84007. _this.object.computeWorldMatrix(false);
  84008. if (_this.object.parent && _this.object.rotationQuaternion) {
  84009. _this.getParentsRotation();
  84010. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84011. }
  84012. else {
  84013. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84014. }
  84015. if (!_this._options.disableBidirectionalTransformation) {
  84016. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84017. }
  84018. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84019. func(_this);
  84020. });
  84021. };
  84022. /**
  84023. * this function is executed by the physics engine.
  84024. */
  84025. this.afterStep = function () {
  84026. if (!_this._physicsEngine) {
  84027. return;
  84028. }
  84029. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84030. func(_this);
  84031. });
  84032. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84033. // object has now its world rotation. needs to be converted to local.
  84034. if (_this.object.parent && _this.object.rotationQuaternion) {
  84035. _this.getParentsRotation();
  84036. _this._tmpQuat.conjugateInPlace();
  84037. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84038. }
  84039. // take the position set and make it the absolute position of this object.
  84040. _this.object.setAbsolutePosition(_this.object.position);
  84041. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84042. _this.object.translate(_this._deltaPosition, 1);
  84043. };
  84044. /**
  84045. * Legacy collision detection event support
  84046. */
  84047. this.onCollideEvent = null;
  84048. //event and body object due to cannon's event-based architecture.
  84049. this.onCollide = function (e) {
  84050. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84051. return;
  84052. }
  84053. if (!_this._physicsEngine) {
  84054. return;
  84055. }
  84056. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84057. if (otherImpostor) {
  84058. // Legacy collision detection event support
  84059. if (_this.onCollideEvent) {
  84060. _this.onCollideEvent(_this, otherImpostor);
  84061. }
  84062. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84063. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84064. }).forEach(function (obj) {
  84065. obj.callback(_this, otherImpostor);
  84066. });
  84067. }
  84068. };
  84069. //sanity check!
  84070. if (!this.object) {
  84071. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84072. return;
  84073. }
  84074. //legacy support for old syntax.
  84075. if (!this._scene && object.getScene) {
  84076. this._scene = object.getScene();
  84077. }
  84078. if (!this._scene) {
  84079. return;
  84080. }
  84081. this._physicsEngine = this._scene.getPhysicsEngine();
  84082. if (!this._physicsEngine) {
  84083. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84084. }
  84085. else {
  84086. //set the object's quaternion, if not set
  84087. if (!this.object.rotationQuaternion) {
  84088. if (this.object.rotation) {
  84089. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84090. }
  84091. else {
  84092. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84093. }
  84094. }
  84095. //default options params
  84096. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84097. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84098. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84099. this._joints = [];
  84100. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84101. if (!this.object.parent || this._options.ignoreParent) {
  84102. this._init();
  84103. }
  84104. else if (this.object.parent.physicsImpostor) {
  84105. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84106. }
  84107. }
  84108. }
  84109. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84110. get: function () {
  84111. return this._isDisposed;
  84112. },
  84113. enumerable: true,
  84114. configurable: true
  84115. });
  84116. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84117. get: function () {
  84118. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84119. },
  84120. set: function (value) {
  84121. this.setMass(value);
  84122. },
  84123. enumerable: true,
  84124. configurable: true
  84125. });
  84126. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84127. get: function () {
  84128. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84129. },
  84130. set: function (value) {
  84131. if (!this._physicsEngine) {
  84132. return;
  84133. }
  84134. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84135. },
  84136. enumerable: true,
  84137. configurable: true
  84138. });
  84139. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84140. get: function () {
  84141. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84142. },
  84143. set: function (value) {
  84144. if (!this._physicsEngine) {
  84145. return;
  84146. }
  84147. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84148. },
  84149. enumerable: true,
  84150. configurable: true
  84151. });
  84152. /**
  84153. * This function will completly initialize this impostor.
  84154. * It will create a new body - but only if this mesh has no parent.
  84155. * If it has, this impostor will not be used other than to define the impostor
  84156. * of the child mesh.
  84157. */
  84158. PhysicsImpostor.prototype._init = function () {
  84159. if (!this._physicsEngine) {
  84160. return;
  84161. }
  84162. this._physicsEngine.removeImpostor(this);
  84163. this.physicsBody = null;
  84164. this._parent = this._parent || this._getPhysicsParent();
  84165. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84166. this._physicsEngine.addImpostor(this);
  84167. }
  84168. };
  84169. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84170. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84171. var parentMesh = this.object.parent;
  84172. return parentMesh.physicsImpostor;
  84173. }
  84174. return null;
  84175. };
  84176. /**
  84177. * Should a new body be generated.
  84178. */
  84179. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84180. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84181. };
  84182. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84183. this.forceUpdate();
  84184. };
  84185. /**
  84186. * Force a regeneration of this or the parent's impostor's body.
  84187. * Use under cautious - This will remove all joints already implemented.
  84188. */
  84189. PhysicsImpostor.prototype.forceUpdate = function () {
  84190. this._init();
  84191. if (this.parent && !this._options.ignoreParent) {
  84192. this.parent.forceUpdate();
  84193. }
  84194. };
  84195. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84196. /*public get mesh(): AbstractMesh {
  84197. return this._mesh;
  84198. }*/
  84199. /**
  84200. * Gets the body that holds this impostor. Either its own, or its parent.
  84201. */
  84202. get: function () {
  84203. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84204. },
  84205. /**
  84206. * Set the physics body. Used mainly by the physics engine/plugin
  84207. */
  84208. set: function (physicsBody) {
  84209. if (this._physicsBody && this._physicsEngine) {
  84210. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84211. }
  84212. this._physicsBody = physicsBody;
  84213. this.resetUpdateFlags();
  84214. },
  84215. enumerable: true,
  84216. configurable: true
  84217. });
  84218. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84219. get: function () {
  84220. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84221. },
  84222. set: function (value) {
  84223. this._parent = value;
  84224. },
  84225. enumerable: true,
  84226. configurable: true
  84227. });
  84228. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84229. this._bodyUpdateRequired = false;
  84230. };
  84231. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84232. if (this.object.getBoundingInfo) {
  84233. var q = this.object.rotationQuaternion;
  84234. //reset rotation
  84235. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84236. //calculate the world matrix with no rotation
  84237. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84238. var boundingInfo = this.object.getBoundingInfo();
  84239. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84240. //bring back the rotation
  84241. this.object.rotationQuaternion = q;
  84242. //calculate the world matrix with the new rotation
  84243. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84244. return size;
  84245. }
  84246. else {
  84247. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84248. }
  84249. };
  84250. PhysicsImpostor.prototype.getObjectCenter = function () {
  84251. if (this.object.getBoundingInfo) {
  84252. var boundingInfo = this.object.getBoundingInfo();
  84253. return boundingInfo.boundingBox.centerWorld;
  84254. }
  84255. else {
  84256. return this.object.position;
  84257. }
  84258. };
  84259. /**
  84260. * Get a specific parametes from the options parameter.
  84261. */
  84262. PhysicsImpostor.prototype.getParam = function (paramName) {
  84263. return this._options[paramName];
  84264. };
  84265. /**
  84266. * Sets a specific parameter in the options given to the physics plugin
  84267. */
  84268. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84269. this._options[paramName] = value;
  84270. this._bodyUpdateRequired = true;
  84271. };
  84272. /**
  84273. * Specifically change the body's mass option. Won't recreate the physics body object
  84274. */
  84275. PhysicsImpostor.prototype.setMass = function (mass) {
  84276. if (this.getParam("mass") !== mass) {
  84277. this.setParam("mass", mass);
  84278. }
  84279. if (this._physicsEngine) {
  84280. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84281. }
  84282. };
  84283. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84284. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84285. };
  84286. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84287. if (this._physicsEngine) {
  84288. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84289. }
  84290. };
  84291. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84292. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84293. };
  84294. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84295. if (this._physicsEngine) {
  84296. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84297. }
  84298. };
  84299. /**
  84300. * Execute a function with the physics plugin native code.
  84301. * Provide a function the will have two variables - the world object and the physics body object.
  84302. */
  84303. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84304. if (this._physicsEngine) {
  84305. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84306. }
  84307. };
  84308. /**
  84309. * Register a function that will be executed before the physics world is stepping forward.
  84310. */
  84311. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84312. this._onBeforePhysicsStepCallbacks.push(func);
  84313. };
  84314. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84315. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84316. if (index > -1) {
  84317. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84318. }
  84319. else {
  84320. BABYLON.Tools.Warn("Function to remove was not found");
  84321. }
  84322. };
  84323. /**
  84324. * Register a function that will be executed after the physics step
  84325. */
  84326. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84327. this._onAfterPhysicsStepCallbacks.push(func);
  84328. };
  84329. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84330. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84331. if (index > -1) {
  84332. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84333. }
  84334. else {
  84335. BABYLON.Tools.Warn("Function to remove was not found");
  84336. }
  84337. };
  84338. /**
  84339. * register a function that will be executed when this impostor collides against a different body.
  84340. */
  84341. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84342. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84343. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84344. };
  84345. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84346. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84347. var index = -1;
  84348. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84349. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84350. // chcek the arrays match
  84351. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84352. return collidedAgainstList.indexOf(impostor) > -1;
  84353. });
  84354. if (sameList) {
  84355. index = idx;
  84356. }
  84357. return sameList;
  84358. }
  84359. return false;
  84360. });
  84361. if (found) {
  84362. this._onPhysicsCollideCallbacks.splice(index, 1);
  84363. }
  84364. else {
  84365. BABYLON.Tools.Warn("Function to remove was not found");
  84366. }
  84367. };
  84368. PhysicsImpostor.prototype.getParentsRotation = function () {
  84369. var parent = this.object.parent;
  84370. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84371. while (parent) {
  84372. if (parent.rotationQuaternion) {
  84373. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84374. }
  84375. else {
  84376. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84377. }
  84378. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84379. parent = parent.parent;
  84380. }
  84381. return this._tmpQuat;
  84382. };
  84383. /**
  84384. * Apply a force
  84385. */
  84386. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84387. if (this._physicsEngine) {
  84388. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84389. }
  84390. return this;
  84391. };
  84392. /**
  84393. * Apply an impulse
  84394. */
  84395. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84396. if (this._physicsEngine) {
  84397. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84398. }
  84399. return this;
  84400. };
  84401. /**
  84402. * A help function to create a joint.
  84403. */
  84404. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84405. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84406. this.addJoint(otherImpostor, joint);
  84407. return this;
  84408. };
  84409. /**
  84410. * Add a joint to this impostor with a different impostor.
  84411. */
  84412. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84413. this._joints.push({
  84414. otherImpostor: otherImpostor,
  84415. joint: joint
  84416. });
  84417. if (this._physicsEngine) {
  84418. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84419. }
  84420. return this;
  84421. };
  84422. /**
  84423. * Will keep this body still, in a sleep mode.
  84424. */
  84425. PhysicsImpostor.prototype.sleep = function () {
  84426. if (this._physicsEngine) {
  84427. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84428. }
  84429. return this;
  84430. };
  84431. /**
  84432. * Wake the body up.
  84433. */
  84434. PhysicsImpostor.prototype.wakeUp = function () {
  84435. if (this._physicsEngine) {
  84436. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84437. }
  84438. return this;
  84439. };
  84440. PhysicsImpostor.prototype.clone = function (newObject) {
  84441. if (!newObject)
  84442. return null;
  84443. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84444. };
  84445. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84446. var _this = this;
  84447. //no dispose if no physics engine is available.
  84448. if (!this._physicsEngine) {
  84449. return;
  84450. }
  84451. this._joints.forEach(function (j) {
  84452. if (_this._physicsEngine) {
  84453. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84454. }
  84455. });
  84456. //dispose the physics body
  84457. this._physicsEngine.removeImpostor(this);
  84458. if (this.parent) {
  84459. this.parent.forceUpdate();
  84460. }
  84461. else {
  84462. /*this._object.getChildMeshes().forEach(function(mesh) {
  84463. if (mesh.physicsImpostor) {
  84464. if (disposeChildren) {
  84465. mesh.physicsImpostor.dispose();
  84466. mesh.physicsImpostor = null;
  84467. }
  84468. }
  84469. })*/
  84470. }
  84471. this._isDisposed = true;
  84472. };
  84473. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84474. this._deltaPosition.copyFrom(position);
  84475. };
  84476. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84477. if (!this._deltaRotation) {
  84478. this._deltaRotation = new BABYLON.Quaternion();
  84479. }
  84480. this._deltaRotation.copyFrom(rotation);
  84481. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84482. };
  84483. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84484. if (this._physicsEngine) {
  84485. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84486. }
  84487. return this;
  84488. };
  84489. PhysicsImpostor.prototype.getRadius = function () {
  84490. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84491. };
  84492. /**
  84493. * Sync a bone with this impostor
  84494. * @param bone The bone to sync to the impostor.
  84495. * @param boneMesh The mesh that the bone is influencing.
  84496. * @param jointPivot The pivot of the joint / bone in local space.
  84497. * @param distToJoint Optional distance from the impostor to the joint.
  84498. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84499. */
  84500. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84501. var tempVec = PhysicsImpostor._tmpVecs[0];
  84502. var mesh = this.object;
  84503. if (mesh.rotationQuaternion) {
  84504. if (adjustRotation) {
  84505. var tempQuat = PhysicsImpostor._tmpQuat;
  84506. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84507. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84508. }
  84509. else {
  84510. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84511. }
  84512. }
  84513. tempVec.x = 0;
  84514. tempVec.y = 0;
  84515. tempVec.z = 0;
  84516. if (jointPivot) {
  84517. tempVec.x = jointPivot.x;
  84518. tempVec.y = jointPivot.y;
  84519. tempVec.z = jointPivot.z;
  84520. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84521. if (distToJoint === undefined || distToJoint === null) {
  84522. distToJoint = jointPivot.length();
  84523. }
  84524. tempVec.x *= distToJoint;
  84525. tempVec.y *= distToJoint;
  84526. tempVec.z *= distToJoint;
  84527. }
  84528. if (bone.getParent()) {
  84529. tempVec.addInPlace(mesh.getAbsolutePosition());
  84530. bone.setAbsolutePosition(tempVec, boneMesh);
  84531. }
  84532. else {
  84533. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84534. boneMesh.position.x -= tempVec.x;
  84535. boneMesh.position.y -= tempVec.y;
  84536. boneMesh.position.z -= tempVec.z;
  84537. }
  84538. };
  84539. /**
  84540. * Sync impostor to a bone
  84541. * @param bone The bone that the impostor will be synced to.
  84542. * @param boneMesh The mesh that the bone is influencing.
  84543. * @param jointPivot The pivot of the joint / bone in local space.
  84544. * @param distToJoint Optional distance from the impostor to the joint.
  84545. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84546. * @param boneAxis Optional vector3 axis the bone is aligned with
  84547. */
  84548. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84549. var mesh = this.object;
  84550. if (mesh.rotationQuaternion) {
  84551. if (adjustRotation) {
  84552. var tempQuat = PhysicsImpostor._tmpQuat;
  84553. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84554. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84555. }
  84556. else {
  84557. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84558. }
  84559. }
  84560. var pos = PhysicsImpostor._tmpVecs[0];
  84561. var boneDir = PhysicsImpostor._tmpVecs[1];
  84562. if (!boneAxis) {
  84563. boneAxis = PhysicsImpostor._tmpVecs[2];
  84564. boneAxis.x = 0;
  84565. boneAxis.y = 1;
  84566. boneAxis.z = 0;
  84567. }
  84568. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84569. bone.getAbsolutePositionToRef(boneMesh, pos);
  84570. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84571. distToJoint = jointPivot.length();
  84572. }
  84573. if (distToJoint !== undefined && distToJoint !== null) {
  84574. pos.x += boneDir.x * distToJoint;
  84575. pos.y += boneDir.y * distToJoint;
  84576. pos.z += boneDir.z * distToJoint;
  84577. }
  84578. mesh.setAbsolutePosition(pos);
  84579. };
  84580. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84581. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84582. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84583. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84584. //Impostor types
  84585. PhysicsImpostor.NoImpostor = 0;
  84586. PhysicsImpostor.SphereImpostor = 1;
  84587. PhysicsImpostor.BoxImpostor = 2;
  84588. PhysicsImpostor.PlaneImpostor = 3;
  84589. PhysicsImpostor.MeshImpostor = 4;
  84590. PhysicsImpostor.CylinderImpostor = 7;
  84591. PhysicsImpostor.ParticleImpostor = 8;
  84592. PhysicsImpostor.HeightmapImpostor = 9;
  84593. return PhysicsImpostor;
  84594. }());
  84595. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84596. })(BABYLON || (BABYLON = {}));
  84597. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84598. var BABYLON;
  84599. (function (BABYLON) {
  84600. var PhysicsEngine = /** @class */ (function () {
  84601. function PhysicsEngine(gravity, _physicsPlugin) {
  84602. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84603. this._physicsPlugin = _physicsPlugin;
  84604. //new methods and parameters
  84605. this._impostors = [];
  84606. this._joints = [];
  84607. if (!this._physicsPlugin.isSupported()) {
  84608. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84609. + "Please make sure it is included.");
  84610. }
  84611. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84612. this.setGravity(gravity);
  84613. this.setTimeStep();
  84614. }
  84615. PhysicsEngine.prototype.setGravity = function (gravity) {
  84616. this.gravity = gravity;
  84617. this._physicsPlugin.setGravity(this.gravity);
  84618. };
  84619. /**
  84620. * Set the time step of the physics engine.
  84621. * default is 1/60.
  84622. * To slow it down, enter 1/600 for example.
  84623. * To speed it up, 1/30
  84624. * @param {number} newTimeStep the new timestep to apply to this world.
  84625. */
  84626. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84627. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84628. this._physicsPlugin.setTimeStep(newTimeStep);
  84629. };
  84630. /**
  84631. * Get the time step of the physics engine.
  84632. */
  84633. PhysicsEngine.prototype.getTimeStep = function () {
  84634. return this._physicsPlugin.getTimeStep();
  84635. };
  84636. PhysicsEngine.prototype.dispose = function () {
  84637. this._impostors.forEach(function (impostor) {
  84638. impostor.dispose();
  84639. });
  84640. this._physicsPlugin.dispose();
  84641. };
  84642. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84643. return this._physicsPlugin.name;
  84644. };
  84645. /**
  84646. * Adding a new impostor for the impostor tracking.
  84647. * This will be done by the impostor itself.
  84648. * @param {PhysicsImpostor} impostor the impostor to add
  84649. */
  84650. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84651. impostor.uniqueId = this._impostors.push(impostor);
  84652. //if no parent, generate the body
  84653. if (!impostor.parent) {
  84654. this._physicsPlugin.generatePhysicsBody(impostor);
  84655. }
  84656. };
  84657. /**
  84658. * Remove an impostor from the engine.
  84659. * This impostor and its mesh will not longer be updated by the physics engine.
  84660. * @param {PhysicsImpostor} impostor the impostor to remove
  84661. */
  84662. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84663. var index = this._impostors.indexOf(impostor);
  84664. if (index > -1) {
  84665. var removed = this._impostors.splice(index, 1);
  84666. //Is it needed?
  84667. if (removed.length) {
  84668. //this will also remove it from the world.
  84669. removed[0].physicsBody = null;
  84670. }
  84671. }
  84672. };
  84673. /**
  84674. * Add a joint to the physics engine
  84675. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84676. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84677. * @param {PhysicsJoint} the joint that will connect both impostors.
  84678. */
  84679. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84680. var impostorJoint = {
  84681. mainImpostor: mainImpostor,
  84682. connectedImpostor: connectedImpostor,
  84683. joint: joint
  84684. };
  84685. joint.physicsPlugin = this._physicsPlugin;
  84686. this._joints.push(impostorJoint);
  84687. this._physicsPlugin.generateJoint(impostorJoint);
  84688. };
  84689. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84690. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84691. return (impostorJoint.connectedImpostor === connectedImpostor
  84692. && impostorJoint.joint === joint
  84693. && impostorJoint.mainImpostor === mainImpostor);
  84694. });
  84695. if (matchingJoints.length) {
  84696. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84697. //TODO remove it from the list as well
  84698. }
  84699. };
  84700. /**
  84701. * Called by the scene. no need to call it.
  84702. */
  84703. PhysicsEngine.prototype._step = function (delta) {
  84704. var _this = this;
  84705. //check if any mesh has no body / requires an update
  84706. this._impostors.forEach(function (impostor) {
  84707. if (impostor.isBodyInitRequired()) {
  84708. _this._physicsPlugin.generatePhysicsBody(impostor);
  84709. }
  84710. });
  84711. if (delta > 0.1) {
  84712. delta = 0.1;
  84713. }
  84714. else if (delta <= 0) {
  84715. delta = 1.0 / 60.0;
  84716. }
  84717. this._physicsPlugin.executeStep(delta, this._impostors);
  84718. };
  84719. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84720. return this._physicsPlugin;
  84721. };
  84722. PhysicsEngine.prototype.getImpostors = function () {
  84723. return this._impostors;
  84724. };
  84725. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84726. for (var i = 0; i < this._impostors.length; ++i) {
  84727. if (this._impostors[i].object === object) {
  84728. return this._impostors[i];
  84729. }
  84730. }
  84731. return null;
  84732. };
  84733. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84734. for (var i = 0; i < this._impostors.length; ++i) {
  84735. if (this._impostors[i].physicsBody === body) {
  84736. return this._impostors[i];
  84737. }
  84738. }
  84739. return null;
  84740. };
  84741. // Statics
  84742. PhysicsEngine.Epsilon = 0.001;
  84743. return PhysicsEngine;
  84744. }());
  84745. BABYLON.PhysicsEngine = PhysicsEngine;
  84746. })(BABYLON || (BABYLON = {}));
  84747. //# sourceMappingURL=babylon.physicsEngine.js.map
  84748. var BABYLON;
  84749. (function (BABYLON) {
  84750. var PhysicsHelper = /** @class */ (function () {
  84751. function PhysicsHelper(scene) {
  84752. this._scene = scene;
  84753. this._physicsEngine = this._scene.getPhysicsEngine();
  84754. if (!this._physicsEngine) {
  84755. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84756. }
  84757. }
  84758. /**
  84759. * @param {Vector3} origin the origin of the explosion
  84760. * @param {number} radius the explosion radius
  84761. * @param {number} strength the explosion strength
  84762. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84763. */
  84764. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84765. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84766. if (!this._physicsEngine) {
  84767. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84768. return null;
  84769. }
  84770. var impostors = this._physicsEngine.getImpostors();
  84771. if (impostors.length === 0) {
  84772. return null;
  84773. }
  84774. var event = new PhysicsRadialExplosionEvent(this._scene);
  84775. impostors.forEach(function (impostor) {
  84776. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84777. if (!impostorForceAndContactPoint) {
  84778. return;
  84779. }
  84780. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84781. });
  84782. event.dispose(false);
  84783. return event;
  84784. };
  84785. /**
  84786. * @param {Vector3} origin the origin of the explosion
  84787. * @param {number} radius the explosion radius
  84788. * @param {number} strength the explosion strength
  84789. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84790. */
  84791. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84792. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84793. if (!this._physicsEngine) {
  84794. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84795. return null;
  84796. }
  84797. var impostors = this._physicsEngine.getImpostors();
  84798. if (impostors.length === 0) {
  84799. return null;
  84800. }
  84801. var event = new PhysicsRadialExplosionEvent(this._scene);
  84802. impostors.forEach(function (impostor) {
  84803. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84804. if (!impostorForceAndContactPoint) {
  84805. return;
  84806. }
  84807. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84808. });
  84809. event.dispose(false);
  84810. return event;
  84811. };
  84812. /**
  84813. * @param {Vector3} origin the origin of the explosion
  84814. * @param {number} radius the explosion radius
  84815. * @param {number} strength the explosion strength
  84816. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84817. */
  84818. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84819. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84820. if (!this._physicsEngine) {
  84821. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84822. return null;
  84823. }
  84824. var impostors = this._physicsEngine.getImpostors();
  84825. if (impostors.length === 0) {
  84826. return null;
  84827. }
  84828. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84829. event.dispose(false);
  84830. return event;
  84831. };
  84832. /**
  84833. * @param {Vector3} origin the origin of the updraft
  84834. * @param {number} radius the radius of the updraft
  84835. * @param {number} strength the strength of the updraft
  84836. * @param {number} height the height of the updraft
  84837. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84838. */
  84839. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84840. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84841. if (!this._physicsEngine) {
  84842. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84843. return null;
  84844. }
  84845. if (this._physicsEngine.getImpostors().length === 0) {
  84846. return null;
  84847. }
  84848. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84849. event.dispose(false);
  84850. return event;
  84851. };
  84852. /**
  84853. * @param {Vector3} origin the of the vortex
  84854. * @param {number} radius the radius of the vortex
  84855. * @param {number} strength the strength of the vortex
  84856. * @param {number} height the height of the vortex
  84857. */
  84858. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84859. if (!this._physicsEngine) {
  84860. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84861. return null;
  84862. }
  84863. if (this._physicsEngine.getImpostors().length === 0) {
  84864. return null;
  84865. }
  84866. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84867. event.dispose(false);
  84868. return event;
  84869. };
  84870. return PhysicsHelper;
  84871. }());
  84872. BABYLON.PhysicsHelper = PhysicsHelper;
  84873. /***** Radial explosion *****/
  84874. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84875. function PhysicsRadialExplosionEvent(scene) {
  84876. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84877. this._rays = [];
  84878. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84879. this._scene = scene;
  84880. }
  84881. /**
  84882. * Returns the data related to the radial explosion event (sphere & rays).
  84883. * @returns {PhysicsRadialExplosionEventData}
  84884. */
  84885. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84886. this._dataFetched = true;
  84887. return {
  84888. sphere: this._sphere,
  84889. rays: this._rays,
  84890. };
  84891. };
  84892. /**
  84893. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84894. * @param impostor
  84895. * @param {Vector3} origin the origin of the explosion
  84896. * @param {number} radius the explosion radius
  84897. * @param {number} strength the explosion strength
  84898. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84899. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84900. */
  84901. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84902. if (impostor.mass === 0) {
  84903. return null;
  84904. }
  84905. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84906. return null;
  84907. }
  84908. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84909. return null;
  84910. }
  84911. var impostorObjectCenter = impostor.getObjectCenter();
  84912. var direction = impostorObjectCenter.subtract(origin);
  84913. var ray = new BABYLON.Ray(origin, direction, radius);
  84914. this._rays.push(ray);
  84915. var hit = ray.intersectsMesh(impostor.object);
  84916. var contactPoint = hit.pickedPoint;
  84917. if (!contactPoint) {
  84918. return null;
  84919. }
  84920. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84921. if (distanceFromOrigin > radius) {
  84922. return null;
  84923. }
  84924. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84925. ? strength
  84926. : strength * (1 - (distanceFromOrigin / radius));
  84927. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84928. return { force: force, contactPoint: contactPoint };
  84929. };
  84930. /**
  84931. * Disposes the sphere.
  84932. * @param {bolean} force
  84933. */
  84934. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84935. var _this = this;
  84936. if (force === void 0) { force = true; }
  84937. if (force) {
  84938. this._sphere.dispose();
  84939. }
  84940. else {
  84941. setTimeout(function () {
  84942. if (!_this._dataFetched) {
  84943. _this._sphere.dispose();
  84944. }
  84945. }, 0);
  84946. }
  84947. };
  84948. /*** Helpers ***/
  84949. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84950. if (!this._sphere) {
  84951. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84952. this._sphere.isVisible = false;
  84953. }
  84954. };
  84955. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84956. var impostorObject = impostor.object;
  84957. this._prepareSphere();
  84958. this._sphere.position = origin;
  84959. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84960. this._sphere._updateBoundingInfo();
  84961. this._sphere.computeWorldMatrix(true);
  84962. return this._sphere.intersectsMesh(impostorObject, true);
  84963. };
  84964. return PhysicsRadialExplosionEvent;
  84965. }());
  84966. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84967. /***** Gravitational Field *****/
  84968. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84969. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84970. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84971. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84972. this._physicsHelper = physicsHelper;
  84973. this._scene = scene;
  84974. this._origin = origin;
  84975. this._radius = radius;
  84976. this._strength = strength;
  84977. this._falloff = falloff;
  84978. this._tickCallback = this._tick.bind(this);
  84979. }
  84980. /**
  84981. * Returns the data related to the gravitational field event (sphere).
  84982. * @returns {PhysicsGravitationalFieldEventData}
  84983. */
  84984. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84985. this._dataFetched = true;
  84986. return {
  84987. sphere: this._sphere,
  84988. };
  84989. };
  84990. /**
  84991. * Enables the gravitational field.
  84992. */
  84993. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84994. this._tickCallback.call(this);
  84995. this._scene.registerBeforeRender(this._tickCallback);
  84996. };
  84997. /**
  84998. * Disables the gravitational field.
  84999. */
  85000. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85001. this._scene.unregisterBeforeRender(this._tickCallback);
  85002. };
  85003. /**
  85004. * Disposes the sphere.
  85005. * @param {bolean} force
  85006. */
  85007. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85008. var _this = this;
  85009. if (force === void 0) { force = true; }
  85010. if (force) {
  85011. this._sphere.dispose();
  85012. }
  85013. else {
  85014. setTimeout(function () {
  85015. if (!_this._dataFetched) {
  85016. _this._sphere.dispose();
  85017. }
  85018. }, 0);
  85019. }
  85020. };
  85021. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85022. // Since the params won't change, we fetch the event only once
  85023. if (this._sphere) {
  85024. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85025. }
  85026. else {
  85027. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85028. if (radialExplosionEvent) {
  85029. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85030. }
  85031. }
  85032. };
  85033. return PhysicsGravitationalFieldEvent;
  85034. }());
  85035. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85036. /***** Updraft *****/
  85037. var PhysicsUpdraftEvent = /** @class */ (function () {
  85038. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85039. this._scene = _scene;
  85040. this._origin = _origin;
  85041. this._radius = _radius;
  85042. this._strength = _strength;
  85043. this._height = _height;
  85044. this._updraftMode = _updraftMode;
  85045. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85046. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85047. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85048. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85049. this._physicsEngine = this._scene.getPhysicsEngine();
  85050. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85051. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85052. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85053. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85054. }
  85055. this._tickCallback = this._tick.bind(this);
  85056. }
  85057. /**
  85058. * Returns the data related to the updraft event (cylinder).
  85059. * @returns {PhysicsUpdraftEventData}
  85060. */
  85061. PhysicsUpdraftEvent.prototype.getData = function () {
  85062. this._dataFetched = true;
  85063. return {
  85064. cylinder: this._cylinder,
  85065. };
  85066. };
  85067. /**
  85068. * Enables the updraft.
  85069. */
  85070. PhysicsUpdraftEvent.prototype.enable = function () {
  85071. this._tickCallback.call(this);
  85072. this._scene.registerBeforeRender(this._tickCallback);
  85073. };
  85074. /**
  85075. * Disables the cortex.
  85076. */
  85077. PhysicsUpdraftEvent.prototype.disable = function () {
  85078. this._scene.unregisterBeforeRender(this._tickCallback);
  85079. };
  85080. /**
  85081. * Disposes the sphere.
  85082. * @param {bolean} force
  85083. */
  85084. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85085. var _this = this;
  85086. if (force === void 0) { force = true; }
  85087. if (force) {
  85088. this._cylinder.dispose();
  85089. }
  85090. else {
  85091. setTimeout(function () {
  85092. if (!_this._dataFetched) {
  85093. _this._cylinder.dispose();
  85094. }
  85095. }, 0);
  85096. }
  85097. };
  85098. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85099. if (impostor.mass === 0) {
  85100. return null;
  85101. }
  85102. if (!this._intersectsWithCylinder(impostor)) {
  85103. return null;
  85104. }
  85105. var impostorObjectCenter = impostor.getObjectCenter();
  85106. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85107. var direction = this._originDirection;
  85108. }
  85109. else {
  85110. var direction = impostorObjectCenter.subtract(this._originTop);
  85111. }
  85112. var multiplier = this._strength * -1;
  85113. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85114. return { force: force, contactPoint: impostorObjectCenter };
  85115. };
  85116. PhysicsUpdraftEvent.prototype._tick = function () {
  85117. var _this = this;
  85118. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85119. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85120. if (!impostorForceAndContactPoint) {
  85121. return;
  85122. }
  85123. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85124. });
  85125. };
  85126. /*** Helpers ***/
  85127. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85128. if (!this._cylinder) {
  85129. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85130. height: this._height,
  85131. diameter: this._radius * 2,
  85132. }, this._scene);
  85133. this._cylinder.isVisible = false;
  85134. }
  85135. };
  85136. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85137. var impostorObject = impostor.object;
  85138. this._prepareCylinder();
  85139. this._cylinder.position = this._cylinderPosition;
  85140. return this._cylinder.intersectsMesh(impostorObject, true);
  85141. };
  85142. return PhysicsUpdraftEvent;
  85143. }());
  85144. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85145. /***** Vortex *****/
  85146. var PhysicsVortexEvent = /** @class */ (function () {
  85147. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85148. this._scene = _scene;
  85149. this._origin = _origin;
  85150. this._radius = _radius;
  85151. this._strength = _strength;
  85152. this._height = _height;
  85153. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85154. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85155. this._updraftMultiplier = 0.02;
  85156. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85157. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85158. this._physicsEngine = this._scene.getPhysicsEngine();
  85159. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85160. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85161. this._tickCallback = this._tick.bind(this);
  85162. }
  85163. /**
  85164. * Returns the data related to the vortex event (cylinder).
  85165. * @returns {PhysicsVortexEventData}
  85166. */
  85167. PhysicsVortexEvent.prototype.getData = function () {
  85168. this._dataFetched = true;
  85169. return {
  85170. cylinder: this._cylinder,
  85171. };
  85172. };
  85173. /**
  85174. * Enables the vortex.
  85175. */
  85176. PhysicsVortexEvent.prototype.enable = function () {
  85177. this._tickCallback.call(this);
  85178. this._scene.registerBeforeRender(this._tickCallback);
  85179. };
  85180. /**
  85181. * Disables the cortex.
  85182. */
  85183. PhysicsVortexEvent.prototype.disable = function () {
  85184. this._scene.unregisterBeforeRender(this._tickCallback);
  85185. };
  85186. /**
  85187. * Disposes the sphere.
  85188. * @param {bolean} force
  85189. */
  85190. PhysicsVortexEvent.prototype.dispose = function (force) {
  85191. var _this = this;
  85192. if (force === void 0) { force = true; }
  85193. if (force) {
  85194. this._cylinder.dispose();
  85195. }
  85196. else {
  85197. setTimeout(function () {
  85198. if (!_this._dataFetched) {
  85199. _this._cylinder.dispose();
  85200. }
  85201. }, 0);
  85202. }
  85203. };
  85204. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85205. if (impostor.mass === 0) {
  85206. return null;
  85207. }
  85208. if (!this._intersectsWithCylinder(impostor)) {
  85209. return null;
  85210. }
  85211. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85212. return null;
  85213. }
  85214. var impostorObjectCenter = impostor.getObjectCenter();
  85215. 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)
  85216. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85217. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85218. var hit = ray.intersectsMesh(impostor.object);
  85219. var contactPoint = hit.pickedPoint;
  85220. if (!contactPoint) {
  85221. return null;
  85222. }
  85223. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85224. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85225. var directionToOrigin = contactPoint.normalize();
  85226. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85227. directionToOrigin = directionToOrigin.negate();
  85228. }
  85229. // TODO: find a more physically based solution
  85230. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85231. var forceX = directionToOrigin.x * this._strength / 8;
  85232. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85233. var forceZ = directionToOrigin.z * this._strength / 8;
  85234. }
  85235. else {
  85236. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85237. var forceY = this._originTop.y * this._updraftMultiplier;
  85238. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85239. }
  85240. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85241. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85242. return { force: force, contactPoint: impostorObjectCenter };
  85243. };
  85244. PhysicsVortexEvent.prototype._tick = function () {
  85245. var _this = this;
  85246. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85247. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85248. if (!impostorForceAndContactPoint) {
  85249. return;
  85250. }
  85251. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85252. });
  85253. };
  85254. /*** Helpers ***/
  85255. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85256. if (!this._cylinder) {
  85257. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85258. height: this._height,
  85259. diameter: this._radius * 2,
  85260. }, this._scene);
  85261. this._cylinder.isVisible = false;
  85262. }
  85263. };
  85264. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85265. var impostorObject = impostor.object;
  85266. this._prepareCylinder();
  85267. this._cylinder.position = this._cylinderPosition;
  85268. return this._cylinder.intersectsMesh(impostorObject, true);
  85269. };
  85270. return PhysicsVortexEvent;
  85271. }());
  85272. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85273. /***** Enums *****/
  85274. /**
  85275. * The strenght of the force in correspondence to the distance of the affected object
  85276. */
  85277. var PhysicsRadialImpulseFalloff;
  85278. (function (PhysicsRadialImpulseFalloff) {
  85279. /** Defines that impulse is constant in strength across it's whole radius */
  85280. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85281. /** DEfines that impulse gets weaker if it's further from the origin */
  85282. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85283. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85284. /**
  85285. * The strenght of the force in correspondence to the distance of the affected object
  85286. */
  85287. var PhysicsUpdraftMode;
  85288. (function (PhysicsUpdraftMode) {
  85289. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85290. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85291. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85292. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85293. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85294. })(BABYLON || (BABYLON = {}));
  85295. //# sourceMappingURL=babylon.physicsHelper.js.map
  85296. var BABYLON;
  85297. (function (BABYLON) {
  85298. var CannonJSPlugin = /** @class */ (function () {
  85299. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85300. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85301. if (iterations === void 0) { iterations = 10; }
  85302. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85303. this.name = "CannonJSPlugin";
  85304. this._physicsMaterials = new Array();
  85305. this._fixedTimeStep = 1 / 60;
  85306. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85307. this.BJSCANNON = CANNON;
  85308. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85309. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85310. this._tmpPosition = BABYLON.Vector3.Zero();
  85311. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85312. this._tmpUnityRotation = new BABYLON.Quaternion();
  85313. if (!this.isSupported()) {
  85314. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85315. return;
  85316. }
  85317. this._extendNamespace();
  85318. this.world = new this.BJSCANNON.World();
  85319. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85320. this.world.solver.iterations = iterations;
  85321. }
  85322. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85323. this.world.gravity.copy(gravity);
  85324. };
  85325. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85326. this._fixedTimeStep = timeStep;
  85327. };
  85328. CannonJSPlugin.prototype.getTimeStep = function () {
  85329. return this._fixedTimeStep;
  85330. };
  85331. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85332. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85333. };
  85334. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85335. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85336. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85337. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85338. };
  85339. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85340. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85341. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85342. impostor.physicsBody.applyForce(impulse, worldPoint);
  85343. };
  85344. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85345. //parent-child relationship. Does this impostor has a parent impostor?
  85346. if (impostor.parent) {
  85347. if (impostor.physicsBody) {
  85348. this.removePhysicsBody(impostor);
  85349. //TODO is that needed?
  85350. impostor.forceUpdate();
  85351. }
  85352. return;
  85353. }
  85354. //should a new body be created for this impostor?
  85355. if (impostor.isBodyInitRequired()) {
  85356. var shape = this._createShape(impostor);
  85357. //unregister events, if body is being changed
  85358. var oldBody = impostor.physicsBody;
  85359. if (oldBody) {
  85360. this.removePhysicsBody(impostor);
  85361. }
  85362. //create the body and material
  85363. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85364. var bodyCreationObject = {
  85365. mass: impostor.getParam("mass"),
  85366. material: material
  85367. };
  85368. // A simple extend, in case native options were used.
  85369. var nativeOptions = impostor.getParam("nativeOptions");
  85370. for (var key in nativeOptions) {
  85371. if (nativeOptions.hasOwnProperty(key)) {
  85372. bodyCreationObject[key] = nativeOptions[key];
  85373. }
  85374. }
  85375. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85376. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85377. this.world.addEventListener("preStep", impostor.beforeStep);
  85378. this.world.addEventListener("postStep", impostor.afterStep);
  85379. impostor.physicsBody.addShape(shape);
  85380. this.world.add(impostor.physicsBody);
  85381. //try to keep the body moving in the right direction by taking old properties.
  85382. //Should be tested!
  85383. if (oldBody) {
  85384. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85385. impostor.physicsBody[param].copy(oldBody[param]);
  85386. });
  85387. }
  85388. this._processChildMeshes(impostor);
  85389. }
  85390. //now update the body's transformation
  85391. this._updatePhysicsBodyTransformation(impostor);
  85392. };
  85393. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85394. var _this = this;
  85395. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85396. var currentRotation = mainImpostor.object.rotationQuaternion;
  85397. if (meshChildren.length) {
  85398. var processMesh = function (localPosition, mesh) {
  85399. if (!currentRotation || !mesh.rotationQuaternion) {
  85400. return;
  85401. }
  85402. var childImpostor = mesh.getPhysicsImpostor();
  85403. if (childImpostor) {
  85404. var parent = childImpostor.parent;
  85405. if (parent !== mainImpostor) {
  85406. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85407. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85408. if (childImpostor.physicsBody) {
  85409. _this.removePhysicsBody(childImpostor);
  85410. childImpostor.physicsBody = null;
  85411. }
  85412. childImpostor.parent = mainImpostor;
  85413. childImpostor.resetUpdateFlags();
  85414. 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));
  85415. //Add the mass of the children.
  85416. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85417. }
  85418. }
  85419. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85420. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85421. };
  85422. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85423. }
  85424. };
  85425. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85426. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85427. this.world.removeEventListener("preStep", impostor.beforeStep);
  85428. this.world.removeEventListener("postStep", impostor.afterStep);
  85429. this.world.remove(impostor.physicsBody);
  85430. };
  85431. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85432. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85433. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85434. if (!mainBody || !connectedBody) {
  85435. return;
  85436. }
  85437. var constraint;
  85438. var jointData = impostorJoint.joint.jointData;
  85439. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85440. var constraintData = {
  85441. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85442. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85443. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85444. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85445. maxForce: jointData.nativeParams.maxForce,
  85446. collideConnected: !!jointData.collision
  85447. };
  85448. switch (impostorJoint.joint.type) {
  85449. case BABYLON.PhysicsJoint.HingeJoint:
  85450. case BABYLON.PhysicsJoint.Hinge2Joint:
  85451. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85452. break;
  85453. case BABYLON.PhysicsJoint.DistanceJoint:
  85454. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85455. break;
  85456. case BABYLON.PhysicsJoint.SpringJoint:
  85457. var springData = jointData;
  85458. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85459. restLength: springData.length,
  85460. stiffness: springData.stiffness,
  85461. damping: springData.damping,
  85462. localAnchorA: constraintData.pivotA,
  85463. localAnchorB: constraintData.pivotB
  85464. });
  85465. break;
  85466. case BABYLON.PhysicsJoint.LockJoint:
  85467. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85468. break;
  85469. case BABYLON.PhysicsJoint.PointToPointJoint:
  85470. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85471. default:
  85472. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85473. break;
  85474. }
  85475. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85476. constraint.collideConnected = !!jointData.collision;
  85477. impostorJoint.joint.physicsJoint = constraint;
  85478. //don't add spring as constraint, as it is not one.
  85479. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85480. this.world.addConstraint(constraint);
  85481. }
  85482. else {
  85483. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85484. constraint.applyForce();
  85485. });
  85486. }
  85487. };
  85488. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85489. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85490. };
  85491. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85492. var index;
  85493. var mat;
  85494. for (index = 0; index < this._physicsMaterials.length; index++) {
  85495. mat = this._physicsMaterials[index];
  85496. if (mat.friction === friction && mat.restitution === restitution) {
  85497. return mat;
  85498. }
  85499. }
  85500. var currentMat = new this.BJSCANNON.Material(name);
  85501. currentMat.friction = friction;
  85502. currentMat.restitution = restitution;
  85503. this._physicsMaterials.push(currentMat);
  85504. return currentMat;
  85505. };
  85506. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85507. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85508. };
  85509. CannonJSPlugin.prototype._createShape = function (impostor) {
  85510. var object = impostor.object;
  85511. var returnValue;
  85512. var extendSize = impostor.getObjectExtendSize();
  85513. switch (impostor.type) {
  85514. case BABYLON.PhysicsImpostor.SphereImpostor:
  85515. var radiusX = extendSize.x;
  85516. var radiusY = extendSize.y;
  85517. var radiusZ = extendSize.z;
  85518. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85519. break;
  85520. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85521. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85522. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85523. break;
  85524. case BABYLON.PhysicsImpostor.BoxImpostor:
  85525. var box = extendSize.scale(0.5);
  85526. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85527. break;
  85528. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85529. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85530. returnValue = new this.BJSCANNON.Plane();
  85531. break;
  85532. case BABYLON.PhysicsImpostor.MeshImpostor:
  85533. // should transform the vertex data to world coordinates!!
  85534. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85535. var rawFaces = object.getIndices ? object.getIndices() : [];
  85536. if (!rawVerts)
  85537. return;
  85538. // get only scale! so the object could transform correctly.
  85539. var oldPosition = object.position.clone();
  85540. var oldRotation = object.rotation && object.rotation.clone();
  85541. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85542. object.position.copyFromFloats(0, 0, 0);
  85543. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85544. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85545. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85546. var transform = object.computeWorldMatrix(true);
  85547. // convert rawVerts to object space
  85548. var temp = new Array();
  85549. var index;
  85550. for (index = 0; index < rawVerts.length; index += 3) {
  85551. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85552. }
  85553. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85554. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85555. //now set back the transformation!
  85556. object.position.copyFrom(oldPosition);
  85557. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85558. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85559. break;
  85560. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85561. var oldPosition2 = object.position.clone();
  85562. var oldRotation2 = object.rotation && object.rotation.clone();
  85563. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85564. object.position.copyFromFloats(0, 0, 0);
  85565. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85566. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85567. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85568. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85569. returnValue = this._createHeightmap(object);
  85570. object.position.copyFrom(oldPosition2);
  85571. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85572. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85573. object.computeWorldMatrix(true);
  85574. break;
  85575. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85576. returnValue = new this.BJSCANNON.Particle();
  85577. break;
  85578. }
  85579. return returnValue;
  85580. };
  85581. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85582. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85583. var transform = object.computeWorldMatrix(true);
  85584. // convert rawVerts to object space
  85585. var temp = new Array();
  85586. var index;
  85587. for (index = 0; index < pos.length; index += 3) {
  85588. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85589. }
  85590. pos = temp;
  85591. var matrix = new Array();
  85592. //For now pointDepth will not be used and will be automatically calculated.
  85593. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85594. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85595. var boundingInfo = object.getBoundingInfo();
  85596. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85597. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85598. var elementSize = dim * 2 / arraySize;
  85599. for (var i = 0; i < pos.length; i = i + 3) {
  85600. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85601. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85602. var y = -pos[i + 2] + minY;
  85603. if (!matrix[x]) {
  85604. matrix[x] = [];
  85605. }
  85606. if (!matrix[x][z]) {
  85607. matrix[x][z] = y;
  85608. }
  85609. matrix[x][z] = Math.max(y, matrix[x][z]);
  85610. }
  85611. for (var x = 0; x <= arraySize; ++x) {
  85612. if (!matrix[x]) {
  85613. var loc = 1;
  85614. while (!matrix[(x + loc) % arraySize]) {
  85615. loc++;
  85616. }
  85617. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85618. //console.log("missing x", x);
  85619. }
  85620. for (var z = 0; z <= arraySize; ++z) {
  85621. if (!matrix[x][z]) {
  85622. var loc = 1;
  85623. var newValue;
  85624. while (newValue === undefined) {
  85625. newValue = matrix[x][(z + loc++) % arraySize];
  85626. }
  85627. matrix[x][z] = newValue;
  85628. }
  85629. }
  85630. }
  85631. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85632. elementSize: elementSize
  85633. });
  85634. //For future reference, needed for body transformation
  85635. shape.minY = minY;
  85636. return shape;
  85637. };
  85638. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85639. var object = impostor.object;
  85640. //make sure it is updated...
  85641. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85642. // The delta between the mesh position and the mesh bounding box center
  85643. var bInfo = object.getBoundingInfo();
  85644. if (!bInfo)
  85645. return;
  85646. var center = impostor.getObjectCenter();
  85647. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85648. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85649. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85650. this._tmpPosition.copyFrom(center);
  85651. var quaternion = object.rotationQuaternion;
  85652. if (!quaternion) {
  85653. return;
  85654. }
  85655. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85656. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85657. //-90 DEG in X, precalculated
  85658. quaternion = quaternion.multiply(this._minus90X);
  85659. //Invert! (Precalculated, 90 deg in X)
  85660. //No need to clone. this will never change.
  85661. impostor.setDeltaRotation(this._plus90X);
  85662. }
  85663. //If it is a heightfield, if should be centered.
  85664. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85665. var mesh = object;
  85666. var boundingInfo = mesh.getBoundingInfo();
  85667. //calculate the correct body position:
  85668. var rotationQuaternion = mesh.rotationQuaternion;
  85669. mesh.rotationQuaternion = this._tmpUnityRotation;
  85670. mesh.computeWorldMatrix(true);
  85671. //get original center with no rotation
  85672. var c = center.clone();
  85673. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85674. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85675. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85676. mesh.setPreTransformMatrix(p);
  85677. mesh.computeWorldMatrix(true);
  85678. //calculate the translation
  85679. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85680. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85681. //add it inverted to the delta
  85682. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85683. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85684. //rotation is back
  85685. mesh.rotationQuaternion = rotationQuaternion;
  85686. mesh.setPreTransformMatrix(oldPivot);
  85687. mesh.computeWorldMatrix(true);
  85688. }
  85689. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85690. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85691. //this._tmpPosition.copyFrom(object.position);
  85692. }
  85693. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85694. //Now update the impostor object
  85695. impostor.physicsBody.position.copy(this._tmpPosition);
  85696. impostor.physicsBody.quaternion.copy(quaternion);
  85697. };
  85698. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85699. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85700. if (impostor.object.rotationQuaternion) {
  85701. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85702. }
  85703. };
  85704. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85705. impostor.physicsBody.position.copy(newPosition);
  85706. impostor.physicsBody.quaternion.copy(newRotation);
  85707. };
  85708. CannonJSPlugin.prototype.isSupported = function () {
  85709. return this.BJSCANNON !== undefined;
  85710. };
  85711. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85712. impostor.physicsBody.velocity.copy(velocity);
  85713. };
  85714. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85715. impostor.physicsBody.angularVelocity.copy(velocity);
  85716. };
  85717. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85718. var v = impostor.physicsBody.velocity;
  85719. if (!v) {
  85720. return null;
  85721. }
  85722. return new BABYLON.Vector3(v.x, v.y, v.z);
  85723. };
  85724. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85725. var v = impostor.physicsBody.angularVelocity;
  85726. if (!v) {
  85727. return null;
  85728. }
  85729. return new BABYLON.Vector3(v.x, v.y, v.z);
  85730. };
  85731. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85732. impostor.physicsBody.mass = mass;
  85733. impostor.physicsBody.updateMassProperties();
  85734. };
  85735. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85736. return impostor.physicsBody.mass;
  85737. };
  85738. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85739. return impostor.physicsBody.material.friction;
  85740. };
  85741. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85742. impostor.physicsBody.material.friction = friction;
  85743. };
  85744. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85745. return impostor.physicsBody.material.restitution;
  85746. };
  85747. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85748. impostor.physicsBody.material.restitution = restitution;
  85749. };
  85750. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85751. impostor.physicsBody.sleep();
  85752. };
  85753. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85754. impostor.physicsBody.wakeUp();
  85755. };
  85756. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85757. joint.physicsJoint.distance = maxDistance;
  85758. };
  85759. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85760. // if (!motorIndex) {
  85761. // joint.physicsJoint.enableMotor();
  85762. // }
  85763. // }
  85764. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85765. // if (!motorIndex) {
  85766. // joint.physicsJoint.disableMotor();
  85767. // }
  85768. // }
  85769. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85770. if (!motorIndex) {
  85771. joint.physicsJoint.enableMotor();
  85772. joint.physicsJoint.setMotorSpeed(speed);
  85773. if (maxForce) {
  85774. this.setLimit(joint, maxForce);
  85775. }
  85776. }
  85777. };
  85778. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85779. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85780. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85781. };
  85782. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85783. var body = impostor.physicsBody;
  85784. mesh.position.x = body.position.x;
  85785. mesh.position.y = body.position.y;
  85786. mesh.position.z = body.position.z;
  85787. if (mesh.rotationQuaternion) {
  85788. mesh.rotationQuaternion.x = body.quaternion.x;
  85789. mesh.rotationQuaternion.y = body.quaternion.y;
  85790. mesh.rotationQuaternion.z = body.quaternion.z;
  85791. mesh.rotationQuaternion.w = body.quaternion.w;
  85792. }
  85793. };
  85794. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85795. var shape = impostor.physicsBody.shapes[0];
  85796. return shape.boundingSphereRadius;
  85797. };
  85798. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85799. var shape = impostor.physicsBody.shapes[0];
  85800. result.x = shape.halfExtents.x * 2;
  85801. result.y = shape.halfExtents.y * 2;
  85802. result.z = shape.halfExtents.z * 2;
  85803. };
  85804. CannonJSPlugin.prototype.dispose = function () {
  85805. };
  85806. CannonJSPlugin.prototype._extendNamespace = function () {
  85807. //this will force cannon to execute at least one step when using interpolation
  85808. var step_tmp1 = new this.BJSCANNON.Vec3();
  85809. var Engine = this.BJSCANNON;
  85810. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85811. maxSubSteps = maxSubSteps || 10;
  85812. timeSinceLastCalled = timeSinceLastCalled || 0;
  85813. if (timeSinceLastCalled === 0) {
  85814. this.internalStep(dt);
  85815. this.time += dt;
  85816. }
  85817. else {
  85818. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85819. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85820. var t0 = performance.now();
  85821. for (var i = 0; i !== internalSteps; i++) {
  85822. this.internalStep(dt);
  85823. if (performance.now() - t0 > dt * 1000) {
  85824. break;
  85825. }
  85826. }
  85827. this.time += timeSinceLastCalled;
  85828. var h = this.time % dt;
  85829. var h_div_dt = h / dt;
  85830. var interpvelo = step_tmp1;
  85831. var bodies = this.bodies;
  85832. for (var j = 0; j !== bodies.length; j++) {
  85833. var b = bodies[j];
  85834. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85835. b.position.vsub(b.previousPosition, interpvelo);
  85836. interpvelo.scale(h_div_dt, interpvelo);
  85837. b.position.vadd(interpvelo, b.interpolatedPosition);
  85838. }
  85839. else {
  85840. b.interpolatedPosition.copy(b.position);
  85841. b.interpolatedQuaternion.copy(b.quaternion);
  85842. }
  85843. }
  85844. }
  85845. };
  85846. };
  85847. return CannonJSPlugin;
  85848. }());
  85849. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85850. })(BABYLON || (BABYLON = {}));
  85851. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85852. var BABYLON;
  85853. (function (BABYLON) {
  85854. var OimoJSPlugin = /** @class */ (function () {
  85855. function OimoJSPlugin(iterations) {
  85856. this.name = "OimoJSPlugin";
  85857. this._tmpImpostorsArray = [];
  85858. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85859. this.BJSOIMO = OIMO;
  85860. this.world = new this.BJSOIMO.World({
  85861. iterations: iterations
  85862. });
  85863. this.world.clear();
  85864. }
  85865. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85866. this.world.gravity.copy(gravity);
  85867. };
  85868. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85869. this.world.timeStep = timeStep;
  85870. };
  85871. OimoJSPlugin.prototype.getTimeStep = function () {
  85872. return this.world.timeStep;
  85873. };
  85874. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85875. var _this = this;
  85876. impostors.forEach(function (impostor) {
  85877. impostor.beforeStep();
  85878. });
  85879. this.world.step();
  85880. impostors.forEach(function (impostor) {
  85881. impostor.afterStep();
  85882. //update the ordered impostors array
  85883. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85884. });
  85885. //check for collisions
  85886. var contact = this.world.contacts;
  85887. while (contact !== null) {
  85888. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85889. contact = contact.next;
  85890. continue;
  85891. }
  85892. //is this body colliding with any other? get the impostor
  85893. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85894. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85895. if (!mainImpostor || !collidingImpostor) {
  85896. contact = contact.next;
  85897. continue;
  85898. }
  85899. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85900. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85901. contact = contact.next;
  85902. }
  85903. };
  85904. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85905. var mass = impostor.physicsBody.mass;
  85906. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85907. };
  85908. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85909. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85910. this.applyImpulse(impostor, force, contactPoint);
  85911. };
  85912. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85913. var _this = this;
  85914. //parent-child relationship. Does this impostor has a parent impostor?
  85915. if (impostor.parent) {
  85916. if (impostor.physicsBody) {
  85917. this.removePhysicsBody(impostor);
  85918. //TODO is that needed?
  85919. impostor.forceUpdate();
  85920. }
  85921. return;
  85922. }
  85923. if (impostor.isBodyInitRequired()) {
  85924. var bodyConfig = {
  85925. name: impostor.uniqueId,
  85926. //Oimo must have mass, also for static objects.
  85927. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85928. size: [],
  85929. type: [],
  85930. pos: [],
  85931. posShape: [],
  85932. rot: [],
  85933. rotShape: [],
  85934. move: impostor.getParam("mass") !== 0,
  85935. density: impostor.getParam("mass"),
  85936. friction: impostor.getParam("friction"),
  85937. restitution: impostor.getParam("restitution"),
  85938. //Supporting older versions of Oimo
  85939. world: this.world
  85940. };
  85941. var impostors = [impostor];
  85942. var addToArray = function (parent) {
  85943. if (!parent.getChildMeshes)
  85944. return;
  85945. parent.getChildMeshes().forEach(function (m) {
  85946. if (m.physicsImpostor) {
  85947. impostors.push(m.physicsImpostor);
  85948. //m.physicsImpostor._init();
  85949. }
  85950. });
  85951. };
  85952. addToArray(impostor.object);
  85953. var checkWithEpsilon_1 = function (value) {
  85954. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85955. };
  85956. impostors.forEach(function (i) {
  85957. if (!i.object.rotationQuaternion) {
  85958. return;
  85959. }
  85960. //get the correct bounding box
  85961. var oldQuaternion = i.object.rotationQuaternion;
  85962. var rot = oldQuaternion.toEulerAngles();
  85963. var extendSize = i.getObjectExtendSize();
  85964. var radToDeg = 57.295779513082320876;
  85965. if (i === impostor) {
  85966. var center = impostor.getObjectCenter();
  85967. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85968. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85969. //Can also use Array.prototype.push.apply
  85970. bodyConfig.pos.push(center.x);
  85971. bodyConfig.pos.push(center.y);
  85972. bodyConfig.pos.push(center.z);
  85973. bodyConfig.posShape.push(0, 0, 0);
  85974. //tmp solution
  85975. bodyConfig.rot.push(rot.x * radToDeg);
  85976. bodyConfig.rot.push(rot.y * radToDeg);
  85977. bodyConfig.rot.push(rot.z * radToDeg);
  85978. bodyConfig.rotShape.push(0, 0, 0);
  85979. }
  85980. else {
  85981. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85982. bodyConfig.posShape.push(localPosition.x);
  85983. bodyConfig.posShape.push(localPosition.y);
  85984. bodyConfig.posShape.push(localPosition.z);
  85985. bodyConfig.pos.push(0, 0, 0);
  85986. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85987. bodyConfig.rot.push(0);
  85988. bodyConfig.rot.push(0);
  85989. bodyConfig.rot.push(0);
  85990. bodyConfig.rotShape.push(rot.x * radToDeg);
  85991. bodyConfig.rotShape.push(rot.y * radToDeg);
  85992. bodyConfig.rotShape.push(rot.z * radToDeg);
  85993. }
  85994. // register mesh
  85995. switch (i.type) {
  85996. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85997. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85998. case BABYLON.PhysicsImpostor.SphereImpostor:
  85999. var radiusX = extendSize.x;
  86000. var radiusY = extendSize.y;
  86001. var radiusZ = extendSize.z;
  86002. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86003. bodyConfig.type.push('sphere');
  86004. //due to the way oimo works with compounds, add 3 times
  86005. bodyConfig.size.push(size);
  86006. bodyConfig.size.push(size);
  86007. bodyConfig.size.push(size);
  86008. break;
  86009. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86010. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86011. var sizeY = checkWithEpsilon_1(extendSize.y);
  86012. bodyConfig.type.push('cylinder');
  86013. bodyConfig.size.push(sizeX);
  86014. bodyConfig.size.push(sizeY);
  86015. //due to the way oimo works with compounds, add one more value.
  86016. bodyConfig.size.push(sizeY);
  86017. break;
  86018. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86019. case BABYLON.PhysicsImpostor.BoxImpostor:
  86020. default:
  86021. var sizeX = checkWithEpsilon_1(extendSize.x);
  86022. var sizeY = checkWithEpsilon_1(extendSize.y);
  86023. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86024. bodyConfig.type.push('box');
  86025. //if (i === impostor) {
  86026. bodyConfig.size.push(sizeX);
  86027. bodyConfig.size.push(sizeY);
  86028. bodyConfig.size.push(sizeZ);
  86029. //} else {
  86030. // bodyConfig.size.push(0,0,0);
  86031. //}
  86032. break;
  86033. }
  86034. //actually not needed, but hey...
  86035. i.object.rotationQuaternion = oldQuaternion;
  86036. });
  86037. impostor.physicsBody = this.world.add(bodyConfig);
  86038. }
  86039. else {
  86040. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86041. }
  86042. impostor.setDeltaPosition(this._tmpPositionVector);
  86043. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86044. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86045. };
  86046. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86047. //impostor.physicsBody.dispose();
  86048. //Same as : (older oimo versions)
  86049. this.world.removeRigidBody(impostor.physicsBody);
  86050. };
  86051. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86052. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86053. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86054. if (!mainBody || !connectedBody) {
  86055. return;
  86056. }
  86057. var jointData = impostorJoint.joint.jointData;
  86058. var options = jointData.nativeParams || {};
  86059. var type;
  86060. var nativeJointData = {
  86061. body1: mainBody,
  86062. body2: connectedBody,
  86063. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86064. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86065. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86066. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86067. min: options.min,
  86068. max: options.max,
  86069. collision: options.collision || jointData.collision,
  86070. spring: options.spring,
  86071. //supporting older version of Oimo
  86072. world: this.world
  86073. };
  86074. switch (impostorJoint.joint.type) {
  86075. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86076. type = "jointBall";
  86077. break;
  86078. case BABYLON.PhysicsJoint.SpringJoint:
  86079. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86080. var springData = jointData;
  86081. nativeJointData.min = springData.length || nativeJointData.min;
  86082. //Max should also be set, just make sure it is at least min
  86083. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86084. case BABYLON.PhysicsJoint.DistanceJoint:
  86085. type = "jointDistance";
  86086. nativeJointData.max = jointData.maxDistance;
  86087. break;
  86088. case BABYLON.PhysicsJoint.PrismaticJoint:
  86089. type = "jointPrisme";
  86090. break;
  86091. case BABYLON.PhysicsJoint.SliderJoint:
  86092. type = "jointSlide";
  86093. break;
  86094. case BABYLON.PhysicsJoint.WheelJoint:
  86095. type = "jointWheel";
  86096. break;
  86097. case BABYLON.PhysicsJoint.HingeJoint:
  86098. default:
  86099. type = "jointHinge";
  86100. break;
  86101. }
  86102. nativeJointData.type = type;
  86103. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86104. };
  86105. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86106. //Bug in Oimo prevents us from disposing a joint in the playground
  86107. //joint.joint.physicsJoint.dispose();
  86108. //So we will bruteforce it!
  86109. try {
  86110. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86111. }
  86112. catch (e) {
  86113. BABYLON.Tools.Warn(e);
  86114. }
  86115. };
  86116. OimoJSPlugin.prototype.isSupported = function () {
  86117. return this.BJSOIMO !== undefined;
  86118. };
  86119. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86120. if (!impostor.physicsBody.sleeping) {
  86121. //TODO check that
  86122. /*if (impostor.physicsBody.shapes.next) {
  86123. var parentShape = this._getLastShape(impostor.physicsBody);
  86124. impostor.object.position.copyFrom(parentShape.position);
  86125. console.log(parentShape.position);
  86126. } else {*/
  86127. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86128. //}
  86129. if (impostor.object.rotationQuaternion) {
  86130. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86131. }
  86132. }
  86133. };
  86134. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86135. var body = impostor.physicsBody;
  86136. body.position.copy(newPosition);
  86137. body.orientation.copy(newRotation);
  86138. body.syncShapes();
  86139. body.awake();
  86140. };
  86141. /*private _getLastShape(body: any): any {
  86142. var lastShape = body.shapes;
  86143. while (lastShape.next) {
  86144. lastShape = lastShape.next;
  86145. }
  86146. return lastShape;
  86147. }*/
  86148. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86149. impostor.physicsBody.linearVelocity.copy(velocity);
  86150. };
  86151. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86152. impostor.physicsBody.angularVelocity.copy(velocity);
  86153. };
  86154. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86155. var v = impostor.physicsBody.linearVelocity;
  86156. if (!v) {
  86157. return null;
  86158. }
  86159. return new BABYLON.Vector3(v.x, v.y, v.z);
  86160. };
  86161. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86162. var v = impostor.physicsBody.angularVelocity;
  86163. if (!v) {
  86164. return null;
  86165. }
  86166. return new BABYLON.Vector3(v.x, v.y, v.z);
  86167. };
  86168. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86169. var staticBody = mass === 0;
  86170. //this will actually set the body's density and not its mass.
  86171. //But this is how oimo treats the mass variable.
  86172. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86173. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86174. };
  86175. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86176. return impostor.physicsBody.shapes.density;
  86177. };
  86178. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86179. return impostor.physicsBody.shapes.friction;
  86180. };
  86181. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86182. impostor.physicsBody.shapes.friction = friction;
  86183. };
  86184. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86185. return impostor.physicsBody.shapes.restitution;
  86186. };
  86187. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86188. impostor.physicsBody.shapes.restitution = restitution;
  86189. };
  86190. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86191. impostor.physicsBody.sleep();
  86192. };
  86193. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86194. impostor.physicsBody.awake();
  86195. };
  86196. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86197. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86198. if (minDistance !== void 0) {
  86199. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86200. }
  86201. };
  86202. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86203. //TODO separate rotational and transational motors.
  86204. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86205. if (motor) {
  86206. motor.setMotor(speed, maxForce);
  86207. }
  86208. };
  86209. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86210. //TODO separate rotational and transational motors.
  86211. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86212. if (motor) {
  86213. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86214. }
  86215. };
  86216. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86217. var body = impostor.physicsBody;
  86218. mesh.position.x = body.position.x;
  86219. mesh.position.y = body.position.y;
  86220. mesh.position.z = body.position.z;
  86221. if (mesh.rotationQuaternion) {
  86222. mesh.rotationQuaternion.x = body.orientation.x;
  86223. mesh.rotationQuaternion.y = body.orientation.y;
  86224. mesh.rotationQuaternion.z = body.orientation.z;
  86225. mesh.rotationQuaternion.w = body.orientation.s;
  86226. }
  86227. };
  86228. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86229. return impostor.physicsBody.shapes.radius;
  86230. };
  86231. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86232. var shape = impostor.physicsBody.shapes;
  86233. result.x = shape.halfWidth * 2;
  86234. result.y = shape.halfHeight * 2;
  86235. result.z = shape.halfDepth * 2;
  86236. };
  86237. OimoJSPlugin.prototype.dispose = function () {
  86238. this.world.clear();
  86239. };
  86240. return OimoJSPlugin;
  86241. }());
  86242. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86243. })(BABYLON || (BABYLON = {}));
  86244. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86245. var BABYLON;
  86246. (function (BABYLON) {
  86247. /*
  86248. * Based on jsTGALoader - Javascript loader for TGA file
  86249. * By Vincent Thibault
  86250. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86251. */
  86252. var TGATools = /** @class */ (function () {
  86253. function TGATools() {
  86254. }
  86255. TGATools.GetTGAHeader = function (data) {
  86256. var offset = 0;
  86257. var header = {
  86258. id_length: data[offset++],
  86259. colormap_type: data[offset++],
  86260. image_type: data[offset++],
  86261. colormap_index: data[offset++] | data[offset++] << 8,
  86262. colormap_length: data[offset++] | data[offset++] << 8,
  86263. colormap_size: data[offset++],
  86264. origin: [
  86265. data[offset++] | data[offset++] << 8,
  86266. data[offset++] | data[offset++] << 8
  86267. ],
  86268. width: data[offset++] | data[offset++] << 8,
  86269. height: data[offset++] | data[offset++] << 8,
  86270. pixel_size: data[offset++],
  86271. flags: data[offset++]
  86272. };
  86273. return header;
  86274. };
  86275. TGATools.UploadContent = function (gl, data) {
  86276. // Not enough data to contain header ?
  86277. if (data.length < 19) {
  86278. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86279. return;
  86280. }
  86281. // Read Header
  86282. var offset = 18;
  86283. var header = TGATools.GetTGAHeader(data);
  86284. // Assume it's a valid Targa file.
  86285. if (header.id_length + offset > data.length) {
  86286. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86287. return;
  86288. }
  86289. // Skip not needed data
  86290. offset += header.id_length;
  86291. var use_rle = false;
  86292. var use_pal = false;
  86293. var use_grey = false;
  86294. // Get some informations.
  86295. switch (header.image_type) {
  86296. case TGATools._TYPE_RLE_INDEXED:
  86297. use_rle = true;
  86298. case TGATools._TYPE_INDEXED:
  86299. use_pal = true;
  86300. break;
  86301. case TGATools._TYPE_RLE_RGB:
  86302. use_rle = true;
  86303. case TGATools._TYPE_RGB:
  86304. // use_rgb = true;
  86305. break;
  86306. case TGATools._TYPE_RLE_GREY:
  86307. use_rle = true;
  86308. case TGATools._TYPE_GREY:
  86309. use_grey = true;
  86310. break;
  86311. }
  86312. var pixel_data;
  86313. // var numAlphaBits = header.flags & 0xf;
  86314. var pixel_size = header.pixel_size >> 3;
  86315. var pixel_total = header.width * header.height * pixel_size;
  86316. // Read palettes
  86317. var palettes;
  86318. if (use_pal) {
  86319. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86320. }
  86321. // Read LRE
  86322. if (use_rle) {
  86323. pixel_data = new Uint8Array(pixel_total);
  86324. var c, count, i;
  86325. var localOffset = 0;
  86326. var pixels = new Uint8Array(pixel_size);
  86327. while (offset < pixel_total && localOffset < pixel_total) {
  86328. c = data[offset++];
  86329. count = (c & 0x7f) + 1;
  86330. // RLE pixels
  86331. if (c & 0x80) {
  86332. // Bind pixel tmp array
  86333. for (i = 0; i < pixel_size; ++i) {
  86334. pixels[i] = data[offset++];
  86335. }
  86336. // Copy pixel array
  86337. for (i = 0; i < count; ++i) {
  86338. pixel_data.set(pixels, localOffset + i * pixel_size);
  86339. }
  86340. localOffset += pixel_size * count;
  86341. }
  86342. // Raw pixels
  86343. else {
  86344. count *= pixel_size;
  86345. for (i = 0; i < count; ++i) {
  86346. pixel_data[localOffset + i] = data[offset++];
  86347. }
  86348. localOffset += count;
  86349. }
  86350. }
  86351. }
  86352. // RAW Pixels
  86353. else {
  86354. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86355. }
  86356. // Load to texture
  86357. var x_start, y_start, x_step, y_step, y_end, x_end;
  86358. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86359. default:
  86360. case TGATools._ORIGIN_UL:
  86361. x_start = 0;
  86362. x_step = 1;
  86363. x_end = header.width;
  86364. y_start = 0;
  86365. y_step = 1;
  86366. y_end = header.height;
  86367. break;
  86368. case TGATools._ORIGIN_BL:
  86369. x_start = 0;
  86370. x_step = 1;
  86371. x_end = header.width;
  86372. y_start = header.height - 1;
  86373. y_step = -1;
  86374. y_end = -1;
  86375. break;
  86376. case TGATools._ORIGIN_UR:
  86377. x_start = header.width - 1;
  86378. x_step = -1;
  86379. x_end = -1;
  86380. y_start = 0;
  86381. y_step = 1;
  86382. y_end = header.height;
  86383. break;
  86384. case TGATools._ORIGIN_BR:
  86385. x_start = header.width - 1;
  86386. x_step = -1;
  86387. x_end = -1;
  86388. y_start = header.height - 1;
  86389. y_step = -1;
  86390. y_end = -1;
  86391. break;
  86392. }
  86393. // Load the specify method
  86394. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86395. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86396. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86397. };
  86398. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86399. var image = pixel_data, colormap = palettes;
  86400. var width = header.width, height = header.height;
  86401. var color, i = 0, x, y;
  86402. var imageData = new Uint8Array(width * height * 4);
  86403. for (y = y_start; y !== y_end; y += y_step) {
  86404. for (x = x_start; x !== x_end; x += x_step, i++) {
  86405. color = image[i];
  86406. imageData[(x + width * y) * 4 + 3] = 255;
  86407. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86408. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86409. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86410. }
  86411. }
  86412. return imageData;
  86413. };
  86414. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86415. var image = pixel_data;
  86416. var width = header.width, height = header.height;
  86417. var color, i = 0, x, y;
  86418. var imageData = new Uint8Array(width * height * 4);
  86419. for (y = y_start; y !== y_end; y += y_step) {
  86420. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86421. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86422. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86423. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86424. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86425. imageData[(x + width * y) * 4 + 0] = r;
  86426. imageData[(x + width * y) * 4 + 1] = g;
  86427. imageData[(x + width * y) * 4 + 2] = b;
  86428. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86429. }
  86430. }
  86431. return imageData;
  86432. };
  86433. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86434. var image = pixel_data;
  86435. var width = header.width, height = header.height;
  86436. var i = 0, x, y;
  86437. var imageData = new Uint8Array(width * height * 4);
  86438. for (y = y_start; y !== y_end; y += y_step) {
  86439. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86440. imageData[(x + width * y) * 4 + 3] = 255;
  86441. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86442. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86443. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86444. }
  86445. }
  86446. return imageData;
  86447. };
  86448. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86449. var image = pixel_data;
  86450. var width = header.width, height = header.height;
  86451. var i = 0, x, y;
  86452. var imageData = new Uint8Array(width * height * 4);
  86453. for (y = y_start; y !== y_end; y += y_step) {
  86454. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86455. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86456. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86457. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86458. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86459. }
  86460. }
  86461. return imageData;
  86462. };
  86463. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86464. var image = pixel_data;
  86465. var width = header.width, height = header.height;
  86466. var color, i = 0, x, y;
  86467. var imageData = new Uint8Array(width * height * 4);
  86468. for (y = y_start; y !== y_end; y += y_step) {
  86469. for (x = x_start; x !== x_end; x += x_step, i++) {
  86470. color = image[i];
  86471. imageData[(x + width * y) * 4 + 0] = color;
  86472. imageData[(x + width * y) * 4 + 1] = color;
  86473. imageData[(x + width * y) * 4 + 2] = color;
  86474. imageData[(x + width * y) * 4 + 3] = 255;
  86475. }
  86476. }
  86477. return imageData;
  86478. };
  86479. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86480. var image = pixel_data;
  86481. var width = header.width, height = header.height;
  86482. var i = 0, x, y;
  86483. var imageData = new Uint8Array(width * height * 4);
  86484. for (y = y_start; y !== y_end; y += y_step) {
  86485. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86486. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86487. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86488. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86489. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86490. }
  86491. }
  86492. return imageData;
  86493. };
  86494. //private static _TYPE_NO_DATA = 0;
  86495. TGATools._TYPE_INDEXED = 1;
  86496. TGATools._TYPE_RGB = 2;
  86497. TGATools._TYPE_GREY = 3;
  86498. TGATools._TYPE_RLE_INDEXED = 9;
  86499. TGATools._TYPE_RLE_RGB = 10;
  86500. TGATools._TYPE_RLE_GREY = 11;
  86501. TGATools._ORIGIN_MASK = 0x30;
  86502. TGATools._ORIGIN_SHIFT = 0x04;
  86503. TGATools._ORIGIN_BL = 0x00;
  86504. TGATools._ORIGIN_BR = 0x01;
  86505. TGATools._ORIGIN_UL = 0x02;
  86506. TGATools._ORIGIN_UR = 0x03;
  86507. return TGATools;
  86508. }());
  86509. BABYLON.TGATools = TGATools;
  86510. })(BABYLON || (BABYLON = {}));
  86511. //# sourceMappingURL=babylon.tga.js.map
  86512. var BABYLON;
  86513. (function (BABYLON) {
  86514. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86515. // All values and structures referenced from:
  86516. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86517. var DDS_MAGIC = 0x20534444;
  86518. var
  86519. //DDSD_CAPS = 0x1,
  86520. //DDSD_HEIGHT = 0x2,
  86521. //DDSD_WIDTH = 0x4,
  86522. //DDSD_PITCH = 0x8,
  86523. //DDSD_PIXELFORMAT = 0x1000,
  86524. DDSD_MIPMAPCOUNT = 0x20000;
  86525. //DDSD_LINEARSIZE = 0x80000,
  86526. //DDSD_DEPTH = 0x800000;
  86527. // var DDSCAPS_COMPLEX = 0x8,
  86528. // DDSCAPS_MIPMAP = 0x400000,
  86529. // DDSCAPS_TEXTURE = 0x1000;
  86530. var DDSCAPS2_CUBEMAP = 0x200;
  86531. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86532. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86533. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86534. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86535. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86536. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86537. // DDSCAPS2_VOLUME = 0x200000;
  86538. var
  86539. //DDPF_ALPHAPIXELS = 0x1,
  86540. //DDPF_ALPHA = 0x2,
  86541. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86542. //DDPF_YUV = 0x200,
  86543. DDPF_LUMINANCE = 0x20000;
  86544. function FourCCToInt32(value) {
  86545. return value.charCodeAt(0) +
  86546. (value.charCodeAt(1) << 8) +
  86547. (value.charCodeAt(2) << 16) +
  86548. (value.charCodeAt(3) << 24);
  86549. }
  86550. function Int32ToFourCC(value) {
  86551. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86552. }
  86553. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86554. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86555. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86556. var FOURCC_DX10 = FourCCToInt32("DX10");
  86557. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86558. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86559. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86560. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86561. var headerLengthInt = 31; // The header length in 32 bit ints
  86562. // Offsets into the header array
  86563. var off_magic = 0;
  86564. var off_size = 1;
  86565. var off_flags = 2;
  86566. var off_height = 3;
  86567. var off_width = 4;
  86568. var off_mipmapCount = 7;
  86569. var off_pfFlags = 20;
  86570. var off_pfFourCC = 21;
  86571. var off_RGBbpp = 22;
  86572. var off_RMask = 23;
  86573. var off_GMask = 24;
  86574. var off_BMask = 25;
  86575. var off_AMask = 26;
  86576. // var off_caps1 = 27;
  86577. var off_caps2 = 28;
  86578. // var off_caps3 = 29;
  86579. // var off_caps4 = 30;
  86580. var off_dxgiFormat = 32;
  86581. ;
  86582. var DDSTools = /** @class */ (function () {
  86583. function DDSTools() {
  86584. }
  86585. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86586. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86587. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86588. var mipmapCount = 1;
  86589. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86590. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86591. }
  86592. var fourCC = header[off_pfFourCC];
  86593. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86594. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86595. switch (fourCC) {
  86596. case FOURCC_D3DFMT_R16G16B16A16F:
  86597. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86598. break;
  86599. case FOURCC_D3DFMT_R32G32B32A32F:
  86600. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86601. break;
  86602. case FOURCC_DX10:
  86603. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86604. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86605. break;
  86606. }
  86607. }
  86608. return {
  86609. width: header[off_width],
  86610. height: header[off_height],
  86611. mipmapCount: mipmapCount,
  86612. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86613. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86614. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86615. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86616. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86617. dxgiFormat: dxgiFormat,
  86618. textureType: textureType
  86619. };
  86620. };
  86621. DDSTools._ToHalfFloat = function (value) {
  86622. if (!DDSTools._FloatView) {
  86623. DDSTools._FloatView = new Float32Array(1);
  86624. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86625. }
  86626. DDSTools._FloatView[0] = value;
  86627. var x = DDSTools._Int32View[0];
  86628. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86629. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86630. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86631. /* If zero, or denormal, or exponent underflows too much for a denormal
  86632. * half, return signed zero. */
  86633. if (e < 103) {
  86634. return bits;
  86635. }
  86636. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86637. if (e > 142) {
  86638. bits |= 0x7c00;
  86639. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86640. * not Inf, so make sure we set one mantissa bit too. */
  86641. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86642. return bits;
  86643. }
  86644. /* If exponent underflows but not too much, return a denormal */
  86645. if (e < 113) {
  86646. m |= 0x0800;
  86647. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86648. * to 1, which is OK. */
  86649. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86650. return bits;
  86651. }
  86652. bits |= ((e - 112) << 10) | (m >> 1);
  86653. bits += m & 1;
  86654. return bits;
  86655. };
  86656. DDSTools._FromHalfFloat = function (value) {
  86657. var s = (value & 0x8000) >> 15;
  86658. var e = (value & 0x7C00) >> 10;
  86659. var f = value & 0x03FF;
  86660. if (e === 0) {
  86661. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86662. }
  86663. else if (e == 0x1F) {
  86664. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86665. }
  86666. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86667. };
  86668. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86669. var destArray = new Float32Array(dataLength);
  86670. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86671. var index = 0;
  86672. for (var y = 0; y < height; y++) {
  86673. for (var x = 0; x < width; x++) {
  86674. var srcPos = (x + y * width) * 4;
  86675. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86676. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86677. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86678. if (DDSTools.StoreLODInAlphaChannel) {
  86679. destArray[index + 3] = lod;
  86680. }
  86681. else {
  86682. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86683. }
  86684. index += 4;
  86685. }
  86686. }
  86687. return destArray;
  86688. };
  86689. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86690. if (DDSTools.StoreLODInAlphaChannel) {
  86691. var destArray = new Uint16Array(dataLength);
  86692. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86693. var index = 0;
  86694. for (var y = 0; y < height; y++) {
  86695. for (var x = 0; x < width; x++) {
  86696. var srcPos = (x + y * width) * 4;
  86697. destArray[index] = srcData[srcPos];
  86698. destArray[index + 1] = srcData[srcPos + 1];
  86699. destArray[index + 2] = srcData[srcPos + 2];
  86700. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86701. index += 4;
  86702. }
  86703. }
  86704. return destArray;
  86705. }
  86706. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86707. };
  86708. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86709. if (DDSTools.StoreLODInAlphaChannel) {
  86710. var destArray = new Float32Array(dataLength);
  86711. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86712. var index = 0;
  86713. for (var y = 0; y < height; y++) {
  86714. for (var x = 0; x < width; x++) {
  86715. var srcPos = (x + y * width) * 4;
  86716. destArray[index] = srcData[srcPos];
  86717. destArray[index + 1] = srcData[srcPos + 1];
  86718. destArray[index + 2] = srcData[srcPos + 2];
  86719. destArray[index + 3] = lod;
  86720. index += 4;
  86721. }
  86722. }
  86723. return destArray;
  86724. }
  86725. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86726. };
  86727. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86728. var destArray = new Uint8Array(dataLength);
  86729. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86730. var index = 0;
  86731. for (var y = 0; y < height; y++) {
  86732. for (var x = 0; x < width; x++) {
  86733. var srcPos = (x + y * width) * 4;
  86734. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86735. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86736. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86737. if (DDSTools.StoreLODInAlphaChannel) {
  86738. destArray[index + 3] = lod;
  86739. }
  86740. else {
  86741. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86742. }
  86743. index += 4;
  86744. }
  86745. }
  86746. return destArray;
  86747. };
  86748. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86749. var destArray = new Uint8Array(dataLength);
  86750. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86751. var index = 0;
  86752. for (var y = 0; y < height; y++) {
  86753. for (var x = 0; x < width; x++) {
  86754. var srcPos = (x + y * width) * 4;
  86755. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86756. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86757. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86758. if (DDSTools.StoreLODInAlphaChannel) {
  86759. destArray[index + 3] = lod;
  86760. }
  86761. else {
  86762. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86763. }
  86764. index += 4;
  86765. }
  86766. }
  86767. return destArray;
  86768. };
  86769. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86770. var byteArray = new Uint8Array(dataLength);
  86771. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86772. var index = 0;
  86773. for (var y = 0; y < height; y++) {
  86774. for (var x = 0; x < width; x++) {
  86775. var srcPos = (x + y * width) * 4;
  86776. byteArray[index] = srcData[srcPos + rOffset];
  86777. byteArray[index + 1] = srcData[srcPos + gOffset];
  86778. byteArray[index + 2] = srcData[srcPos + bOffset];
  86779. byteArray[index + 3] = srcData[srcPos + aOffset];
  86780. index += 4;
  86781. }
  86782. }
  86783. return byteArray;
  86784. };
  86785. DDSTools._ExtractLongWordOrder = function (value) {
  86786. if (value === 0 || value === 255 || value === -16777216) {
  86787. return 0;
  86788. }
  86789. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86790. };
  86791. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86792. var byteArray = new Uint8Array(dataLength);
  86793. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86794. var index = 0;
  86795. for (var y = 0; y < height; y++) {
  86796. for (var x = 0; x < width; x++) {
  86797. var srcPos = (x + y * width) * 3;
  86798. byteArray[index] = srcData[srcPos + rOffset];
  86799. byteArray[index + 1] = srcData[srcPos + gOffset];
  86800. byteArray[index + 2] = srcData[srcPos + bOffset];
  86801. index += 3;
  86802. }
  86803. }
  86804. return byteArray;
  86805. };
  86806. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86807. var byteArray = new Uint8Array(dataLength);
  86808. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86809. var index = 0;
  86810. for (var y = 0; y < height; y++) {
  86811. for (var x = 0; x < width; x++) {
  86812. var srcPos = (x + y * width);
  86813. byteArray[index] = srcData[srcPos];
  86814. index++;
  86815. }
  86816. }
  86817. return byteArray;
  86818. };
  86819. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86820. if (lodIndex === void 0) { lodIndex = -1; }
  86821. var sphericalPolynomialFaces = null;
  86822. if (info.sphericalPolynomial) {
  86823. sphericalPolynomialFaces = new Array();
  86824. }
  86825. var ext = engine.getCaps().s3tc;
  86826. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86827. var fourCC, width, height, dataLength = 0, dataOffset;
  86828. var byteArray, mipmapCount, mip;
  86829. var internalFormat = 0;
  86830. var format = 0;
  86831. var blockBytes = 1;
  86832. if (header[off_magic] !== DDS_MAGIC) {
  86833. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86834. return;
  86835. }
  86836. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86837. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86838. return;
  86839. }
  86840. if (info.isCompressed && !ext) {
  86841. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86842. return;
  86843. }
  86844. var bpp = header[off_RGBbpp];
  86845. dataOffset = header[off_size] + 4;
  86846. var computeFormats = false;
  86847. if (info.isFourCC) {
  86848. fourCC = header[off_pfFourCC];
  86849. switch (fourCC) {
  86850. case FOURCC_DXT1:
  86851. blockBytes = 8;
  86852. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86853. break;
  86854. case FOURCC_DXT3:
  86855. blockBytes = 16;
  86856. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86857. break;
  86858. case FOURCC_DXT5:
  86859. blockBytes = 16;
  86860. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86861. break;
  86862. case FOURCC_D3DFMT_R16G16B16A16F:
  86863. computeFormats = true;
  86864. break;
  86865. case FOURCC_D3DFMT_R32G32B32A32F:
  86866. computeFormats = true;
  86867. break;
  86868. case FOURCC_DX10:
  86869. // There is an additionnal header so dataOffset need to be changed
  86870. dataOffset += 5 * 4; // 5 uints
  86871. var supported = false;
  86872. switch (info.dxgiFormat) {
  86873. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86874. computeFormats = true;
  86875. supported = true;
  86876. break;
  86877. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86878. info.isRGB = true;
  86879. info.isFourCC = false;
  86880. bpp = 32;
  86881. supported = true;
  86882. break;
  86883. }
  86884. if (supported) {
  86885. break;
  86886. }
  86887. default:
  86888. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86889. return;
  86890. }
  86891. }
  86892. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86893. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86894. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86895. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86896. if (computeFormats) {
  86897. format = engine._getWebGLTextureType(info.textureType);
  86898. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86899. }
  86900. mipmapCount = 1;
  86901. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86902. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86903. }
  86904. for (var face = 0; face < faces; face++) {
  86905. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86906. width = header[off_width];
  86907. height = header[off_height];
  86908. for (mip = 0; mip < mipmapCount; ++mip) {
  86909. if (lodIndex === -1 || lodIndex === mip) {
  86910. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86911. var i = (lodIndex === -1) ? mip : 0;
  86912. if (!info.isCompressed && info.isFourCC) {
  86913. dataLength = width * height * 4;
  86914. var floatArray = null;
  86915. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86916. if (bpp === 128) {
  86917. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86918. if (sphericalPolynomialFaces && i == 0) {
  86919. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86920. }
  86921. }
  86922. else if (bpp === 64) {
  86923. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86924. if (sphericalPolynomialFaces && i == 0) {
  86925. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86926. }
  86927. }
  86928. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86929. format = engine._getWebGLTextureType(info.textureType);
  86930. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86931. }
  86932. else {
  86933. if (bpp === 128) {
  86934. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86935. if (sphericalPolynomialFaces && i == 0) {
  86936. sphericalPolynomialFaces.push(floatArray);
  86937. }
  86938. }
  86939. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86940. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86941. if (sphericalPolynomialFaces && i == 0) {
  86942. sphericalPolynomialFaces.push(floatArray);
  86943. }
  86944. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86945. format = engine._getWebGLTextureType(info.textureType);
  86946. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86947. }
  86948. else { // 64
  86949. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86950. if (sphericalPolynomialFaces && i == 0) {
  86951. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86952. }
  86953. }
  86954. }
  86955. if (floatArray) {
  86956. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86957. }
  86958. }
  86959. else if (info.isRGB) {
  86960. if (bpp === 24) {
  86961. dataLength = width * height * 3;
  86962. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86963. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86964. }
  86965. else { // 32
  86966. dataLength = width * height * 4;
  86967. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86968. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86969. }
  86970. }
  86971. else if (info.isLuminance) {
  86972. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86973. var unpaddedRowSize = width;
  86974. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86975. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86976. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86977. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86978. }
  86979. else {
  86980. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86981. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86982. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86983. }
  86984. }
  86985. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86986. width *= 0.5;
  86987. height *= 0.5;
  86988. width = Math.max(1.0, width);
  86989. height = Math.max(1.0, height);
  86990. }
  86991. if (currentFace !== undefined) {
  86992. // Loading a single face
  86993. break;
  86994. }
  86995. }
  86996. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86997. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86998. size: header[off_width],
  86999. right: sphericalPolynomialFaces[0],
  87000. left: sphericalPolynomialFaces[1],
  87001. up: sphericalPolynomialFaces[2],
  87002. down: sphericalPolynomialFaces[3],
  87003. front: sphericalPolynomialFaces[4],
  87004. back: sphericalPolynomialFaces[5],
  87005. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87006. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87007. gammaSpace: false,
  87008. });
  87009. }
  87010. else {
  87011. info.sphericalPolynomial = undefined;
  87012. }
  87013. };
  87014. DDSTools.StoreLODInAlphaChannel = false;
  87015. return DDSTools;
  87016. }());
  87017. BABYLON.DDSTools = DDSTools;
  87018. })(BABYLON || (BABYLON = {}));
  87019. //# sourceMappingURL=babylon.dds.js.map
  87020. var BABYLON;
  87021. (function (BABYLON) {
  87022. /**
  87023. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87024. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87025. */
  87026. var KhronosTextureContainer = /** @class */ (function () {
  87027. /**
  87028. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87029. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87030. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87031. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87032. */
  87033. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87034. this.arrayBuffer = arrayBuffer;
  87035. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87036. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87037. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87038. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87039. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87040. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87041. BABYLON.Tools.Error("texture missing KTX identifier");
  87042. return;
  87043. }
  87044. // load the reset of the header in native 32 bit int
  87045. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87046. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87047. var oppositeEndianess = header[0] === 0x01020304;
  87048. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87049. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87050. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87051. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87052. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87053. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87054. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87055. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87056. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87057. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87058. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87059. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87060. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87061. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87062. if (this.glType !== 0) {
  87063. BABYLON.Tools.Error("only compressed formats currently supported");
  87064. return;
  87065. }
  87066. else {
  87067. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87068. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87069. }
  87070. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87071. BABYLON.Tools.Error("only 2D textures currently supported");
  87072. return;
  87073. }
  87074. if (this.numberOfArrayElements !== 0) {
  87075. BABYLON.Tools.Error("texture arrays not currently supported");
  87076. return;
  87077. }
  87078. if (this.numberOfFaces !== facesExpected) {
  87079. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87080. return;
  87081. }
  87082. // we now have a completely validated file, so could use existence of loadType as success
  87083. // would need to make this more elaborate & adjust checks above to support more than one load type
  87084. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87085. }
  87086. // not as fast hardware based, but will probably never need to use
  87087. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87088. return ((val & 0xFF) << 24)
  87089. | ((val & 0xFF00) << 8)
  87090. | ((val >> 8) & 0xFF00)
  87091. | ((val >> 24) & 0xFF);
  87092. };
  87093. /**
  87094. * It is assumed that the texture has already been created & is currently bound
  87095. */
  87096. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87097. switch (this.loadType) {
  87098. case KhronosTextureContainer.COMPRESSED_2D:
  87099. this._upload2DCompressedLevels(gl, loadMipmaps);
  87100. break;
  87101. case KhronosTextureContainer.TEX_2D:
  87102. case KhronosTextureContainer.COMPRESSED_3D:
  87103. case KhronosTextureContainer.TEX_3D:
  87104. }
  87105. };
  87106. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87107. // initialize width & height for level 1
  87108. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87109. var width = this.pixelWidth;
  87110. var height = this.pixelHeight;
  87111. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87112. for (var level = 0; level < mipmapCount; level++) {
  87113. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87114. for (var face = 0; face < this.numberOfFaces; face++) {
  87115. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87116. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  87117. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87118. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  87119. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87120. }
  87121. width = Math.max(1.0, width * 0.5);
  87122. height = Math.max(1.0, height * 0.5);
  87123. }
  87124. };
  87125. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87126. // load types
  87127. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87128. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87129. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87130. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87131. return KhronosTextureContainer;
  87132. }());
  87133. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87134. })(BABYLON || (BABYLON = {}));
  87135. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87136. var BABYLON;
  87137. (function (BABYLON) {
  87138. var Debug;
  87139. (function (Debug) {
  87140. /**
  87141. * Class used to render a debug view of a given skeleton
  87142. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87143. */
  87144. var SkeletonViewer = /** @class */ (function () {
  87145. /**
  87146. * Creates a new SkeletonViewer
  87147. * @param skeleton defines the skeleton to render
  87148. * @param mesh defines the mesh attached to the skeleton
  87149. * @param scene defines the hosting scene
  87150. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87151. * @param renderingGroupId defines the rendering group id to use with the viewer
  87152. */
  87153. function SkeletonViewer(
  87154. /** defines the skeleton to render */
  87155. skeleton,
  87156. /** defines the mesh attached to the skeleton */
  87157. mesh, scene,
  87158. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87159. autoUpdateBonesMatrices,
  87160. /** defines the rendering group id to use with the viewer */
  87161. renderingGroupId) {
  87162. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87163. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87164. this.skeleton = skeleton;
  87165. this.mesh = mesh;
  87166. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87167. this.renderingGroupId = renderingGroupId;
  87168. /** Gets or sets the color used to render the skeleton */
  87169. this.color = BABYLON.Color3.White();
  87170. this._debugLines = new Array();
  87171. this._isEnabled = false;
  87172. this._scene = scene;
  87173. this.update();
  87174. this._renderFunction = this.update.bind(this);
  87175. }
  87176. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87177. get: function () {
  87178. return this._isEnabled;
  87179. },
  87180. /** Gets or sets a boolean indicating if the viewer is enabled */
  87181. set: function (value) {
  87182. if (this._isEnabled === value) {
  87183. return;
  87184. }
  87185. this._isEnabled = value;
  87186. if (value) {
  87187. this._scene.registerBeforeRender(this._renderFunction);
  87188. }
  87189. else {
  87190. this._scene.unregisterBeforeRender(this._renderFunction);
  87191. }
  87192. },
  87193. enumerable: true,
  87194. configurable: true
  87195. });
  87196. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87197. if (x === void 0) { x = 0; }
  87198. if (y === void 0) { y = 0; }
  87199. if (z === void 0) { z = 0; }
  87200. var tmat = BABYLON.Tmp.Matrix[0];
  87201. var parentBone = bone.getParent();
  87202. tmat.copyFrom(bone.getLocalMatrix());
  87203. if (x !== 0 || y !== 0 || z !== 0) {
  87204. var tmat2 = BABYLON.Tmp.Matrix[1];
  87205. BABYLON.Matrix.IdentityToRef(tmat2);
  87206. tmat2.m[12] = x;
  87207. tmat2.m[13] = y;
  87208. tmat2.m[14] = z;
  87209. tmat2.multiplyToRef(tmat, tmat);
  87210. }
  87211. if (parentBone) {
  87212. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87213. }
  87214. tmat.multiplyToRef(meshMat, tmat);
  87215. position.x = tmat.m[12];
  87216. position.y = tmat.m[13];
  87217. position.z = tmat.m[14];
  87218. };
  87219. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87220. var len = bones.length;
  87221. var meshPos = this.mesh.position;
  87222. for (var i = 0; i < len; i++) {
  87223. var bone = bones[i];
  87224. var points = this._debugLines[i];
  87225. if (!points) {
  87226. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87227. this._debugLines[i] = points;
  87228. }
  87229. this._getBonePosition(points[0], bone, meshMat);
  87230. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87231. points[0].subtractInPlace(meshPos);
  87232. points[1].subtractInPlace(meshPos);
  87233. }
  87234. };
  87235. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87236. var len = bones.length;
  87237. var boneNum = 0;
  87238. var meshPos = this.mesh.position;
  87239. for (var i = len - 1; i >= 0; i--) {
  87240. var childBone = bones[i];
  87241. var parentBone = childBone.getParent();
  87242. if (!parentBone) {
  87243. continue;
  87244. }
  87245. var points = this._debugLines[boneNum];
  87246. if (!points) {
  87247. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87248. this._debugLines[boneNum] = points;
  87249. }
  87250. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87251. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87252. points[0].subtractInPlace(meshPos);
  87253. points[1].subtractInPlace(meshPos);
  87254. boneNum++;
  87255. }
  87256. };
  87257. /** Update the viewer to sync with current skeleton state */
  87258. SkeletonViewer.prototype.update = function () {
  87259. if (this.autoUpdateBonesMatrices) {
  87260. this.skeleton.computeAbsoluteTransforms();
  87261. }
  87262. if (this.skeleton.bones[0].length === undefined) {
  87263. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87264. }
  87265. else {
  87266. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87267. }
  87268. if (!this._debugMesh) {
  87269. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87270. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87271. }
  87272. else {
  87273. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87274. }
  87275. this._debugMesh.position.copyFrom(this.mesh.position);
  87276. this._debugMesh.color = this.color;
  87277. };
  87278. /** Release associated resources */
  87279. SkeletonViewer.prototype.dispose = function () {
  87280. if (this._debugMesh) {
  87281. this.isEnabled = false;
  87282. this._debugMesh.dispose();
  87283. this._debugMesh = null;
  87284. }
  87285. };
  87286. return SkeletonViewer;
  87287. }());
  87288. Debug.SkeletonViewer = SkeletonViewer;
  87289. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87290. })(BABYLON || (BABYLON = {}));
  87291. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87292. /**
  87293. * Module Debug contains the (visual) components to debug a scene correctly
  87294. */
  87295. var BABYLON;
  87296. (function (BABYLON) {
  87297. var Debug;
  87298. (function (Debug) {
  87299. /**
  87300. * The Axes viewer will show 3 axes in a specific point in space
  87301. */
  87302. var AxesViewer = /** @class */ (function () {
  87303. /**
  87304. * Creates a new AxesViewer
  87305. * @param scene defines the hosting scene
  87306. * @param scaleLines defines a number used to scale line length (1 by default)
  87307. */
  87308. function AxesViewer(scene, scaleLines) {
  87309. if (scaleLines === void 0) { scaleLines = 1; }
  87310. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87311. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87312. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87313. /**
  87314. * Gets or sets a number used to scale line length
  87315. */
  87316. this.scaleLines = 1;
  87317. this.scaleLines = scaleLines;
  87318. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87319. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87320. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87321. this._xmesh.renderingGroupId = 2;
  87322. this._ymesh.renderingGroupId = 2;
  87323. this._zmesh.renderingGroupId = 2;
  87324. this._xmesh.material.checkReadyOnlyOnce = true;
  87325. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87326. this._ymesh.material.checkReadyOnlyOnce = true;
  87327. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87328. this._zmesh.material.checkReadyOnlyOnce = true;
  87329. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87330. this.scene = scene;
  87331. }
  87332. /**
  87333. * Force the viewer to update
  87334. * @param position defines the position of the viewer
  87335. * @param xaxis defines the x axis of the viewer
  87336. * @param yaxis defines the y axis of the viewer
  87337. * @param zaxis defines the z axis of the viewer
  87338. */
  87339. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87340. var scaleLines = this.scaleLines;
  87341. if (this._xmesh) {
  87342. this._xmesh.position.copyFrom(position);
  87343. }
  87344. if (this._ymesh) {
  87345. this._ymesh.position.copyFrom(position);
  87346. }
  87347. if (this._zmesh) {
  87348. this._zmesh.position.copyFrom(position);
  87349. }
  87350. var point2 = this._xline[1];
  87351. point2.x = xaxis.x * scaleLines;
  87352. point2.y = xaxis.y * scaleLines;
  87353. point2.z = xaxis.z * scaleLines;
  87354. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87355. point2 = this._yline[1];
  87356. point2.x = yaxis.x * scaleLines;
  87357. point2.y = yaxis.y * scaleLines;
  87358. point2.z = yaxis.z * scaleLines;
  87359. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87360. point2 = this._zline[1];
  87361. point2.x = zaxis.x * scaleLines;
  87362. point2.y = zaxis.y * scaleLines;
  87363. point2.z = zaxis.z * scaleLines;
  87364. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87365. };
  87366. /** Releases resources */
  87367. AxesViewer.prototype.dispose = function () {
  87368. if (this._xmesh) {
  87369. this._xmesh.dispose();
  87370. }
  87371. if (this._ymesh) {
  87372. this._ymesh.dispose();
  87373. }
  87374. if (this._zmesh) {
  87375. this._zmesh.dispose();
  87376. }
  87377. this._xmesh = null;
  87378. this._ymesh = null;
  87379. this._zmesh = null;
  87380. this.scene = null;
  87381. };
  87382. return AxesViewer;
  87383. }());
  87384. Debug.AxesViewer = AxesViewer;
  87385. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87386. })(BABYLON || (BABYLON = {}));
  87387. //# sourceMappingURL=babylon.axesViewer.js.map
  87388. var BABYLON;
  87389. (function (BABYLON) {
  87390. var Debug;
  87391. (function (Debug) {
  87392. /**
  87393. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87394. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87395. */
  87396. var BoneAxesViewer = /** @class */ (function (_super) {
  87397. __extends(BoneAxesViewer, _super);
  87398. /**
  87399. * Creates a new BoneAxesViewer
  87400. * @param scene defines the hosting scene
  87401. * @param bone defines the target bone
  87402. * @param mesh defines the target mesh
  87403. * @param scaleLines defines a scaling factor for line length (1 by default)
  87404. */
  87405. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87406. if (scaleLines === void 0) { scaleLines = 1; }
  87407. var _this = _super.call(this, scene, scaleLines) || this;
  87408. /** Gets current position */
  87409. _this.pos = BABYLON.Vector3.Zero();
  87410. /** Gets direction of X axis */
  87411. _this.xaxis = BABYLON.Vector3.Zero();
  87412. /** Gets direction of Y axis */
  87413. _this.yaxis = BABYLON.Vector3.Zero();
  87414. /** Gets direction of Z axis */
  87415. _this.zaxis = BABYLON.Vector3.Zero();
  87416. _this.mesh = mesh;
  87417. _this.bone = bone;
  87418. return _this;
  87419. }
  87420. /**
  87421. * Force the viewer to update
  87422. */
  87423. BoneAxesViewer.prototype.update = function () {
  87424. if (!this.mesh || !this.bone) {
  87425. return;
  87426. }
  87427. var bone = this.bone;
  87428. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87429. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87430. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87431. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87432. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87433. };
  87434. /** Releases resources */
  87435. BoneAxesViewer.prototype.dispose = function () {
  87436. if (this.mesh) {
  87437. this.mesh = null;
  87438. this.bone = null;
  87439. _super.prototype.dispose.call(this);
  87440. }
  87441. };
  87442. return BoneAxesViewer;
  87443. }(Debug.AxesViewer));
  87444. Debug.BoneAxesViewer = BoneAxesViewer;
  87445. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87446. })(BABYLON || (BABYLON = {}));
  87447. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87448. var BABYLON;
  87449. (function (BABYLON) {
  87450. var RayHelper = /** @class */ (function () {
  87451. function RayHelper(ray) {
  87452. this.ray = ray;
  87453. }
  87454. RayHelper.CreateAndShow = function (ray, scene, color) {
  87455. var helper = new RayHelper(ray);
  87456. helper.show(scene, color);
  87457. return helper;
  87458. };
  87459. RayHelper.prototype.show = function (scene, color) {
  87460. if (!this._renderFunction && this.ray) {
  87461. var ray = this.ray;
  87462. this._renderFunction = this._render.bind(this);
  87463. this._scene = scene;
  87464. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87465. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87466. if (this._renderFunction) {
  87467. this._scene.registerBeforeRender(this._renderFunction);
  87468. }
  87469. }
  87470. if (color && this._renderLine) {
  87471. this._renderLine.color.copyFrom(color);
  87472. }
  87473. };
  87474. RayHelper.prototype.hide = function () {
  87475. if (this._renderFunction && this._scene) {
  87476. this._scene.unregisterBeforeRender(this._renderFunction);
  87477. this._scene = null;
  87478. this._renderFunction = null;
  87479. if (this._renderLine) {
  87480. this._renderLine.dispose();
  87481. this._renderLine = null;
  87482. }
  87483. this._renderPoints = [];
  87484. }
  87485. };
  87486. RayHelper.prototype._render = function () {
  87487. var ray = this.ray;
  87488. if (!ray) {
  87489. return;
  87490. }
  87491. var point = this._renderPoints[1];
  87492. var len = Math.min(ray.length, 1000000);
  87493. point.copyFrom(ray.direction);
  87494. point.scaleInPlace(len);
  87495. point.addInPlace(ray.origin);
  87496. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87497. };
  87498. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87499. this._attachedToMesh = mesh;
  87500. var ray = this.ray;
  87501. if (!ray) {
  87502. return;
  87503. }
  87504. if (!ray.direction) {
  87505. ray.direction = BABYLON.Vector3.Zero();
  87506. }
  87507. if (!ray.origin) {
  87508. ray.origin = BABYLON.Vector3.Zero();
  87509. }
  87510. if (length) {
  87511. ray.length = length;
  87512. }
  87513. if (!meshSpaceOrigin) {
  87514. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87515. }
  87516. if (!meshSpaceDirection) {
  87517. // -1 so that this will work with Mesh.lookAt
  87518. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87519. }
  87520. if (!this._meshSpaceDirection) {
  87521. this._meshSpaceDirection = meshSpaceDirection.clone();
  87522. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87523. }
  87524. else {
  87525. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87526. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87527. }
  87528. if (!this._updateToMeshFunction) {
  87529. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87530. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87531. }
  87532. this._updateToMesh();
  87533. };
  87534. RayHelper.prototype.detachFromMesh = function () {
  87535. if (this._attachedToMesh) {
  87536. if (this._updateToMeshFunction) {
  87537. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87538. }
  87539. this._attachedToMesh = null;
  87540. this._updateToMeshFunction = null;
  87541. }
  87542. };
  87543. RayHelper.prototype._updateToMesh = function () {
  87544. var ray = this.ray;
  87545. if (!this._attachedToMesh || !ray) {
  87546. return;
  87547. }
  87548. if (this._attachedToMesh._isDisposed) {
  87549. this.detachFromMesh();
  87550. return;
  87551. }
  87552. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87553. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87554. };
  87555. RayHelper.prototype.dispose = function () {
  87556. this.hide();
  87557. this.detachFromMesh();
  87558. this.ray = null;
  87559. };
  87560. return RayHelper;
  87561. }());
  87562. BABYLON.RayHelper = RayHelper;
  87563. })(BABYLON || (BABYLON = {}));
  87564. //# sourceMappingURL=babylon.rayHelper.js.map
  87565. var BABYLON;
  87566. (function (BABYLON) {
  87567. // load the inspector using require, if not present in the global namespace.
  87568. var DebugLayer = /** @class */ (function () {
  87569. function DebugLayer(scene) {
  87570. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87571. this._scene = scene;
  87572. // load inspector using require, if it doesn't exist on the global namespace.
  87573. }
  87574. /** Creates the inspector window. */
  87575. DebugLayer.prototype._createInspector = function (config) {
  87576. if (config === void 0) { config = {}; }
  87577. var popup = config.popup || false;
  87578. var initialTab = config.initialTab || 0;
  87579. var parentElement = config.parentElement || null;
  87580. if (!this._inspector) {
  87581. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87582. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87583. } // else nothing to do,; instance is already existing
  87584. };
  87585. DebugLayer.prototype.isVisible = function () {
  87586. if (!this._inspector) {
  87587. return false;
  87588. }
  87589. return true;
  87590. };
  87591. DebugLayer.prototype.hide = function () {
  87592. if (this._inspector) {
  87593. try {
  87594. this._inspector.dispose();
  87595. }
  87596. catch (e) {
  87597. // If the inspector has been removed directly from the inspector tool
  87598. }
  87599. this.onPropertyChangedObservable.clear();
  87600. this._inspector = null;
  87601. }
  87602. };
  87603. /**
  87604. *
  87605. * Launch the debugLayer.
  87606. *
  87607. * initialTab:
  87608. * | Value | Tab Name |
  87609. * | --- | --- |
  87610. * | 0 | Scene |
  87611. * | 1 | Console |
  87612. * | 2 | Stats |
  87613. * | 3 | Textures |
  87614. * | 4 | Mesh |
  87615. * | 5 | Light |
  87616. * | 6 | Material |
  87617. * | 7 | GLTF |
  87618. * | 8 | GUI |
  87619. * | 9 | Physics |
  87620. * | 10 | Camera |
  87621. * | 11 | Audio |
  87622. *
  87623. */
  87624. DebugLayer.prototype.show = function (config) {
  87625. if (config === void 0) { config = {}; }
  87626. if (typeof this.BJSINSPECTOR == 'undefined') {
  87627. // Load inspector and add it to the DOM
  87628. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87629. }
  87630. else {
  87631. // Otherwise creates the inspector
  87632. this._createInspector(config);
  87633. this.onPropertyChangedObservable = new BABYLON.Observable();
  87634. }
  87635. };
  87636. /**
  87637. * Gets the active tab
  87638. * @return the index of the active tab or -1 if the inspector is hidden
  87639. */
  87640. DebugLayer.prototype.getActiveTab = function () {
  87641. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87642. };
  87643. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87644. return DebugLayer;
  87645. }());
  87646. BABYLON.DebugLayer = DebugLayer;
  87647. })(BABYLON || (BABYLON = {}));
  87648. //# sourceMappingURL=babylon.debugLayer.js.map
  87649. var BABYLON;
  87650. (function (BABYLON) {
  87651. var Debug;
  87652. (function (Debug) {
  87653. /**
  87654. * Used to show the physics impostor around the specific mesh
  87655. */
  87656. var PhysicsViewer = /** @class */ (function () {
  87657. /**
  87658. * Creates a new PhysicsViewer
  87659. * @param scene defines the hosting scene
  87660. */
  87661. function PhysicsViewer(scene) {
  87662. /** @hidden */
  87663. this._impostors = [];
  87664. /** @hidden */
  87665. this._meshes = [];
  87666. /** @hidden */
  87667. this._numMeshes = 0;
  87668. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87669. var physicEngine = this._scene.getPhysicsEngine();
  87670. if (physicEngine) {
  87671. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87672. }
  87673. }
  87674. /** @hidden */
  87675. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87676. var plugin = this._physicsEnginePlugin;
  87677. for (var i = 0; i < this._numMeshes; i++) {
  87678. var impostor = this._impostors[i];
  87679. if (!impostor) {
  87680. continue;
  87681. }
  87682. if (impostor.isDisposed) {
  87683. this.hideImpostor(this._impostors[i--]);
  87684. }
  87685. else {
  87686. var mesh = this._meshes[i];
  87687. if (mesh && plugin) {
  87688. plugin.syncMeshWithImpostor(mesh, impostor);
  87689. }
  87690. }
  87691. }
  87692. };
  87693. /**
  87694. * Renders a specified physic impostor
  87695. * @param impostor defines the impostor to render
  87696. */
  87697. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87698. if (!this._scene) {
  87699. return;
  87700. }
  87701. for (var i = 0; i < this._numMeshes; i++) {
  87702. if (this._impostors[i] == impostor) {
  87703. return;
  87704. }
  87705. }
  87706. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87707. if (debugMesh) {
  87708. this._impostors[this._numMeshes] = impostor;
  87709. this._meshes[this._numMeshes] = debugMesh;
  87710. if (this._numMeshes === 0) {
  87711. this._renderFunction = this._updateDebugMeshes.bind(this);
  87712. this._scene.registerBeforeRender(this._renderFunction);
  87713. }
  87714. this._numMeshes++;
  87715. }
  87716. };
  87717. /**
  87718. * Hides a specified physic impostor
  87719. * @param impostor defines the impostor to hide
  87720. */
  87721. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87722. if (!impostor || !this._scene) {
  87723. return;
  87724. }
  87725. var removed = false;
  87726. for (var i = 0; i < this._numMeshes; i++) {
  87727. if (this._impostors[i] == impostor) {
  87728. var mesh = this._meshes[i];
  87729. if (!mesh) {
  87730. continue;
  87731. }
  87732. this._scene.removeMesh(mesh);
  87733. mesh.dispose();
  87734. this._numMeshes--;
  87735. if (this._numMeshes > 0) {
  87736. this._meshes[i] = this._meshes[this._numMeshes];
  87737. this._impostors[i] = this._impostors[this._numMeshes];
  87738. this._meshes[this._numMeshes] = null;
  87739. this._impostors[this._numMeshes] = null;
  87740. }
  87741. else {
  87742. this._meshes[0] = null;
  87743. this._impostors[0] = null;
  87744. }
  87745. removed = true;
  87746. break;
  87747. }
  87748. }
  87749. if (removed && this._numMeshes === 0) {
  87750. this._scene.unregisterBeforeRender(this._renderFunction);
  87751. }
  87752. };
  87753. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87754. if (!this._debugMaterial) {
  87755. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87756. this._debugMaterial.wireframe = true;
  87757. }
  87758. return this._debugMaterial;
  87759. };
  87760. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87761. if (!this._debugBoxMesh) {
  87762. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87763. this._debugBoxMesh.renderingGroupId = 1;
  87764. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87765. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87766. scene.removeMesh(this._debugBoxMesh);
  87767. }
  87768. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87769. };
  87770. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87771. if (!this._debugSphereMesh) {
  87772. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87773. this._debugSphereMesh.renderingGroupId = 1;
  87774. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87775. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87776. scene.removeMesh(this._debugSphereMesh);
  87777. }
  87778. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87779. };
  87780. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87781. var mesh = null;
  87782. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87783. mesh = this._getDebugBoxMesh(scene);
  87784. impostor.getBoxSizeToRef(mesh.scaling);
  87785. }
  87786. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87787. mesh = this._getDebugSphereMesh(scene);
  87788. var radius = impostor.getRadius();
  87789. mesh.scaling.x = radius * 2;
  87790. mesh.scaling.y = radius * 2;
  87791. mesh.scaling.z = radius * 2;
  87792. }
  87793. return mesh;
  87794. };
  87795. /** Releases all resources */
  87796. PhysicsViewer.prototype.dispose = function () {
  87797. for (var i = 0; i < this._numMeshes; i++) {
  87798. this.hideImpostor(this._impostors[i]);
  87799. }
  87800. if (this._debugBoxMesh) {
  87801. this._debugBoxMesh.dispose();
  87802. }
  87803. if (this._debugSphereMesh) {
  87804. this._debugSphereMesh.dispose();
  87805. }
  87806. if (this._debugMaterial) {
  87807. this._debugMaterial.dispose();
  87808. }
  87809. this._impostors.length = 0;
  87810. this._scene = null;
  87811. this._physicsEnginePlugin = null;
  87812. };
  87813. return PhysicsViewer;
  87814. }());
  87815. Debug.PhysicsViewer = PhysicsViewer;
  87816. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87817. })(BABYLON || (BABYLON = {}));
  87818. //# sourceMappingURL=babylon.physicsViewer.js.map
  87819. var BABYLON;
  87820. (function (BABYLON) {
  87821. var BoundingBoxRenderer = /** @class */ (function () {
  87822. function BoundingBoxRenderer(scene) {
  87823. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87824. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87825. this.showBackLines = true;
  87826. this.renderList = new BABYLON.SmartArray(32);
  87827. this._vertexBuffers = {};
  87828. this._scene = scene;
  87829. }
  87830. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87831. if (this._colorShader) {
  87832. return;
  87833. }
  87834. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87835. attributes: [BABYLON.VertexBuffer.PositionKind],
  87836. uniforms: ["world", "viewProjection", "color"]
  87837. });
  87838. var engine = this._scene.getEngine();
  87839. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87840. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87841. this._createIndexBuffer();
  87842. };
  87843. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87844. var engine = this._scene.getEngine();
  87845. 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]);
  87846. };
  87847. BoundingBoxRenderer.prototype._rebuild = function () {
  87848. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87849. if (vb) {
  87850. vb._rebuild();
  87851. }
  87852. this._createIndexBuffer();
  87853. };
  87854. BoundingBoxRenderer.prototype.reset = function () {
  87855. this.renderList.reset();
  87856. };
  87857. BoundingBoxRenderer.prototype.render = function () {
  87858. if (this.renderList.length === 0) {
  87859. return;
  87860. }
  87861. this._prepareRessources();
  87862. if (!this._colorShader.isReady()) {
  87863. return;
  87864. }
  87865. var engine = this._scene.getEngine();
  87866. engine.setDepthWrite(false);
  87867. this._colorShader._preBind();
  87868. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87869. var boundingBox = this.renderList.data[boundingBoxIndex];
  87870. var min = boundingBox.minimum;
  87871. var max = boundingBox.maximum;
  87872. var diff = max.subtract(min);
  87873. var median = min.add(diff.scale(0.5));
  87874. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87875. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87876. .multiply(boundingBox.getWorldMatrix());
  87877. // VBOs
  87878. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87879. if (this.showBackLines) {
  87880. // Back
  87881. engine.setDepthFunctionToGreaterOrEqual();
  87882. this._scene.resetCachedMaterial();
  87883. this._colorShader.setColor4("color", this.backColor.toColor4());
  87884. this._colorShader.bind(worldMatrix);
  87885. // Draw order
  87886. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87887. }
  87888. // Front
  87889. engine.setDepthFunctionToLess();
  87890. this._scene.resetCachedMaterial();
  87891. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87892. this._colorShader.bind(worldMatrix);
  87893. // Draw order
  87894. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87895. }
  87896. this._colorShader.unbind();
  87897. engine.setDepthFunctionToLessOrEqual();
  87898. engine.setDepthWrite(true);
  87899. };
  87900. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87901. this._prepareRessources();
  87902. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87903. return;
  87904. }
  87905. var engine = this._scene.getEngine();
  87906. engine.setDepthWrite(false);
  87907. engine.setColorWrite(false);
  87908. this._colorShader._preBind();
  87909. var boundingBox = mesh._boundingInfo.boundingBox;
  87910. var min = boundingBox.minimum;
  87911. var max = boundingBox.maximum;
  87912. var diff = max.subtract(min);
  87913. var median = min.add(diff.scale(0.5));
  87914. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87915. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87916. .multiply(boundingBox.getWorldMatrix());
  87917. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87918. engine.setDepthFunctionToLess();
  87919. this._scene.resetCachedMaterial();
  87920. this._colorShader.bind(worldMatrix);
  87921. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87922. this._colorShader.unbind();
  87923. engine.setDepthFunctionToLessOrEqual();
  87924. engine.setDepthWrite(true);
  87925. engine.setColorWrite(true);
  87926. };
  87927. BoundingBoxRenderer.prototype.dispose = function () {
  87928. if (!this._colorShader) {
  87929. return;
  87930. }
  87931. this.renderList.dispose();
  87932. this._colorShader.dispose();
  87933. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87934. if (buffer) {
  87935. buffer.dispose();
  87936. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87937. }
  87938. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87939. };
  87940. return BoundingBoxRenderer;
  87941. }());
  87942. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87943. })(BABYLON || (BABYLON = {}));
  87944. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87945. var BABYLON;
  87946. (function (BABYLON) {
  87947. /**
  87948. * Renders a layer on top of an existing scene
  87949. */
  87950. var UtilityLayerRenderer = /** @class */ (function () {
  87951. /**
  87952. * Instantiates a UtilityLayerRenderer
  87953. * @param originalScene the original scene that will be rendered on top of
  87954. */
  87955. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87956. var _this = this;
  87957. this.originalScene = originalScene;
  87958. this._pointerCaptures = {};
  87959. this._lastPointerEvents = {};
  87960. /**
  87961. * If the utility layer should automatically be rendered on top of existing scene
  87962. */
  87963. this.shouldRender = true;
  87964. /**
  87965. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87966. */
  87967. this.onlyCheckPointerDownEvents = true;
  87968. /**
  87969. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87970. */
  87971. this.processAllEvents = false;
  87972. /**
  87973. * Observable raised when the pointer move from the utility layer scene to the main scene
  87974. */
  87975. this.onPointerOutObservable = new BABYLON.Observable();
  87976. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87977. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87978. originalScene.getEngine().scenes.pop();
  87979. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87980. this.utilityLayerScene.detachControl();
  87981. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87982. if (!_this.processAllEvents) {
  87983. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87984. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87985. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87986. return;
  87987. }
  87988. }
  87989. var pointerEvent = (prePointerInfo.event);
  87990. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  87991. return;
  87992. }
  87993. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87994. if (!prePointerInfo.ray && utilityScenePick) {
  87995. prePointerInfo.ray = utilityScenePick.ray;
  87996. }
  87997. // always fire the prepointer oversvable
  87998. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87999. // allow every non pointer down event to flow to the utility layer
  88000. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88001. if (!prePointerInfo.skipOnPointerObservable) {
  88002. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88003. }
  88004. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88005. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88006. }
  88007. return;
  88008. }
  88009. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88010. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88011. if (utilityScenePick && utilityScenePick.hit) {
  88012. if (!prePointerInfo.skipOnPointerObservable) {
  88013. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88014. }
  88015. prePointerInfo.skipOnPointerObservable = true;
  88016. }
  88017. }
  88018. else {
  88019. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88020. var pointerEvent_1 = (prePointerInfo.event);
  88021. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88022. if (originalScenePick && utilityScenePick) {
  88023. // No pick in utility scene
  88024. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88025. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88026. // We touched an utility mesh present in the main scene
  88027. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88028. prePointerInfo.skipOnPointerObservable = true;
  88029. }
  88030. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88031. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88032. }
  88033. }
  88034. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88035. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88036. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88037. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88038. }
  88039. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88040. // We have a pick in both scenes but main is closer than utility
  88041. // We touched an utility mesh present in the main scene
  88042. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88043. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88044. prePointerInfo.skipOnPointerObservable = true;
  88045. }
  88046. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88047. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88048. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88049. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88050. }
  88051. }
  88052. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88053. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88054. }
  88055. }
  88056. }
  88057. });
  88058. // Render directly on top of existing scene without clearing
  88059. this.utilityLayerScene.autoClear = false;
  88060. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88061. if (_this.shouldRender) {
  88062. _this.render();
  88063. }
  88064. });
  88065. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88066. _this.dispose();
  88067. });
  88068. this._updateCamera();
  88069. }
  88070. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88071. if (!prePointerInfo.skipOnPointerObservable) {
  88072. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88073. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88074. }
  88075. };
  88076. /**
  88077. * Renders the utility layers scene on top of the original scene
  88078. */
  88079. UtilityLayerRenderer.prototype.render = function () {
  88080. this._updateCamera();
  88081. this.utilityLayerScene.render(false);
  88082. };
  88083. /**
  88084. * Disposes of the renderer
  88085. */
  88086. UtilityLayerRenderer.prototype.dispose = function () {
  88087. this.onPointerOutObservable.clear();
  88088. if (this._afterRenderObserver) {
  88089. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88090. }
  88091. if (this._sceneDisposeObserver) {
  88092. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88093. }
  88094. if (this._originalPointerObserver) {
  88095. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88096. }
  88097. this.utilityLayerScene.dispose();
  88098. };
  88099. UtilityLayerRenderer.prototype._updateCamera = function () {
  88100. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88101. };
  88102. return UtilityLayerRenderer;
  88103. }());
  88104. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88105. })(BABYLON || (BABYLON = {}));
  88106. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88107. //# sourceMappingURL=babylon.behavior.js.map
  88108. var BABYLON;
  88109. (function (BABYLON) {
  88110. /**
  88111. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88112. */
  88113. var PointerDragBehavior = /** @class */ (function () {
  88114. /**
  88115. * Creates a pointer drag behavior that can be attached to a mesh
  88116. * @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)
  88117. */
  88118. function PointerDragBehavior(options) {
  88119. this.options = options;
  88120. /**
  88121. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88122. */
  88123. this.currentDraggingPointerID = -1;
  88124. /**
  88125. * If the behavior is currently in a dragging state
  88126. */
  88127. this.dragging = false;
  88128. /**
  88129. * 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)
  88130. */
  88131. this.dragDeltaRatio = 0.2;
  88132. /**
  88133. * If the drag plane orientation should be updated during the dragging (Default: true)
  88134. */
  88135. this.updateDragPlane = true;
  88136. // Debug mode will display drag planes to help visualize behavior
  88137. this._debugMode = false;
  88138. this._moving = false;
  88139. /**
  88140. * Fires each time the attached mesh is dragged with the pointer
  88141. * * delta between last drag position and current drag position in world space
  88142. * * dragDistance along the drag axis
  88143. * * dragPlaneNormal normal of the current drag plane used during the drag
  88144. * * dragPlanePoint in world space where the drag intersects the drag plane
  88145. */
  88146. this.onDragObservable = new BABYLON.Observable();
  88147. /**
  88148. * Fires each time a drag begins (eg. mouse down on mesh)
  88149. */
  88150. this.onDragStartObservable = new BABYLON.Observable();
  88151. /**
  88152. * Fires each time a drag ends (eg. mouse release after drag)
  88153. */
  88154. this.onDragEndObservable = new BABYLON.Observable();
  88155. /**
  88156. * If the attached mesh should be moved when dragged
  88157. */
  88158. this.moveAttached = true;
  88159. /**
  88160. * If the drag behavior will react to drag events (Default: true)
  88161. */
  88162. this.enabled = true;
  88163. /**
  88164. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88165. */
  88166. this.useObjectOrienationForDragging = true;
  88167. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88168. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88169. // Variables to avoid instantiation in the below method
  88170. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88171. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88172. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88173. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88174. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88175. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88176. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88177. var optionCount = 0;
  88178. if (options === undefined) {
  88179. options = {};
  88180. }
  88181. if (options.dragAxis) {
  88182. optionCount++;
  88183. }
  88184. if (options.dragPlaneNormal) {
  88185. optionCount++;
  88186. }
  88187. if (optionCount > 1) {
  88188. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88189. }
  88190. }
  88191. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88192. /**
  88193. * The name of the behavior
  88194. */
  88195. get: function () {
  88196. return "PointerDrag";
  88197. },
  88198. enumerable: true,
  88199. configurable: true
  88200. });
  88201. /**
  88202. * Initializes the behavior
  88203. */
  88204. PointerDragBehavior.prototype.init = function () { };
  88205. /**
  88206. * Attaches the drag behavior the passed in mesh
  88207. * @param ownerNode The mesh that will be dragged around once attached
  88208. */
  88209. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88210. var _this = this;
  88211. this._scene = ownerNode.getScene();
  88212. this._attachedNode = ownerNode;
  88213. // Initialize drag plane to not interfere with existing scene
  88214. if (!PointerDragBehavior._planeScene) {
  88215. if (this._debugMode) {
  88216. PointerDragBehavior._planeScene = this._scene;
  88217. }
  88218. else {
  88219. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88220. this._scene.getEngine().scenes.pop();
  88221. }
  88222. }
  88223. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88224. // State of the drag
  88225. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88226. var delta = new BABYLON.Vector3(0, 0, 0);
  88227. var dragLength = 0;
  88228. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88229. var pickPredicate = function (m) {
  88230. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88231. };
  88232. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88233. if (!_this.enabled) {
  88234. return;
  88235. }
  88236. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88237. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88238. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88239. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88240. if (pickedPoint) {
  88241. _this.dragging = true;
  88242. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88243. _this.lastDragPosition.copyFrom(pickedPoint);
  88244. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88245. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88246. }
  88247. }
  88248. }
  88249. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88250. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88251. _this.releaseDrag();
  88252. }
  88253. }
  88254. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88255. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88256. _this._moving = true;
  88257. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88258. if (pickedPoint) {
  88259. if (_this.updateDragPlane) {
  88260. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88261. }
  88262. // depending on the drag mode option drag accordingly
  88263. if (_this.options.dragAxis) {
  88264. // Convert local drag axis to world
  88265. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88266. // Project delta drag from the drag plane onto the drag axis
  88267. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88268. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88269. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88270. }
  88271. else {
  88272. dragLength = delta.length();
  88273. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88274. }
  88275. targetPosition.addInPlace(delta);
  88276. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88277. _this.lastDragPosition.copyFrom(pickedPoint);
  88278. }
  88279. }
  88280. }
  88281. });
  88282. this._scene.onBeforeRenderObservable.add(function () {
  88283. if (_this._moving && _this.moveAttached) {
  88284. // Slowly move mesh to avoid jitter
  88285. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88286. _this._tmpVector.scaleInPlace(0.2);
  88287. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88288. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88289. }
  88290. });
  88291. };
  88292. PointerDragBehavior.prototype.releaseDrag = function () {
  88293. this.dragging = false;
  88294. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88295. this.currentDraggingPointerID = -1;
  88296. this._moving = false;
  88297. };
  88298. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88299. var _this = this;
  88300. if (!ray) {
  88301. return null;
  88302. }
  88303. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88304. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88305. return pickResult.pickedPoint;
  88306. }
  88307. else {
  88308. return null;
  88309. }
  88310. };
  88311. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88312. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88313. this._pointA.copyFrom(dragPlanePosition);
  88314. if (this.options.dragAxis) {
  88315. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88316. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88317. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88318. ray.origin.subtractToRef(this._pointA, this._pointC);
  88319. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88320. // Get perpendicular line from direction to camera and drag axis
  88321. this._pointB.subtractToRef(this._pointA, this._lineA);
  88322. this._pointC.subtractToRef(this._pointA, this._lineB);
  88323. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88324. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88325. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88326. this._lookAt.normalize();
  88327. this._dragPlane.position.copyFrom(this._pointA);
  88328. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88329. this._dragPlane.lookAt(this._lookAt);
  88330. }
  88331. else if (this.options.dragPlaneNormal) {
  88332. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88333. this._dragPlane.position.copyFrom(this._pointA);
  88334. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88335. this._dragPlane.lookAt(this._lookAt);
  88336. }
  88337. else {
  88338. this._dragPlane.position.copyFrom(this._pointA);
  88339. this._dragPlane.lookAt(ray.origin);
  88340. }
  88341. this._dragPlane.computeWorldMatrix(true);
  88342. };
  88343. /**
  88344. * Detaches the behavior from the mesh
  88345. */
  88346. PointerDragBehavior.prototype.detach = function () {
  88347. if (this._pointerObserver) {
  88348. this._scene.onPointerObservable.remove(this._pointerObserver);
  88349. }
  88350. };
  88351. return PointerDragBehavior;
  88352. }());
  88353. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88354. })(BABYLON || (BABYLON = {}));
  88355. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88356. var BABYLON;
  88357. (function (BABYLON) {
  88358. /**
  88359. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88360. */
  88361. var MultiPointerScaleBehavior = /** @class */ (function () {
  88362. function MultiPointerScaleBehavior() {
  88363. this._startDistance = 0;
  88364. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88365. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88366. this._sceneRenderObserver = null;
  88367. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88368. this._dragBehaviorA.moveAttached = false;
  88369. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88370. this._dragBehaviorB.moveAttached = false;
  88371. }
  88372. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88373. /**
  88374. * The name of the behavior
  88375. */
  88376. get: function () {
  88377. return "MultiPointerScale";
  88378. },
  88379. enumerable: true,
  88380. configurable: true
  88381. });
  88382. /**
  88383. * Initializes the behavior
  88384. */
  88385. MultiPointerScaleBehavior.prototype.init = function () { };
  88386. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88387. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88388. };
  88389. /**
  88390. * Attaches the scale behavior the passed in mesh
  88391. * @param ownerNode The mesh that will be scaled around once attached
  88392. */
  88393. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88394. var _this = this;
  88395. this._ownerNode = ownerNode;
  88396. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88397. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88398. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88399. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88400. _this._dragBehaviorA.releaseDrag();
  88401. }
  88402. else {
  88403. _this._initialScale.copyFrom(ownerNode.scaling);
  88404. _this._startDistance = _this._getCurrentDistance();
  88405. }
  88406. }
  88407. });
  88408. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88409. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88410. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88411. _this._dragBehaviorB.releaseDrag();
  88412. }
  88413. else {
  88414. _this._initialScale.copyFrom(ownerNode.scaling);
  88415. _this._startDistance = _this._getCurrentDistance();
  88416. }
  88417. }
  88418. });
  88419. // Once both drag behaviors are active scale based on the distance between the two pointers
  88420. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88421. behavior.onDragObservable.add(function () {
  88422. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88423. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88424. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88425. }
  88426. });
  88427. });
  88428. ownerNode.addBehavior(this._dragBehaviorA);
  88429. ownerNode.addBehavior(this._dragBehaviorB);
  88430. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88431. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88432. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88433. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88434. if (change.length() > 0.01) {
  88435. ownerNode.scaling.addInPlace(change);
  88436. }
  88437. }
  88438. });
  88439. };
  88440. /**
  88441. * Detaches the behavior from the mesh
  88442. */
  88443. MultiPointerScaleBehavior.prototype.detach = function () {
  88444. var _this = this;
  88445. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88446. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88447. behavior.onDragStartObservable.clear();
  88448. behavior.onDragObservable.clear();
  88449. _this._ownerNode.removeBehavior(behavior);
  88450. });
  88451. };
  88452. return MultiPointerScaleBehavior;
  88453. }());
  88454. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88455. })(BABYLON || (BABYLON = {}));
  88456. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88457. var BABYLON;
  88458. (function (BABYLON) {
  88459. /**
  88460. * 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
  88461. */
  88462. var SixDofDragBehavior = /** @class */ (function () {
  88463. function SixDofDragBehavior() {
  88464. this._sceneRenderObserver = null;
  88465. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88466. this._moving = false;
  88467. this._startingOrientation = new BABYLON.Quaternion();
  88468. /**
  88469. * 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)
  88470. */
  88471. this.zDragFactor = 5;
  88472. /**
  88473. * If the behavior is currently in a dragging state
  88474. */
  88475. this.dragging = false;
  88476. /**
  88477. * 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)
  88478. */
  88479. this.dragDeltaRatio = 0.2;
  88480. /**
  88481. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88482. */
  88483. this.currentDraggingPointerID = -1;
  88484. }
  88485. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88486. /**
  88487. * The name of the behavior
  88488. */
  88489. get: function () {
  88490. return "SixDofDrag";
  88491. },
  88492. enumerable: true,
  88493. configurable: true
  88494. });
  88495. /**
  88496. * Initializes the behavior
  88497. */
  88498. SixDofDragBehavior.prototype.init = function () { };
  88499. /**
  88500. * Attaches the scale behavior the passed in mesh
  88501. * @param ownerNode The mesh that will be scaled around once attached
  88502. */
  88503. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88504. var _this = this;
  88505. this._ownerNode = ownerNode;
  88506. this._scene = this._ownerNode.getScene();
  88507. if (!SixDofDragBehavior._virtualScene) {
  88508. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88509. this._scene.getEngine().scenes.pop();
  88510. }
  88511. var pickedMesh = null;
  88512. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88513. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88514. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88515. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88516. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88517. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88518. var pickPredicate = function (m) {
  88519. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88520. };
  88521. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88522. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88523. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88524. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88525. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88526. // Set position and orientation of the controller
  88527. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88528. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88529. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88530. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88531. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88532. if (!pickedMesh.rotationQuaternion) {
  88533. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88534. }
  88535. var oldParent = pickedMesh.parent;
  88536. pickedMesh.setParent(null);
  88537. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88538. pickedMesh.setParent(oldParent);
  88539. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88540. // Update state
  88541. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88542. _this.dragging = true;
  88543. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88544. }
  88545. }
  88546. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88547. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88548. _this.dragging = false;
  88549. _this._moving = false;
  88550. _this.currentDraggingPointerID = -1;
  88551. pickedMesh = null;
  88552. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88553. }
  88554. }
  88555. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88556. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88557. // Calculate controller drag distance in controller space
  88558. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88559. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88560. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88561. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88562. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88563. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88564. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88565. if (_this._virtualDragMesh.position.z < 0) {
  88566. _this._virtualDragMesh.position.z = 0;
  88567. }
  88568. // Update the controller position
  88569. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88570. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88571. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88572. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88573. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88574. if (pickedMesh.parent) {
  88575. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88576. }
  88577. if (!_this._moving) {
  88578. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88579. }
  88580. _this._moving = true;
  88581. }
  88582. }
  88583. });
  88584. var tmpQuaternion = new BABYLON.Quaternion();
  88585. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88586. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88587. if (_this.dragging && _this._moving && pickedMesh) {
  88588. // Slowly move mesh to avoid jitter
  88589. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88590. // Get change in rotation
  88591. tmpQuaternion.copyFrom(_this._startingOrientation);
  88592. tmpQuaternion.x = -tmpQuaternion.x;
  88593. tmpQuaternion.y = -tmpQuaternion.y;
  88594. tmpQuaternion.z = -tmpQuaternion.z;
  88595. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88596. // Convert change in rotation to only y axis rotation
  88597. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88598. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88599. // Slowly move mesh to avoid jitter
  88600. var oldParent = pickedMesh.parent;
  88601. pickedMesh.setParent(null);
  88602. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88603. pickedMesh.setParent(oldParent);
  88604. }
  88605. });
  88606. };
  88607. /**
  88608. * Detaches the behavior from the mesh
  88609. */
  88610. SixDofDragBehavior.prototype.detach = function () {
  88611. this._scene.onPointerObservable.remove(this._pointerObserver);
  88612. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88613. this._virtualOriginMesh.dispose();
  88614. this._virtualDragMesh.dispose();
  88615. };
  88616. return SixDofDragBehavior;
  88617. }());
  88618. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88619. })(BABYLON || (BABYLON = {}));
  88620. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88621. var BABYLON;
  88622. (function (BABYLON) {
  88623. /**
  88624. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88625. */
  88626. var Gizmo = /** @class */ (function () {
  88627. /**
  88628. * Creates a gizmo
  88629. * @param gizmoLayer The utility layer the gizmo will be added to
  88630. */
  88631. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88632. var _this = this;
  88633. this.gizmoLayer = gizmoLayer;
  88634. /**
  88635. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88636. */
  88637. this.updateGizmoRotationToMatchAttachedMesh = true;
  88638. /**
  88639. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88640. */
  88641. this.updateGizmoPositionToMatchAttachedMesh = true;
  88642. /**
  88643. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88644. */
  88645. this._updateScale = true;
  88646. this._interactionsEnabled = true;
  88647. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88648. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88649. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88650. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88651. _this._rootMesh.scaling.set(dist, dist, dist);
  88652. }
  88653. if (_this.attachedMesh) {
  88654. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88655. if (!_this._rootMesh.rotationQuaternion) {
  88656. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88657. }
  88658. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88659. }
  88660. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88661. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88662. }
  88663. }
  88664. });
  88665. }
  88666. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88667. };
  88668. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  88669. get: function () {
  88670. return this._interactionsEnabled;
  88671. },
  88672. /**
  88673. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  88674. */
  88675. set: function (value) {
  88676. this._interactionsEnabled = value;
  88677. this._onInteractionsEnabledChanged(value);
  88678. },
  88679. enumerable: true,
  88680. configurable: true
  88681. });
  88682. /**
  88683. * Disposes of the gizmo
  88684. */
  88685. Gizmo.prototype.dispose = function () {
  88686. this._rootMesh.dispose();
  88687. if (this._beforeRenderObserver) {
  88688. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88689. }
  88690. };
  88691. return Gizmo;
  88692. }());
  88693. BABYLON.Gizmo = Gizmo;
  88694. })(BABYLON || (BABYLON = {}));
  88695. //# sourceMappingURL=babylon.gizmo.js.map
  88696. var BABYLON;
  88697. (function (BABYLON) {
  88698. /**
  88699. * Single axis drag gizmo
  88700. */
  88701. var AxisDragGizmo = /** @class */ (function (_super) {
  88702. __extends(AxisDragGizmo, _super);
  88703. /**
  88704. * Creates an AxisDragGizmo
  88705. * @param gizmoLayer The utility layer the gizmo will be added to
  88706. * @param dragAxis The axis which the gizmo will be able to drag on
  88707. * @param color The color of the gizmo
  88708. */
  88709. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  88710. var _this = _super.call(this, gizmoLayer) || this;
  88711. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88712. // Create Material
  88713. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88714. coloredMaterial.disableLighting = true;
  88715. coloredMaterial.emissiveColor = color;
  88716. // Build mesh on root node
  88717. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88718. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88719. _this._rootMesh.addChild(arrowMesh);
  88720. _this._rootMesh.addChild(arrowTail);
  88721. // Position arrow pointing in its drag axis
  88722. arrowMesh.scaling.scaleInPlace(0.1);
  88723. arrowMesh.material = coloredMaterial;
  88724. arrowMesh.rotation.x = Math.PI / 2;
  88725. arrowMesh.position.z += 0.3;
  88726. arrowTail.rotation.x = Math.PI / 2;
  88727. arrowTail.material = coloredMaterial;
  88728. arrowTail.position.z += 0.2;
  88729. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88730. // Add drag behavior to handle events when the gizmo is dragged
  88731. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88732. _this._dragBehavior.moveAttached = false;
  88733. _this._rootMesh.addBehavior(_this._dragBehavior);
  88734. _this._dragBehavior.onDragObservable.add(function (event) {
  88735. if (!_this.interactionsEnabled) {
  88736. return;
  88737. }
  88738. if (_this.attachedMesh) {
  88739. _this.attachedMesh.position.addInPlace(event.delta);
  88740. }
  88741. });
  88742. return _this;
  88743. }
  88744. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88745. this._dragBehavior.enabled = value;
  88746. };
  88747. /**
  88748. * Disposes of the gizmo
  88749. */
  88750. AxisDragGizmo.prototype.dispose = function () {
  88751. this._dragBehavior.detach();
  88752. _super.prototype.dispose.call(this);
  88753. };
  88754. return AxisDragGizmo;
  88755. }(BABYLON.Gizmo));
  88756. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88757. })(BABYLON || (BABYLON = {}));
  88758. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88759. var BABYLON;
  88760. (function (BABYLON) {
  88761. /**
  88762. * Single axis scale gizmo
  88763. */
  88764. var AxisScaleGizmo = /** @class */ (function (_super) {
  88765. __extends(AxisScaleGizmo, _super);
  88766. /**
  88767. * Creates an AxisScaleGizmo
  88768. * @param gizmoLayer The utility layer the gizmo will be added to
  88769. * @param dragAxis The axis which the gizmo will be able to scale on
  88770. * @param color The color of the gizmo
  88771. */
  88772. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  88773. var _this = _super.call(this, gizmoLayer) || this;
  88774. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88775. // Create Material
  88776. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88777. coloredMaterial.disableLighting = true;
  88778. coloredMaterial.emissiveColor = color;
  88779. // Build mesh on root node
  88780. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  88781. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88782. _this._rootMesh.addChild(arrowMesh);
  88783. _this._rootMesh.addChild(arrowTail);
  88784. // Position arrow pointing in its drag axis
  88785. arrowMesh.scaling.scaleInPlace(0.1);
  88786. arrowMesh.material = coloredMaterial;
  88787. arrowMesh.rotation.x = Math.PI / 2;
  88788. arrowMesh.position.z += 0.3;
  88789. arrowTail.rotation.x = Math.PI / 2;
  88790. arrowTail.material = coloredMaterial;
  88791. arrowTail.position.z += 0.2;
  88792. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88793. // Add drag behavior to handle events when the gizmo is dragged
  88794. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88795. _this._dragBehavior.moveAttached = false;
  88796. _this._rootMesh.addBehavior(_this._dragBehavior);
  88797. _this._dragBehavior.onDragObservable.add(function (event) {
  88798. if (!_this.interactionsEnabled) {
  88799. return;
  88800. }
  88801. if (_this.attachedMesh) {
  88802. _this.attachedMesh.scaling.addInPlace(event.delta);
  88803. }
  88804. });
  88805. return _this;
  88806. }
  88807. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88808. this._dragBehavior.enabled = value;
  88809. };
  88810. /**
  88811. * Disposes of the gizmo
  88812. */
  88813. AxisScaleGizmo.prototype.dispose = function () {
  88814. this._dragBehavior.detach();
  88815. _super.prototype.dispose.call(this);
  88816. };
  88817. return AxisScaleGizmo;
  88818. }(BABYLON.Gizmo));
  88819. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  88820. })(BABYLON || (BABYLON = {}));
  88821. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  88822. var BABYLON;
  88823. (function (BABYLON) {
  88824. /**
  88825. * Single plane rotation gizmo
  88826. */
  88827. var PlaneRotationGizmo = /** @class */ (function (_super) {
  88828. __extends(PlaneRotationGizmo, _super);
  88829. /**
  88830. * Creates a PlaneRotationGizmo
  88831. * @param gizmoLayer The utility layer the gizmo will be added to
  88832. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  88833. * @param color The color of the gizmo
  88834. */
  88835. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  88836. var _this = _super.call(this, gizmoLayer) || this;
  88837. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88838. // Create Material
  88839. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88840. coloredMaterial.disableLighting = true;
  88841. coloredMaterial.emissiveColor = color;
  88842. // Build mesh on root node
  88843. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  88844. _this._rootMesh.addChild(rotationMesh);
  88845. // Position arrow pointing in its drag axis
  88846. rotationMesh.scaling.scaleInPlace(0.1);
  88847. rotationMesh.material = coloredMaterial;
  88848. rotationMesh.rotation.x = Math.PI / 2;
  88849. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  88850. // Add drag behavior to handle events when the gizmo is dragged
  88851. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: new BABYLON.Vector3(0, 0, 1) });
  88852. _this._dragBehavior.moveAttached = false;
  88853. _this._rootMesh.addBehavior(_this._dragBehavior);
  88854. var lastDragPosition = null;
  88855. _this._dragBehavior.onDragStartObservable.add(function (e) {
  88856. if (!_this.interactionsEnabled) {
  88857. return;
  88858. }
  88859. lastDragPosition = e.dragPlanePoint;
  88860. });
  88861. _this._dragBehavior.onDragObservable.add(function (event) {
  88862. if (!_this.interactionsEnabled) {
  88863. return;
  88864. }
  88865. if (_this.attachedMesh && lastDragPosition) {
  88866. if (!_this.attachedMesh.rotationQuaternion) {
  88867. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88868. }
  88869. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  88870. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  88871. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  88872. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  88873. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  88874. var angle = Math.atan2(cross.length(), dot);
  88875. var up = planeNormal.clone();
  88876. // Flip up vector depending on which side the camera is on
  88877. if (gizmoLayer.utilityLayerScene.activeCamera) {
  88878. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  88879. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  88880. up.scaleInPlace(-1);
  88881. }
  88882. }
  88883. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  88884. if (halfCircleSide)
  88885. angle = -angle;
  88886. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  88887. var quaternionCoefficient = Math.sin(angle / 2);
  88888. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  88889. // Rotate selected mesh quaternion over fixed axis
  88890. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  88891. lastDragPosition = event.dragPlanePoint;
  88892. }
  88893. });
  88894. return _this;
  88895. }
  88896. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88897. this._dragBehavior.enabled = value;
  88898. };
  88899. /**
  88900. * Disposes of the gizmo
  88901. */
  88902. PlaneRotationGizmo.prototype.dispose = function () {
  88903. this._dragBehavior.detach();
  88904. _super.prototype.dispose.call(this);
  88905. };
  88906. return PlaneRotationGizmo;
  88907. }(BABYLON.Gizmo));
  88908. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  88909. })(BABYLON || (BABYLON = {}));
  88910. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  88911. var BABYLON;
  88912. (function (BABYLON) {
  88913. /**
  88914. * Gizmo that enables dragging a mesh along 3 axis
  88915. */
  88916. var PositionGizmo = /** @class */ (function (_super) {
  88917. __extends(PositionGizmo, _super);
  88918. /**
  88919. * Creates a PositionGizmo
  88920. * @param gizmoLayer The utility layer the gizmo will be added to
  88921. */
  88922. function PositionGizmo(gizmoLayer) {
  88923. var _this = _super.call(this, gizmoLayer) || this;
  88924. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88925. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88926. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88927. return _this;
  88928. }
  88929. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  88930. set: function (mesh) {
  88931. this._xDrag.attachedMesh = mesh;
  88932. this._yDrag.attachedMesh = mesh;
  88933. this._zDrag.attachedMesh = mesh;
  88934. },
  88935. enumerable: true,
  88936. configurable: true
  88937. });
  88938. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88939. this._xDrag.interactionsEnabled = value;
  88940. this._yDrag.interactionsEnabled = value;
  88941. this._zDrag.interactionsEnabled = value;
  88942. };
  88943. /**
  88944. * Disposes of the gizmo
  88945. */
  88946. PositionGizmo.prototype.dispose = function () {
  88947. this._xDrag.dispose();
  88948. this._yDrag.dispose();
  88949. this._zDrag.dispose();
  88950. };
  88951. return PositionGizmo;
  88952. }(BABYLON.Gizmo));
  88953. BABYLON.PositionGizmo = PositionGizmo;
  88954. })(BABYLON || (BABYLON = {}));
  88955. //# sourceMappingURL=babylon.positionGizmo.js.map
  88956. var BABYLON;
  88957. (function (BABYLON) {
  88958. /**
  88959. * Gizmo that enables rotating a mesh along 3 axis
  88960. */
  88961. var RotationGizmo = /** @class */ (function (_super) {
  88962. __extends(RotationGizmo, _super);
  88963. /**
  88964. * Creates a RotationGizmo
  88965. * @param gizmoLayer The utility layer the gizmo will be added to
  88966. */
  88967. function RotationGizmo(gizmoLayer) {
  88968. var _this = _super.call(this, gizmoLayer) || this;
  88969. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88970. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88971. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88972. return _this;
  88973. }
  88974. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  88975. set: function (mesh) {
  88976. this._xDrag.attachedMesh = mesh;
  88977. this._yDrag.attachedMesh = mesh;
  88978. this._zDrag.attachedMesh = mesh;
  88979. },
  88980. enumerable: true,
  88981. configurable: true
  88982. });
  88983. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88984. this._xDrag.interactionsEnabled = value;
  88985. this._yDrag.interactionsEnabled = value;
  88986. this._zDrag.interactionsEnabled = value;
  88987. };
  88988. /**
  88989. * Disposes of the gizmo
  88990. */
  88991. RotationGizmo.prototype.dispose = function () {
  88992. this._xDrag.dispose();
  88993. this._yDrag.dispose();
  88994. this._zDrag.dispose();
  88995. };
  88996. return RotationGizmo;
  88997. }(BABYLON.Gizmo));
  88998. BABYLON.RotationGizmo = RotationGizmo;
  88999. })(BABYLON || (BABYLON = {}));
  89000. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89001. var BABYLON;
  89002. (function (BABYLON) {
  89003. /**
  89004. * Gizmo that enables scaling a mesh along 3 axis
  89005. */
  89006. var ScaleGizmo = /** @class */ (function (_super) {
  89007. __extends(ScaleGizmo, _super);
  89008. /**
  89009. * Creates a ScaleGizmo
  89010. * @param gizmoLayer The utility layer the gizmo will be added to
  89011. */
  89012. function ScaleGizmo(gizmoLayer) {
  89013. var _this = _super.call(this, gizmoLayer) || this;
  89014. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  89015. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  89016. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  89017. return _this;
  89018. }
  89019. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89020. set: function (mesh) {
  89021. this._xDrag.attachedMesh = mesh;
  89022. this._yDrag.attachedMesh = mesh;
  89023. this._zDrag.attachedMesh = mesh;
  89024. },
  89025. enumerable: true,
  89026. configurable: true
  89027. });
  89028. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  89029. this._xDrag.interactionsEnabled = value;
  89030. this._yDrag.interactionsEnabled = value;
  89031. this._zDrag.interactionsEnabled = value;
  89032. };
  89033. /**
  89034. * Disposes of the gizmo
  89035. */
  89036. ScaleGizmo.prototype.dispose = function () {
  89037. this._xDrag.dispose();
  89038. this._yDrag.dispose();
  89039. this._zDrag.dispose();
  89040. };
  89041. return ScaleGizmo;
  89042. }(BABYLON.Gizmo));
  89043. BABYLON.ScaleGizmo = ScaleGizmo;
  89044. })(BABYLON || (BABYLON = {}));
  89045. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89046. var BABYLON;
  89047. (function (BABYLON) {
  89048. /**
  89049. * Bounding box gizmo
  89050. */
  89051. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89052. __extends(BoundingBoxGizmo, _super);
  89053. /**
  89054. * Creates an BoundingBoxGizmo
  89055. * @param gizmoLayer The utility layer the gizmo will be added to
  89056. * @param color The color of the gizmo
  89057. */
  89058. function BoundingBoxGizmo(gizmoLayer, color) {
  89059. var _this = _super.call(this, gizmoLayer) || this;
  89060. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89061. _this._renderObserver = null;
  89062. _this._pointerObserver = null;
  89063. _this._scaleDragSpeed = 0.2;
  89064. _this._tmpQuaternion = new BABYLON.Quaternion();
  89065. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89066. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89067. _this._updateScale = false;
  89068. // Create Materials
  89069. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89070. coloredMaterial.disableLighting = true;
  89071. coloredMaterial.emissiveColor = color;
  89072. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89073. hoverColoredMaterial.disableLighting = true;
  89074. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89075. // Build bounding box out of lines
  89076. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89077. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89078. var lines = [];
  89079. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89080. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89081. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89082. 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));
  89083. 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));
  89084. 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));
  89085. 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));
  89086. 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));
  89087. 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));
  89088. 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));
  89089. 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));
  89090. 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));
  89091. lines.forEach(function (l) {
  89092. l.color = color;
  89093. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89094. l.isPickable = false;
  89095. _this._lineBoundingBox.addChild(l);
  89096. });
  89097. _this._rootMesh.addChild(_this._lineBoundingBox);
  89098. // Create rotation spheres
  89099. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89100. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89101. var _loop_1 = function (i_1) {
  89102. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  89103. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89104. sphere.material = coloredMaterial;
  89105. // Drag behavior
  89106. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89107. _dragBehavior.moveAttached = false;
  89108. _dragBehavior.updateDragPlane = false;
  89109. sphere.addBehavior(_dragBehavior);
  89110. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89111. var totalTurnAmountOfDrag = 0;
  89112. _dragBehavior.onDragStartObservable.add(function (event) {
  89113. startingTurnDirection.copyFrom(sphere.forward);
  89114. totalTurnAmountOfDrag = 0;
  89115. });
  89116. _dragBehavior.onDragObservable.add(function (event) {
  89117. if (_this.attachedMesh) {
  89118. var worldDragDirection = startingTurnDirection;
  89119. // Project the world right on to the drag plane
  89120. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89121. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89122. // project drag delta on to the resulting drag axis and rotate based on that
  89123. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89124. // Rotate based on axis
  89125. if (!_this.attachedMesh.rotationQuaternion) {
  89126. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89127. }
  89128. // Do not allow the object to turn more than a full circle
  89129. totalTurnAmountOfDrag += projectDist;
  89130. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89131. if (i_1 >= 8) {
  89132. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89133. }
  89134. else if (i_1 >= 4) {
  89135. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89136. }
  89137. else {
  89138. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89139. }
  89140. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89141. }
  89142. }
  89143. });
  89144. // Selection/deselection
  89145. _dragBehavior.onDragStartObservable.add(function () {
  89146. _this._selectNode(sphere);
  89147. });
  89148. _dragBehavior.onDragEndObservable.add(function () {
  89149. _this._selectNode(null);
  89150. });
  89151. this_1._rotateSpheresParent.addChild(sphere);
  89152. };
  89153. var this_1 = this, _dragBehavior;
  89154. for (var i_1 = 0; i_1 < 12; i_1++) {
  89155. _loop_1(i_1);
  89156. }
  89157. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89158. // Create scale cubes
  89159. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89160. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89161. for (var i = 0; i < 2; i++) {
  89162. for (var j = 0; j < 2; j++) {
  89163. var _loop_2 = function () {
  89164. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  89165. box.material = coloredMaterial;
  89166. // Dragging logic
  89167. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89168. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89169. _dragBehavior.moveAttached = false;
  89170. box.addBehavior(_dragBehavior);
  89171. _dragBehavior.onDragObservable.add(function (event) {
  89172. if (_this.attachedMesh) {
  89173. // Current boudning box dimensions
  89174. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89175. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89176. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89177. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89178. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89179. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89180. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89181. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89182. // Update scale and position
  89183. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89184. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89185. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89186. }
  89187. });
  89188. // Selection/deselection
  89189. _dragBehavior.onDragStartObservable.add(function () {
  89190. _this._selectNode(box);
  89191. });
  89192. _dragBehavior.onDragEndObservable.add(function () {
  89193. _this._selectNode(null);
  89194. });
  89195. this_2._scaleBoxesParent.addChild(box);
  89196. };
  89197. var this_2 = this, _dragBehavior;
  89198. for (var k = 0; k < 2; k++) {
  89199. _loop_2();
  89200. }
  89201. }
  89202. }
  89203. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89204. // Hover color change
  89205. var pointerIds = new Array();
  89206. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89207. if (!pointerIds[pointerInfo.event.pointerId]) {
  89208. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89209. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89210. pointerIds[pointerInfo.event.pointerId] = mesh;
  89211. mesh.material = hoverColoredMaterial;
  89212. }
  89213. });
  89214. }
  89215. else {
  89216. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89217. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89218. delete pointerIds[pointerInfo.event.pointerId];
  89219. }
  89220. }
  89221. });
  89222. // Update bounding box positions
  89223. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89224. _this._updateBoundingBox();
  89225. });
  89226. _this._updateBoundingBox();
  89227. return _this;
  89228. }
  89229. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89230. this._rotateSpheresParent.getChildMeshes()
  89231. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89232. m.isVisible = (!selectedMesh || m == selectedMesh);
  89233. });
  89234. };
  89235. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89236. if (this.attachedMesh) {
  89237. // Update bounding dimensions/positions
  89238. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89239. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89240. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89241. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89242. }
  89243. // Update rotation sphere locations
  89244. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89245. for (var i = 0; i < 3; i++) {
  89246. for (var j = 0; j < 2; j++) {
  89247. for (var k = 0; k < 2; k++) {
  89248. var index = ((i * 4) + (j * 2)) + k;
  89249. if (i == 0) {
  89250. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89251. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89252. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89253. }
  89254. if (i == 1) {
  89255. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89256. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89257. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89258. }
  89259. if (i == 2) {
  89260. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89261. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89262. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89263. }
  89264. }
  89265. }
  89266. }
  89267. // Update scale box locations
  89268. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89269. for (var i = 0; i < 2; i++) {
  89270. for (var j = 0; j < 2; j++) {
  89271. for (var k = 0; k < 2; k++) {
  89272. var index = ((i * 4) + (j * 2)) + k;
  89273. if (scaleBoxes[index]) {
  89274. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89275. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89276. }
  89277. }
  89278. }
  89279. }
  89280. };
  89281. /**
  89282. * Disposes of the gizmo
  89283. */
  89284. BoundingBoxGizmo.prototype.dispose = function () {
  89285. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89286. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89287. this._lineBoundingBox.dispose();
  89288. this._rotateSpheresParent.dispose();
  89289. this._scaleBoxesParent.dispose();
  89290. _super.prototype.dispose.call(this);
  89291. };
  89292. return BoundingBoxGizmo;
  89293. }(BABYLON.Gizmo));
  89294. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89295. })(BABYLON || (BABYLON = {}));
  89296. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89297. var BABYLON;
  89298. (function (BABYLON) {
  89299. /**
  89300. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89301. */
  89302. var GizmoManager = /** @class */ (function () {
  89303. /**
  89304. * Instatiates a gizmo manager
  89305. * @param scene the scene to overlay the gizmos on top of
  89306. * @param options If only a single gizmo should exist at one time
  89307. */
  89308. function GizmoManager(scene, options) {
  89309. var _this = this;
  89310. this.scene = scene;
  89311. // Set of gizmos that are currently in the scene for each mesh
  89312. this._gizmoSet = {};
  89313. this._pointerObserver = null;
  89314. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89315. // Options parsing
  89316. if (!options) {
  89317. options = {};
  89318. }
  89319. if (options.singleGizmo === undefined) {
  89320. options.singleGizmo = true;
  89321. }
  89322. // Instatiate/dispose gizmos based on pointer actions
  89323. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89324. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89325. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89326. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89327. if (options.singleGizmo) {
  89328. _this._clearGizmos();
  89329. }
  89330. // Enable gizmo when mesh is selected
  89331. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89332. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89333. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89334. }
  89335. else {
  89336. if (!options.singleGizmo) {
  89337. // Disable gizmo when clicked again
  89338. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89339. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89340. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89341. }
  89342. }
  89343. }
  89344. else {
  89345. if (options.singleGizmo) {
  89346. // Disable gizmo when clicked away
  89347. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89348. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89349. if (gizmoPick && !gizmoPick.hit) {
  89350. _this._clearGizmos();
  89351. }
  89352. }
  89353. }
  89354. }
  89355. }
  89356. });
  89357. }
  89358. /**
  89359. * Disposes of the gizmo manager
  89360. */
  89361. GizmoManager.prototype.dispose = function () {
  89362. this.scene.onPointerObservable.remove(this._pointerObserver);
  89363. this._clearGizmos();
  89364. this._gizmoLayer.dispose();
  89365. };
  89366. GizmoManager.prototype._clearGizmos = function () {
  89367. for (var key in this._gizmoSet) {
  89368. if (this._gizmoSet.hasOwnProperty(key)) {
  89369. this._gizmoSet[key].positionGizmo.dispose();
  89370. this._gizmoSet[key].rotationGizmo.dispose();
  89371. delete this._gizmoSet[key];
  89372. }
  89373. }
  89374. };
  89375. return GizmoManager;
  89376. }());
  89377. BABYLON.GizmoManager = GizmoManager;
  89378. })(BABYLON || (BABYLON = {}));
  89379. //# sourceMappingURL=babylon.gizmoManager.js.map
  89380. var BABYLON;
  89381. (function (BABYLON) {
  89382. /**
  89383. * Defines a target to use with MorphTargetManager
  89384. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89385. */
  89386. var MorphTarget = /** @class */ (function () {
  89387. /**
  89388. * Creates a new MorphTarget
  89389. * @param name defines the name of the target
  89390. * @param influence defines the influence to use
  89391. */
  89392. function MorphTarget(
  89393. /** defines the name of the target */
  89394. name, influence, scene) {
  89395. if (influence === void 0) { influence = 0; }
  89396. if (scene === void 0) { scene = null; }
  89397. this.name = name;
  89398. /**
  89399. * Gets or sets the list of animations
  89400. */
  89401. this.animations = new Array();
  89402. this._positions = null;
  89403. this._normals = null;
  89404. this._tangents = null;
  89405. /**
  89406. * Observable raised when the influence changes
  89407. */
  89408. this.onInfluenceChanged = new BABYLON.Observable();
  89409. this._animationPropertiesOverride = null;
  89410. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89411. this.influence = influence;
  89412. }
  89413. Object.defineProperty(MorphTarget.prototype, "influence", {
  89414. /**
  89415. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  89416. */
  89417. get: function () {
  89418. return this._influence;
  89419. },
  89420. set: function (influence) {
  89421. if (this._influence === influence) {
  89422. return;
  89423. }
  89424. var previous = this._influence;
  89425. this._influence = influence;
  89426. if (this.onInfluenceChanged.hasObservers) {
  89427. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  89428. }
  89429. },
  89430. enumerable: true,
  89431. configurable: true
  89432. });
  89433. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  89434. /**
  89435. * Gets or sets the animation properties override
  89436. */
  89437. get: function () {
  89438. if (!this._animationPropertiesOverride && this._scene) {
  89439. return this._scene.animationPropertiesOverride;
  89440. }
  89441. return this._animationPropertiesOverride;
  89442. },
  89443. set: function (value) {
  89444. this._animationPropertiesOverride = value;
  89445. },
  89446. enumerable: true,
  89447. configurable: true
  89448. });
  89449. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  89450. /**
  89451. * Gets a boolean defining if the target contains position data
  89452. */
  89453. get: function () {
  89454. return !!this._positions;
  89455. },
  89456. enumerable: true,
  89457. configurable: true
  89458. });
  89459. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  89460. /**
  89461. * Gets a boolean defining if the target contains normal data
  89462. */
  89463. get: function () {
  89464. return !!this._normals;
  89465. },
  89466. enumerable: true,
  89467. configurable: true
  89468. });
  89469. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  89470. /**
  89471. * Gets a boolean defining if the target contains tangent data
  89472. */
  89473. get: function () {
  89474. return !!this._tangents;
  89475. },
  89476. enumerable: true,
  89477. configurable: true
  89478. });
  89479. /**
  89480. * Affects position data to this target
  89481. * @param data defines the position data to use
  89482. */
  89483. MorphTarget.prototype.setPositions = function (data) {
  89484. this._positions = data;
  89485. };
  89486. /**
  89487. * Gets the position data stored in this target
  89488. * @returns a FloatArray containing the position data (or null if not present)
  89489. */
  89490. MorphTarget.prototype.getPositions = function () {
  89491. return this._positions;
  89492. };
  89493. /**
  89494. * Affects normal data to this target
  89495. * @param data defines the normal data to use
  89496. */
  89497. MorphTarget.prototype.setNormals = function (data) {
  89498. this._normals = data;
  89499. };
  89500. /**
  89501. * Gets the normal data stored in this target
  89502. * @returns a FloatArray containing the normal data (or null if not present)
  89503. */
  89504. MorphTarget.prototype.getNormals = function () {
  89505. return this._normals;
  89506. };
  89507. /**
  89508. * Affects tangent data to this target
  89509. * @param data defines the tangent data to use
  89510. */
  89511. MorphTarget.prototype.setTangents = function (data) {
  89512. this._tangents = data;
  89513. };
  89514. /**
  89515. * Gets the tangent data stored in this target
  89516. * @returns a FloatArray containing the tangent data (or null if not present)
  89517. */
  89518. MorphTarget.prototype.getTangents = function () {
  89519. return this._tangents;
  89520. };
  89521. /**
  89522. * Serializes the current target into a Serialization object
  89523. * @returns the serialized object
  89524. */
  89525. MorphTarget.prototype.serialize = function () {
  89526. var serializationObject = {};
  89527. serializationObject.name = this.name;
  89528. serializationObject.influence = this.influence;
  89529. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  89530. if (this.hasNormals) {
  89531. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  89532. }
  89533. if (this.hasTangents) {
  89534. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  89535. }
  89536. // Animations
  89537. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  89538. return serializationObject;
  89539. };
  89540. // Statics
  89541. /**
  89542. * Creates a new target from serialized data
  89543. * @param serializationObject defines the serialized data to use
  89544. * @returns a new MorphTarget
  89545. */
  89546. MorphTarget.Parse = function (serializationObject) {
  89547. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  89548. result.setPositions(serializationObject.positions);
  89549. if (serializationObject.normals) {
  89550. result.setNormals(serializationObject.normals);
  89551. }
  89552. if (serializationObject.tangents) {
  89553. result.setTangents(serializationObject.tangents);
  89554. }
  89555. // Animations
  89556. if (serializationObject.animations) {
  89557. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  89558. var parsedAnimation = serializationObject.animations[animationIndex];
  89559. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  89560. }
  89561. }
  89562. return result;
  89563. };
  89564. /**
  89565. * Creates a MorphTarget from mesh data
  89566. * @param mesh defines the source mesh
  89567. * @param name defines the name to use for the new target
  89568. * @param influence defines the influence to attach to the target
  89569. * @returns a new MorphTarget
  89570. */
  89571. MorphTarget.FromMesh = function (mesh, name, influence) {
  89572. if (!name) {
  89573. name = mesh.name;
  89574. }
  89575. var result = new MorphTarget(name, influence, mesh.getScene());
  89576. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89577. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89578. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  89579. }
  89580. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  89581. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  89582. }
  89583. return result;
  89584. };
  89585. return MorphTarget;
  89586. }());
  89587. BABYLON.MorphTarget = MorphTarget;
  89588. })(BABYLON || (BABYLON = {}));
  89589. //# sourceMappingURL=babylon.morphTarget.js.map
  89590. var BABYLON;
  89591. (function (BABYLON) {
  89592. /**
  89593. * This class is used to deform meshes using morphing between different targets
  89594. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89595. */
  89596. var MorphTargetManager = /** @class */ (function () {
  89597. /**
  89598. * Creates a new MorphTargetManager
  89599. * @param scene defines the current scene
  89600. */
  89601. function MorphTargetManager(scene) {
  89602. if (scene === void 0) { scene = null; }
  89603. this._targets = new Array();
  89604. this._targetObservable = new Array();
  89605. this._activeTargets = new BABYLON.SmartArray(16);
  89606. this._supportsNormals = false;
  89607. this._supportsTangents = false;
  89608. this._vertexCount = 0;
  89609. this._uniqueId = 0;
  89610. this._tempInfluences = new Array();
  89611. if (!scene) {
  89612. scene = BABYLON.Engine.LastCreatedScene;
  89613. }
  89614. this._scene = scene;
  89615. if (this._scene) {
  89616. this._scene.morphTargetManagers.push(this);
  89617. this._uniqueId = this._scene.getUniqueId();
  89618. }
  89619. }
  89620. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  89621. /**
  89622. * Gets the unique ID of this manager
  89623. */
  89624. get: function () {
  89625. return this._uniqueId;
  89626. },
  89627. enumerable: true,
  89628. configurable: true
  89629. });
  89630. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  89631. /**
  89632. * Gets the number of vertices handled by this manager
  89633. */
  89634. get: function () {
  89635. return this._vertexCount;
  89636. },
  89637. enumerable: true,
  89638. configurable: true
  89639. });
  89640. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  89641. /**
  89642. * Gets a boolean indicating if this manager supports morphing of normals
  89643. */
  89644. get: function () {
  89645. return this._supportsNormals;
  89646. },
  89647. enumerable: true,
  89648. configurable: true
  89649. });
  89650. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  89651. /**
  89652. * Gets a boolean indicating if this manager supports morphing of tangents
  89653. */
  89654. get: function () {
  89655. return this._supportsTangents;
  89656. },
  89657. enumerable: true,
  89658. configurable: true
  89659. });
  89660. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  89661. /**
  89662. * Gets the number of targets stored in this manager
  89663. */
  89664. get: function () {
  89665. return this._targets.length;
  89666. },
  89667. enumerable: true,
  89668. configurable: true
  89669. });
  89670. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  89671. /**
  89672. * Gets the number of influencers (ie. the number of targets with influences > 0)
  89673. */
  89674. get: function () {
  89675. return this._activeTargets.length;
  89676. },
  89677. enumerable: true,
  89678. configurable: true
  89679. });
  89680. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  89681. /**
  89682. * Gets the list of influences (one per target)
  89683. */
  89684. get: function () {
  89685. return this._influences;
  89686. },
  89687. enumerable: true,
  89688. configurable: true
  89689. });
  89690. /**
  89691. * Gets the active target at specified index. An active target is a target with an influence > 0
  89692. * @param index defines the index to check
  89693. * @returns the requested target
  89694. */
  89695. MorphTargetManager.prototype.getActiveTarget = function (index) {
  89696. return this._activeTargets.data[index];
  89697. };
  89698. /**
  89699. * Gets the target at specified index
  89700. * @param index defines the index to check
  89701. * @returns the requested target
  89702. */
  89703. MorphTargetManager.prototype.getTarget = function (index) {
  89704. return this._targets[index];
  89705. };
  89706. /**
  89707. * Add a new target to this manager
  89708. * @param target defines the target to add
  89709. */
  89710. MorphTargetManager.prototype.addTarget = function (target) {
  89711. var _this = this;
  89712. this._targets.push(target);
  89713. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  89714. _this._syncActiveTargets(needUpdate);
  89715. }));
  89716. this._syncActiveTargets(true);
  89717. };
  89718. /**
  89719. * Removes a target from the manager
  89720. * @param target defines the target to remove
  89721. */
  89722. MorphTargetManager.prototype.removeTarget = function (target) {
  89723. var index = this._targets.indexOf(target);
  89724. if (index >= 0) {
  89725. this._targets.splice(index, 1);
  89726. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  89727. this._syncActiveTargets(true);
  89728. }
  89729. };
  89730. /**
  89731. * Serializes the current manager into a Serialization object
  89732. * @returns the serialized object
  89733. */
  89734. MorphTargetManager.prototype.serialize = function () {
  89735. var serializationObject = {};
  89736. serializationObject.id = this.uniqueId;
  89737. serializationObject.targets = [];
  89738. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89739. var target = _a[_i];
  89740. serializationObject.targets.push(target.serialize());
  89741. }
  89742. return serializationObject;
  89743. };
  89744. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  89745. var influenceCount = 0;
  89746. this._activeTargets.reset();
  89747. this._supportsNormals = true;
  89748. this._supportsTangents = true;
  89749. this._vertexCount = 0;
  89750. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89751. var target = _a[_i];
  89752. this._activeTargets.push(target);
  89753. this._tempInfluences[influenceCount++] = target.influence;
  89754. var positions = target.getPositions();
  89755. if (positions) {
  89756. this._supportsNormals = this._supportsNormals && target.hasNormals;
  89757. this._supportsTangents = this._supportsTangents && target.hasTangents;
  89758. var vertexCount = positions.length / 3;
  89759. if (this._vertexCount === 0) {
  89760. this._vertexCount = vertexCount;
  89761. }
  89762. else if (this._vertexCount !== vertexCount) {
  89763. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  89764. return;
  89765. }
  89766. }
  89767. }
  89768. if (!this._influences || this._influences.length !== influenceCount) {
  89769. this._influences = new Float32Array(influenceCount);
  89770. }
  89771. for (var index = 0; index < influenceCount; index++) {
  89772. this._influences[index] = this._tempInfluences[index];
  89773. }
  89774. if (needUpdate) {
  89775. this.synchronize();
  89776. }
  89777. };
  89778. /**
  89779. * Syncrhonize the targets with all the meshes using this morph target manager
  89780. */
  89781. MorphTargetManager.prototype.synchronize = function () {
  89782. if (!this._scene) {
  89783. return;
  89784. }
  89785. // Flag meshes as dirty to resync with the active targets
  89786. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  89787. var mesh = _a[_i];
  89788. if (mesh.morphTargetManager === this) {
  89789. mesh._syncGeometryWithMorphTargetManager();
  89790. }
  89791. }
  89792. };
  89793. // Statics
  89794. /**
  89795. * Creates a new MorphTargetManager from serialized data
  89796. * @param serializationObject defines the serialized data
  89797. * @param scene defines the hosting scene
  89798. * @returns the new MorphTargetManager
  89799. */
  89800. MorphTargetManager.Parse = function (serializationObject, scene) {
  89801. var result = new MorphTargetManager(scene);
  89802. result._uniqueId = serializationObject.id;
  89803. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  89804. var targetData = _a[_i];
  89805. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  89806. }
  89807. return result;
  89808. };
  89809. return MorphTargetManager;
  89810. }());
  89811. BABYLON.MorphTargetManager = MorphTargetManager;
  89812. })(BABYLON || (BABYLON = {}));
  89813. //# sourceMappingURL=babylon.morphTargetManager.js.map
  89814. var BABYLON;
  89815. (function (BABYLON) {
  89816. var Octree = /** @class */ (function () {
  89817. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  89818. if (maxDepth === void 0) { maxDepth = 2; }
  89819. this.maxDepth = maxDepth;
  89820. this.dynamicContent = new Array();
  89821. this._maxBlockCapacity = maxBlockCapacity || 64;
  89822. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  89823. this._creationFunc = creationFunc;
  89824. }
  89825. // Methods
  89826. Octree.prototype.update = function (worldMin, worldMax, entries) {
  89827. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  89828. };
  89829. Octree.prototype.addMesh = function (entry) {
  89830. for (var index = 0; index < this.blocks.length; index++) {
  89831. var block = this.blocks[index];
  89832. block.addEntry(entry);
  89833. }
  89834. };
  89835. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  89836. this._selectionContent.reset();
  89837. for (var index = 0; index < this.blocks.length; index++) {
  89838. var block = this.blocks[index];
  89839. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  89840. }
  89841. if (allowDuplicate) {
  89842. this._selectionContent.concat(this.dynamicContent);
  89843. }
  89844. else {
  89845. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89846. }
  89847. return this._selectionContent;
  89848. };
  89849. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  89850. this._selectionContent.reset();
  89851. for (var index = 0; index < this.blocks.length; index++) {
  89852. var block = this.blocks[index];
  89853. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  89854. }
  89855. if (allowDuplicate) {
  89856. this._selectionContent.concat(this.dynamicContent);
  89857. }
  89858. else {
  89859. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89860. }
  89861. return this._selectionContent;
  89862. };
  89863. Octree.prototype.intersectsRay = function (ray) {
  89864. this._selectionContent.reset();
  89865. for (var index = 0; index < this.blocks.length; index++) {
  89866. var block = this.blocks[index];
  89867. block.intersectsRay(ray, this._selectionContent);
  89868. }
  89869. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89870. return this._selectionContent;
  89871. };
  89872. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  89873. target.blocks = new Array();
  89874. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  89875. // Segmenting space
  89876. for (var x = 0; x < 2; x++) {
  89877. for (var y = 0; y < 2; y++) {
  89878. for (var z = 0; z < 2; z++) {
  89879. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  89880. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  89881. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  89882. block.addEntries(entries);
  89883. target.blocks.push(block);
  89884. }
  89885. }
  89886. }
  89887. };
  89888. Octree.CreationFuncForMeshes = function (entry, block) {
  89889. var boundingInfo = entry.getBoundingInfo();
  89890. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89891. block.entries.push(entry);
  89892. }
  89893. };
  89894. Octree.CreationFuncForSubMeshes = function (entry, block) {
  89895. var boundingInfo = entry.getBoundingInfo();
  89896. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89897. block.entries.push(entry);
  89898. }
  89899. };
  89900. return Octree;
  89901. }());
  89902. BABYLON.Octree = Octree;
  89903. })(BABYLON || (BABYLON = {}));
  89904. //# sourceMappingURL=babylon.octree.js.map
  89905. var BABYLON;
  89906. (function (BABYLON) {
  89907. var OctreeBlock = /** @class */ (function () {
  89908. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  89909. this.entries = new Array();
  89910. this._boundingVectors = new Array();
  89911. this._capacity = capacity;
  89912. this._depth = depth;
  89913. this._maxDepth = maxDepth;
  89914. this._creationFunc = creationFunc;
  89915. this._minPoint = minPoint;
  89916. this._maxPoint = maxPoint;
  89917. this._boundingVectors.push(minPoint.clone());
  89918. this._boundingVectors.push(maxPoint.clone());
  89919. this._boundingVectors.push(minPoint.clone());
  89920. this._boundingVectors[2].x = maxPoint.x;
  89921. this._boundingVectors.push(minPoint.clone());
  89922. this._boundingVectors[3].y = maxPoint.y;
  89923. this._boundingVectors.push(minPoint.clone());
  89924. this._boundingVectors[4].z = maxPoint.z;
  89925. this._boundingVectors.push(maxPoint.clone());
  89926. this._boundingVectors[5].z = minPoint.z;
  89927. this._boundingVectors.push(maxPoint.clone());
  89928. this._boundingVectors[6].x = minPoint.x;
  89929. this._boundingVectors.push(maxPoint.clone());
  89930. this._boundingVectors[7].y = minPoint.y;
  89931. }
  89932. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  89933. // Property
  89934. get: function () {
  89935. return this._capacity;
  89936. },
  89937. enumerable: true,
  89938. configurable: true
  89939. });
  89940. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  89941. get: function () {
  89942. return this._minPoint;
  89943. },
  89944. enumerable: true,
  89945. configurable: true
  89946. });
  89947. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  89948. get: function () {
  89949. return this._maxPoint;
  89950. },
  89951. enumerable: true,
  89952. configurable: true
  89953. });
  89954. // Methods
  89955. OctreeBlock.prototype.addEntry = function (entry) {
  89956. if (this.blocks) {
  89957. for (var index = 0; index < this.blocks.length; index++) {
  89958. var block = this.blocks[index];
  89959. block.addEntry(entry);
  89960. }
  89961. return;
  89962. }
  89963. this._creationFunc(entry, this);
  89964. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  89965. this.createInnerBlocks();
  89966. }
  89967. };
  89968. OctreeBlock.prototype.addEntries = function (entries) {
  89969. for (var index = 0; index < entries.length; index++) {
  89970. var mesh = entries[index];
  89971. this.addEntry(mesh);
  89972. }
  89973. };
  89974. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  89975. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  89976. if (this.blocks) {
  89977. for (var index = 0; index < this.blocks.length; index++) {
  89978. var block = this.blocks[index];
  89979. block.select(frustumPlanes, selection, allowDuplicate);
  89980. }
  89981. return;
  89982. }
  89983. if (allowDuplicate) {
  89984. selection.concat(this.entries);
  89985. }
  89986. else {
  89987. selection.concatWithNoDuplicate(this.entries);
  89988. }
  89989. }
  89990. };
  89991. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  89992. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  89993. if (this.blocks) {
  89994. for (var index = 0; index < this.blocks.length; index++) {
  89995. var block = this.blocks[index];
  89996. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  89997. }
  89998. return;
  89999. }
  90000. if (allowDuplicate) {
  90001. selection.concat(this.entries);
  90002. }
  90003. else {
  90004. selection.concatWithNoDuplicate(this.entries);
  90005. }
  90006. }
  90007. };
  90008. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90009. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90010. if (this.blocks) {
  90011. for (var index = 0; index < this.blocks.length; index++) {
  90012. var block = this.blocks[index];
  90013. block.intersectsRay(ray, selection);
  90014. }
  90015. return;
  90016. }
  90017. selection.concatWithNoDuplicate(this.entries);
  90018. }
  90019. };
  90020. OctreeBlock.prototype.createInnerBlocks = function () {
  90021. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90022. };
  90023. return OctreeBlock;
  90024. }());
  90025. BABYLON.OctreeBlock = OctreeBlock;
  90026. })(BABYLON || (BABYLON = {}));
  90027. //# sourceMappingURL=babylon.octreeBlock.js.map
  90028. var BABYLON;
  90029. (function (BABYLON) {
  90030. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90031. __extends(VRDistortionCorrectionPostProcess, _super);
  90032. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90033. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90034. 'LensCenter',
  90035. 'Scale',
  90036. 'ScaleIn',
  90037. 'HmdWarpParam'
  90038. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90039. _this._isRightEye = isRightEye;
  90040. _this._distortionFactors = vrMetrics.distortionK;
  90041. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90042. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90043. _this.adaptScaleToCurrentViewport = true;
  90044. _this.onSizeChangedObservable.add(function () {
  90045. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90046. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90047. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90048. });
  90049. _this.onApplyObservable.add(function (effect) {
  90050. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90051. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90052. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90053. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90054. });
  90055. return _this;
  90056. }
  90057. return VRDistortionCorrectionPostProcess;
  90058. }(BABYLON.PostProcess));
  90059. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90060. })(BABYLON || (BABYLON = {}));
  90061. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90062. var BABYLON;
  90063. (function (BABYLON) {
  90064. /**
  90065. * Postprocess used to generate anaglyphic rendering
  90066. */
  90067. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90068. __extends(AnaglyphPostProcess, _super);
  90069. /**
  90070. * Creates a new AnaglyphPostProcess
  90071. * @param name defines postprocess name
  90072. * @param options defines creation options or target ratio scale
  90073. * @param rigCameras defines cameras using this postprocess
  90074. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90075. * @param engine defines hosting engine
  90076. * @param reusable defines if the postprocess will be reused multiple times per frame
  90077. */
  90078. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90079. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90080. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90081. _this.onApplyObservable.add(function (effect) {
  90082. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90083. });
  90084. return _this;
  90085. }
  90086. return AnaglyphPostProcess;
  90087. }(BABYLON.PostProcess));
  90088. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90089. })(BABYLON || (BABYLON = {}));
  90090. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90091. var BABYLON;
  90092. (function (BABYLON) {
  90093. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90094. __extends(StereoscopicInterlacePostProcess, _super);
  90095. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90096. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90097. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90098. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90099. _this.onSizeChangedObservable.add(function () {
  90100. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90101. });
  90102. _this.onApplyObservable.add(function (effect) {
  90103. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90104. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90105. });
  90106. return _this;
  90107. }
  90108. return StereoscopicInterlacePostProcess;
  90109. }(BABYLON.PostProcess));
  90110. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90111. })(BABYLON || (BABYLON = {}));
  90112. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90113. var BABYLON;
  90114. (function (BABYLON) {
  90115. /**
  90116. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90117. * Screen rotation is taken into account.
  90118. */
  90119. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90120. function FreeCameraDeviceOrientationInput() {
  90121. var _this = this;
  90122. this._screenOrientationAngle = 0;
  90123. this._screenQuaternion = new BABYLON.Quaternion();
  90124. this._alpha = 0;
  90125. this._beta = 0;
  90126. this._gamma = 0;
  90127. this._orientationChanged = function () {
  90128. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90129. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90130. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90131. };
  90132. this._deviceOrientation = function (evt) {
  90133. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90134. _this._beta = evt.beta !== null ? evt.beta : 0;
  90135. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90136. };
  90137. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  90138. this._orientationChanged();
  90139. }
  90140. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  90141. get: function () {
  90142. return this._camera;
  90143. },
  90144. set: function (camera) {
  90145. this._camera = camera;
  90146. if (this._camera != null && !this._camera.rotationQuaternion) {
  90147. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90148. }
  90149. },
  90150. enumerable: true,
  90151. configurable: true
  90152. });
  90153. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90154. window.addEventListener("orientationchange", this._orientationChanged);
  90155. window.addEventListener("deviceorientation", this._deviceOrientation);
  90156. //In certain cases, the attach control is called AFTER orientation was changed,
  90157. //So this is needed.
  90158. this._orientationChanged();
  90159. };
  90160. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90161. window.removeEventListener("orientationchange", this._orientationChanged);
  90162. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90163. };
  90164. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90165. //if no device orientation provided, don't update the rotation.
  90166. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90167. if (!this._alpha)
  90168. return;
  90169. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90170. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90171. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90172. //Mirror on XY Plane
  90173. this._camera.rotationQuaternion.z *= -1;
  90174. this._camera.rotationQuaternion.w *= -1;
  90175. };
  90176. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90177. return "FreeCameraDeviceOrientationInput";
  90178. };
  90179. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90180. return "deviceOrientation";
  90181. };
  90182. return FreeCameraDeviceOrientationInput;
  90183. }());
  90184. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90185. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90186. })(BABYLON || (BABYLON = {}));
  90187. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90188. var BABYLON;
  90189. (function (BABYLON) {
  90190. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90191. function ArcRotateCameraVRDeviceOrientationInput() {
  90192. this.alphaCorrection = 1;
  90193. this.betaCorrection = 1;
  90194. this.gammaCorrection = 1;
  90195. this._alpha = 0;
  90196. this._gamma = 0;
  90197. this._dirty = false;
  90198. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90199. }
  90200. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90201. this.camera.attachControl(element, noPreventDefault);
  90202. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90203. };
  90204. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90205. if (evt.alpha !== null) {
  90206. this._alpha = +evt.alpha | 0;
  90207. }
  90208. if (evt.gamma !== null) {
  90209. this._gamma = +evt.gamma | 0;
  90210. }
  90211. this._dirty = true;
  90212. };
  90213. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90214. if (this._dirty) {
  90215. this._dirty = false;
  90216. if (this._gamma < 0) {
  90217. this._gamma = 180 + this._gamma;
  90218. }
  90219. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90220. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90221. }
  90222. };
  90223. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90224. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90225. };
  90226. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90227. return "ArcRotateCameraVRDeviceOrientationInput";
  90228. };
  90229. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90230. return "VRDeviceOrientation";
  90231. };
  90232. return ArcRotateCameraVRDeviceOrientationInput;
  90233. }());
  90234. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90235. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90236. })(BABYLON || (BABYLON = {}));
  90237. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90238. var BABYLON;
  90239. (function (BABYLON) {
  90240. var VRCameraMetrics = /** @class */ (function () {
  90241. function VRCameraMetrics() {
  90242. this.compensateDistortion = true;
  90243. }
  90244. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90245. get: function () {
  90246. return this.hResolution / (2 * this.vResolution);
  90247. },
  90248. enumerable: true,
  90249. configurable: true
  90250. });
  90251. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90252. get: function () {
  90253. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90254. },
  90255. enumerable: true,
  90256. configurable: true
  90257. });
  90258. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90259. get: function () {
  90260. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90261. var h = (4 * meters) / this.hScreenSize;
  90262. return BABYLON.Matrix.Translation(h, 0, 0);
  90263. },
  90264. enumerable: true,
  90265. configurable: true
  90266. });
  90267. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90268. get: function () {
  90269. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90270. var h = (4 * meters) / this.hScreenSize;
  90271. return BABYLON.Matrix.Translation(-h, 0, 0);
  90272. },
  90273. enumerable: true,
  90274. configurable: true
  90275. });
  90276. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90277. get: function () {
  90278. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90279. },
  90280. enumerable: true,
  90281. configurable: true
  90282. });
  90283. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90284. get: function () {
  90285. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90286. },
  90287. enumerable: true,
  90288. configurable: true
  90289. });
  90290. VRCameraMetrics.GetDefault = function () {
  90291. var result = new VRCameraMetrics();
  90292. result.hResolution = 1280;
  90293. result.vResolution = 800;
  90294. result.hScreenSize = 0.149759993;
  90295. result.vScreenSize = 0.0935999975;
  90296. result.vScreenCenter = 0.0467999987;
  90297. result.eyeToScreenDistance = 0.0410000011;
  90298. result.lensSeparationDistance = 0.0635000020;
  90299. result.interpupillaryDistance = 0.0640000030;
  90300. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90301. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90302. result.postProcessScaleFactor = 1.714605507808412;
  90303. result.lensCenterOffset = 0.151976421;
  90304. return result;
  90305. };
  90306. return VRCameraMetrics;
  90307. }());
  90308. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90309. })(BABYLON || (BABYLON = {}));
  90310. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90311. var BABYLON;
  90312. (function (BABYLON) {
  90313. /**
  90314. * This represents a WebVR camera.
  90315. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90316. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90317. */
  90318. var WebVRFreeCamera = /** @class */ (function (_super) {
  90319. __extends(WebVRFreeCamera, _super);
  90320. /**
  90321. * Instantiates a WebVRFreeCamera.
  90322. * @param name The name of the WebVRFreeCamera
  90323. * @param position The starting anchor position for the camera
  90324. * @param scene The scene the camera belongs to
  90325. * @param webVROptions a set of customizable options for the webVRCamera
  90326. */
  90327. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90328. if (webVROptions === void 0) { webVROptions = {}; }
  90329. var _this = _super.call(this, name, position, scene) || this;
  90330. _this.webVROptions = webVROptions;
  90331. /**
  90332. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90333. */
  90334. _this._vrDevice = null;
  90335. /**
  90336. * The rawPose of the vrDevice.
  90337. */
  90338. _this.rawPose = null;
  90339. _this._specsVersion = "1.1";
  90340. _this._attached = false;
  90341. _this._descendants = [];
  90342. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90343. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90344. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90345. _this._standingMatrix = null;
  90346. /**
  90347. * Represents device position in babylon space.
  90348. */
  90349. _this.devicePosition = BABYLON.Vector3.Zero();
  90350. /**
  90351. * Represents device rotation in babylon space.
  90352. */
  90353. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90354. /**
  90355. * The scale of the device to be used when translating from device space to babylon space.
  90356. */
  90357. _this.deviceScaleFactor = 1;
  90358. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90359. _this._worldToDevice = BABYLON.Matrix.Identity();
  90360. /**
  90361. * References to the webVR controllers for the vrDevice.
  90362. */
  90363. _this.controllers = [];
  90364. /**
  90365. * Emits an event when a controller is attached.
  90366. */
  90367. _this.onControllersAttachedObservable = new BABYLON.Observable();
  90368. /**
  90369. * Emits an event when a controller's mesh has been loaded;
  90370. */
  90371. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90372. /**
  90373. * If the rig cameras be used as parent instead of this camera.
  90374. */
  90375. _this.rigParenting = true;
  90376. _this._defaultHeight = undefined;
  90377. _this._workingVector = BABYLON.Vector3.Zero();
  90378. _this._oneVector = BABYLON.Vector3.One();
  90379. _this._workingMatrix = BABYLON.Matrix.Identity();
  90380. _this._cache.position = BABYLON.Vector3.Zero();
  90381. if (webVROptions.defaultHeight) {
  90382. _this._defaultHeight = webVROptions.defaultHeight;
  90383. _this.position.y = _this._defaultHeight;
  90384. }
  90385. _this.minZ = 0.1;
  90386. //legacy support - the compensation boolean was removed.
  90387. if (arguments.length === 5) {
  90388. _this.webVROptions = arguments[4];
  90389. }
  90390. // default webVR options
  90391. if (_this.webVROptions.trackPosition == undefined) {
  90392. _this.webVROptions.trackPosition = true;
  90393. }
  90394. if (_this.webVROptions.controllerMeshes == undefined) {
  90395. _this.webVROptions.controllerMeshes = true;
  90396. }
  90397. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  90398. _this.webVROptions.defaultLightingOnControllers = true;
  90399. }
  90400. _this.rotationQuaternion = new BABYLON.Quaternion();
  90401. if (_this.webVROptions && _this.webVROptions.positionScale) {
  90402. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  90403. }
  90404. //enable VR
  90405. var engine = _this.getEngine();
  90406. _this._onVREnabled = function (success) { if (success) {
  90407. _this.initControllers();
  90408. } };
  90409. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  90410. engine.initWebVR().add(function (event) {
  90411. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  90412. return;
  90413. }
  90414. _this._vrDevice = event.vrDisplay;
  90415. //reset the rig parameters.
  90416. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  90417. if (_this._attached) {
  90418. _this.getEngine().enableVR();
  90419. }
  90420. });
  90421. if (typeof (VRFrameData) !== "undefined")
  90422. _this._frameData = new VRFrameData();
  90423. /**
  90424. * The idea behind the following lines:
  90425. * objects that have the camera as parent should actually have the rig cameras as a parent.
  90426. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  90427. * the second will not show it correctly.
  90428. *
  90429. * To solve this - each object that has the camera as parent will be added to a protected array.
  90430. * When the rig camera renders, it will take this array and set all of those to be its children.
  90431. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  90432. * Amazing!
  90433. */
  90434. scene.onBeforeCameraRenderObservable.add(function (camera) {
  90435. if (camera.parent === _this && _this.rigParenting) {
  90436. _this._descendants = _this.getDescendants(true, function (n) {
  90437. // don't take the cameras or the controllers!
  90438. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  90439. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  90440. return !isController && !isRigCamera;
  90441. });
  90442. _this._descendants.forEach(function (node) {
  90443. node.parent = camera;
  90444. });
  90445. }
  90446. });
  90447. scene.onAfterCameraRenderObservable.add(function (camera) {
  90448. if (camera.parent === _this && _this.rigParenting) {
  90449. _this._descendants.forEach(function (node) {
  90450. node.parent = _this;
  90451. });
  90452. }
  90453. });
  90454. return _this;
  90455. }
  90456. /**
  90457. * Gets the device distance from the ground in meters.
  90458. * @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.
  90459. */
  90460. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  90461. if (this._standingMatrix) {
  90462. // Add standing matrix offset to get real offset from ground in room
  90463. this._standingMatrix.getTranslationToRef(this._workingVector);
  90464. return this._deviceRoomPosition.y + this._workingVector.y;
  90465. }
  90466. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  90467. return this._defaultHeight || 0;
  90468. };
  90469. /**
  90470. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90471. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  90472. */
  90473. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  90474. var _this = this;
  90475. if (callback === void 0) { callback = function (bool) { }; }
  90476. // Use standing matrix if available
  90477. this.getEngine().initWebVRAsync().then(function (result) {
  90478. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  90479. callback(false);
  90480. }
  90481. else {
  90482. _this._standingMatrix = new BABYLON.Matrix();
  90483. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  90484. if (!_this.getScene().useRightHandedSystem) {
  90485. [2, 6, 8, 9, 14].forEach(function (num) {
  90486. if (_this._standingMatrix) {
  90487. _this._standingMatrix.m[num] *= -1;
  90488. }
  90489. });
  90490. }
  90491. callback(true);
  90492. }
  90493. });
  90494. };
  90495. /**
  90496. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90497. * @returns A promise with a boolean set to if the standing matrix is supported.
  90498. */
  90499. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  90500. var _this = this;
  90501. return new Promise(function (res, rej) {
  90502. _this.useStandingMatrix(function (supported) {
  90503. res(supported);
  90504. });
  90505. });
  90506. };
  90507. /**
  90508. * Disposes the camera
  90509. */
  90510. WebVRFreeCamera.prototype.dispose = function () {
  90511. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  90512. _super.prototype.dispose.call(this);
  90513. };
  90514. /**
  90515. * Gets a vrController by name.
  90516. * @param name The name of the controller to retreive
  90517. * @returns the controller matching the name specified or null if not found
  90518. */
  90519. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  90520. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  90521. var gp = _a[_i];
  90522. if (gp.hand === name) {
  90523. return gp;
  90524. }
  90525. }
  90526. return null;
  90527. };
  90528. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  90529. /**
  90530. * The controller corrisponding to the users left hand.
  90531. */
  90532. get: function () {
  90533. if (!this._leftController) {
  90534. this._leftController = this.getControllerByName("left");
  90535. }
  90536. return this._leftController;
  90537. },
  90538. enumerable: true,
  90539. configurable: true
  90540. });
  90541. ;
  90542. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  90543. /**
  90544. * The controller corrisponding to the users right hand.
  90545. */
  90546. get: function () {
  90547. if (!this._rightController) {
  90548. this._rightController = this.getControllerByName("right");
  90549. }
  90550. return this._rightController;
  90551. },
  90552. enumerable: true,
  90553. configurable: true
  90554. });
  90555. ;
  90556. /**
  90557. * Casts a ray forward from the vrCamera's gaze.
  90558. * @param length Length of the ray (default: 100)
  90559. * @returns the ray corrisponding to the gaze
  90560. */
  90561. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  90562. if (length === void 0) { length = 100; }
  90563. if (this.leftCamera) {
  90564. // Use left eye to avoid computation to compute center on every call
  90565. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  90566. }
  90567. else {
  90568. return _super.prototype.getForwardRay.call(this, length);
  90569. }
  90570. };
  90571. /**
  90572. * Updates the camera based on device's frame data
  90573. */
  90574. WebVRFreeCamera.prototype._checkInputs = function () {
  90575. if (this._vrDevice && this._vrDevice.isPresenting) {
  90576. this._vrDevice.getFrameData(this._frameData);
  90577. this.updateFromDevice(this._frameData.pose);
  90578. }
  90579. _super.prototype._checkInputs.call(this);
  90580. };
  90581. /**
  90582. * Updates the poseControlled values based on the input device pose.
  90583. * @param poseData Pose coming from the device
  90584. */
  90585. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  90586. if (poseData && poseData.orientation) {
  90587. this.rawPose = poseData;
  90588. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  90589. if (this.getScene().useRightHandedSystem) {
  90590. this._deviceRoomRotationQuaternion.z *= -1;
  90591. this._deviceRoomRotationQuaternion.w *= -1;
  90592. }
  90593. if (this.webVROptions.trackPosition && this.rawPose.position) {
  90594. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  90595. if (this.getScene().useRightHandedSystem) {
  90596. this._deviceRoomPosition.z *= -1;
  90597. }
  90598. }
  90599. }
  90600. };
  90601. /**
  90602. * WebVR's attach control will start broadcasting frames to the device.
  90603. * Note that in certain browsers (chrome for example) this function must be called
  90604. * within a user-interaction callback. Example:
  90605. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  90606. *
  90607. * @param element html element to attach the vrDevice to
  90608. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  90609. */
  90610. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  90611. _super.prototype.attachControl.call(this, element, noPreventDefault);
  90612. this._attached = true;
  90613. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  90614. if (this._vrDevice) {
  90615. this.getEngine().enableVR();
  90616. }
  90617. };
  90618. /**
  90619. * Detaches the camera from the html element and disables VR
  90620. *
  90621. * @param element html element to detach from
  90622. */
  90623. WebVRFreeCamera.prototype.detachControl = function (element) {
  90624. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  90625. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  90626. _super.prototype.detachControl.call(this, element);
  90627. this._attached = false;
  90628. this.getEngine().disableVR();
  90629. };
  90630. /**
  90631. * @returns the name of this class
  90632. */
  90633. WebVRFreeCamera.prototype.getClassName = function () {
  90634. return "WebVRFreeCamera";
  90635. };
  90636. /**
  90637. * Calls resetPose on the vrDisplay
  90638. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  90639. */
  90640. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  90641. //uses the vrDisplay's "resetPose()".
  90642. //pitch and roll won't be affected.
  90643. this._vrDevice.resetPose();
  90644. };
  90645. /**
  90646. * Updates the rig cameras (left and right eye)
  90647. */
  90648. WebVRFreeCamera.prototype._updateRigCameras = function () {
  90649. var camLeft = this._rigCameras[0];
  90650. var camRight = this._rigCameras[1];
  90651. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90652. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90653. camLeft.position.copyFrom(this._deviceRoomPosition);
  90654. camRight.position.copyFrom(this._deviceRoomPosition);
  90655. };
  90656. /**
  90657. * Updates the cached values of the camera
  90658. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  90659. */
  90660. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  90661. var _this = this;
  90662. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  90663. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  90664. if (!this.updateCacheCalled) {
  90665. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  90666. this.updateCacheCalled = true;
  90667. this.update();
  90668. }
  90669. // Set working vector to the device position in room space rotated by the new rotation
  90670. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  90671. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  90672. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  90673. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  90674. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  90675. // Add translation from anchor position
  90676. this._deviceToWorld.getTranslationToRef(this._workingVector);
  90677. this._workingVector.addInPlace(this.position);
  90678. this._workingVector.subtractInPlace(this._cache.position);
  90679. this._deviceToWorld.setTranslation(this._workingVector);
  90680. // Set an inverted matrix to be used when updating the camera
  90681. this._deviceToWorld.invertToRef(this._worldToDevice);
  90682. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  90683. this.controllers.forEach(function (controller) {
  90684. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  90685. controller.update();
  90686. });
  90687. }
  90688. if (!ignoreParentClass) {
  90689. _super.prototype._updateCache.call(this);
  90690. }
  90691. this.updateCacheCalled = false;
  90692. };
  90693. /**
  90694. * Updates the current device position and rotation in the babylon world
  90695. */
  90696. WebVRFreeCamera.prototype.update = function () {
  90697. // Get current device position in babylon world
  90698. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  90699. // Get current device rotation in babylon world
  90700. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  90701. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  90702. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  90703. _super.prototype.update.call(this);
  90704. };
  90705. /**
  90706. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  90707. * @returns an identity matrix
  90708. */
  90709. WebVRFreeCamera.prototype._getViewMatrix = function () {
  90710. return BABYLON.Matrix.Identity();
  90711. };
  90712. /**
  90713. * This function is called by the two RIG cameras.
  90714. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  90715. */
  90716. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  90717. var _this = this;
  90718. // Update the parent camera prior to using a child camera to avoid desynchronization
  90719. var parentCamera = this._cameraRigParams["parentCamera"];
  90720. parentCamera._updateCache();
  90721. //WebVR 1.1
  90722. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  90723. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  90724. if (!this.getScene().useRightHandedSystem) {
  90725. [2, 6, 8, 9, 14].forEach(function (num) {
  90726. _this._webvrViewMatrix.m[num] *= -1;
  90727. });
  90728. }
  90729. // update the camera rotation matrix
  90730. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  90731. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  90732. // Computing target and final matrix
  90733. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  90734. // should the view matrix be updated with scale and position offset?
  90735. if (parentCamera.deviceScaleFactor !== 1) {
  90736. this._webvrViewMatrix.invert();
  90737. // scale the position, if set
  90738. if (parentCamera.deviceScaleFactor) {
  90739. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  90740. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  90741. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  90742. }
  90743. this._webvrViewMatrix.invert();
  90744. }
  90745. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  90746. // Compute global position
  90747. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  90748. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  90749. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  90750. this._workingMatrix.getTranslationToRef(this._globalPosition);
  90751. this._markSyncedWithParent();
  90752. return this._webvrViewMatrix;
  90753. };
  90754. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  90755. var _this = this;
  90756. var parentCamera = this.parent;
  90757. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  90758. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  90759. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  90760. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  90761. //babylon compatible matrix
  90762. if (!this.getScene().useRightHandedSystem) {
  90763. [8, 9, 10, 11].forEach(function (num) {
  90764. _this._projectionMatrix.m[num] *= -1;
  90765. });
  90766. }
  90767. return this._projectionMatrix;
  90768. };
  90769. /**
  90770. * Initializes the controllers and their meshes
  90771. */
  90772. WebVRFreeCamera.prototype.initControllers = function () {
  90773. var _this = this;
  90774. this.controllers = [];
  90775. var manager = this.getScene().gamepadManager;
  90776. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  90777. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90778. var webVrController = gamepad;
  90779. if (webVrController.defaultModel) {
  90780. webVrController.defaultModel.setEnabled(false);
  90781. }
  90782. if (webVrController.hand === "right") {
  90783. _this._rightController = null;
  90784. }
  90785. if (webVrController.hand === "left") {
  90786. _this._leftController = null;
  90787. }
  90788. var controllerIndex = _this.controllers.indexOf(webVrController);
  90789. if (controllerIndex !== -1) {
  90790. _this.controllers.splice(controllerIndex, 1);
  90791. }
  90792. }
  90793. });
  90794. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  90795. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90796. var webVrController_1 = gamepad;
  90797. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  90798. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  90799. if (_this.webVROptions.controllerMeshes) {
  90800. if (webVrController_1.defaultModel) {
  90801. webVrController_1.defaultModel.setEnabled(true);
  90802. }
  90803. else {
  90804. // Load the meshes
  90805. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  90806. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  90807. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  90808. if (_this.webVROptions.defaultLightingOnControllers) {
  90809. if (!_this._lightOnControllers) {
  90810. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  90811. }
  90812. var activateLightOnSubMeshes_1 = function (mesh, light) {
  90813. var children = mesh.getChildren();
  90814. if (children.length !== 0) {
  90815. children.forEach(function (mesh) {
  90816. light.includedOnlyMeshes.push(mesh);
  90817. activateLightOnSubMeshes_1(mesh, light);
  90818. });
  90819. }
  90820. };
  90821. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  90822. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  90823. }
  90824. });
  90825. }
  90826. }
  90827. webVrController_1.attachToPoseControlledCamera(_this);
  90828. // since this is async - sanity check. Is the controller already stored?
  90829. if (_this.controllers.indexOf(webVrController_1) === -1) {
  90830. //add to the controllers array
  90831. _this.controllers.push(webVrController_1);
  90832. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  90833. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  90834. // So we're overriding setting left & right manually to be sure
  90835. var firstViveWandDetected = false;
  90836. for (var i = 0; i < _this.controllers.length; i++) {
  90837. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90838. if (!firstViveWandDetected) {
  90839. firstViveWandDetected = true;
  90840. _this.controllers[i].hand = "left";
  90841. }
  90842. else {
  90843. _this.controllers[i].hand = "right";
  90844. }
  90845. }
  90846. }
  90847. //did we find enough controllers? Great! let the developer know.
  90848. if (_this.controllers.length >= 2) {
  90849. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  90850. }
  90851. }
  90852. }
  90853. });
  90854. };
  90855. return WebVRFreeCamera;
  90856. }(BABYLON.FreeCamera));
  90857. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  90858. })(BABYLON || (BABYLON = {}));
  90859. //# sourceMappingURL=babylon.webVRCamera.js.map
  90860. var BABYLON;
  90861. (function (BABYLON) {
  90862. // We're mainly based on the logic defined into the FreeCamera code
  90863. /**
  90864. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  90865. * being tilted forward or back and left or right.
  90866. */
  90867. var DeviceOrientationCamera = /** @class */ (function (_super) {
  90868. __extends(DeviceOrientationCamera, _super);
  90869. /**
  90870. * Creates a new device orientation camera
  90871. * @param name The name of the camera
  90872. * @param position The start position camera
  90873. * @param scene The scene the camera belongs to
  90874. */
  90875. function DeviceOrientationCamera(name, position, scene) {
  90876. var _this = _super.call(this, name, position, scene) || this;
  90877. _this._quaternionCache = new BABYLON.Quaternion();
  90878. _this.inputs.addDeviceOrientation();
  90879. return _this;
  90880. }
  90881. /**
  90882. * Gets the current instance class name ("DeviceOrientationCamera").
  90883. * This helps avoiding instanceof at run time.
  90884. * @returns the class name
  90885. */
  90886. DeviceOrientationCamera.prototype.getClassName = function () {
  90887. return "DeviceOrientationCamera";
  90888. };
  90889. /**
  90890. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  90891. */
  90892. DeviceOrientationCamera.prototype._checkInputs = function () {
  90893. _super.prototype._checkInputs.call(this);
  90894. this._quaternionCache.copyFrom(this.rotationQuaternion);
  90895. if (this._initialQuaternion) {
  90896. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90897. }
  90898. };
  90899. /**
  90900. * Reset the camera to its default orientation on the specified axis only.
  90901. * @param axis The axis to reset
  90902. */
  90903. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  90904. var _this = this;
  90905. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  90906. //can only work if this camera has a rotation quaternion already.
  90907. if (!this.rotationQuaternion)
  90908. return;
  90909. if (!this._initialQuaternion) {
  90910. this._initialQuaternion = new BABYLON.Quaternion();
  90911. }
  90912. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  90913. ['x', 'y', 'z'].forEach(function (axisName) {
  90914. if (!axis[axisName]) {
  90915. _this._initialQuaternion[axisName] = 0;
  90916. }
  90917. else {
  90918. _this._initialQuaternion[axisName] *= -1;
  90919. }
  90920. });
  90921. this._initialQuaternion.normalize();
  90922. //force rotation update
  90923. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90924. };
  90925. return DeviceOrientationCamera;
  90926. }(BABYLON.FreeCamera));
  90927. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  90928. })(BABYLON || (BABYLON = {}));
  90929. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  90930. var BABYLON;
  90931. (function (BABYLON) {
  90932. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  90933. __extends(VRDeviceOrientationFreeCamera, _super);
  90934. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90935. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90936. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90937. var _this = _super.call(this, name, position, scene) || this;
  90938. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90939. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90940. return _this;
  90941. }
  90942. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  90943. return "VRDeviceOrientationFreeCamera";
  90944. };
  90945. return VRDeviceOrientationFreeCamera;
  90946. }(BABYLON.DeviceOrientationCamera));
  90947. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  90948. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  90949. __extends(VRDeviceOrientationGamepadCamera, _super);
  90950. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90951. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90952. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90953. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  90954. _this.inputs.addGamepad();
  90955. return _this;
  90956. }
  90957. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  90958. return "VRDeviceOrientationGamepadCamera";
  90959. };
  90960. return VRDeviceOrientationGamepadCamera;
  90961. }(VRDeviceOrientationFreeCamera));
  90962. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  90963. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  90964. __extends(VRDeviceOrientationArcRotateCamera, _super);
  90965. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  90966. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90967. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90968. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90969. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90970. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90971. _this.inputs.addVRDeviceOrientation();
  90972. return _this;
  90973. }
  90974. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  90975. return "VRDeviceOrientationArcRotateCamera";
  90976. };
  90977. return VRDeviceOrientationArcRotateCamera;
  90978. }(BABYLON.ArcRotateCamera));
  90979. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  90980. })(BABYLON || (BABYLON = {}));
  90981. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  90982. var BABYLON;
  90983. (function (BABYLON) {
  90984. /**
  90985. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  90986. */
  90987. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  90988. __extends(AnaglyphFreeCamera, _super);
  90989. /**
  90990. * Creates a new AnaglyphFreeCamera
  90991. * @param name defines camera name
  90992. * @param position defines initial position
  90993. * @param interaxialDistance defines distance between each color axis
  90994. * @param scene defines the hosting scene
  90995. */
  90996. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  90997. var _this = _super.call(this, name, position, scene) || this;
  90998. _this.interaxialDistance = interaxialDistance;
  90999. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91000. return _this;
  91001. }
  91002. /**
  91003. * Gets camera class name
  91004. * @returns AnaglyphFreeCamera
  91005. */
  91006. AnaglyphFreeCamera.prototype.getClassName = function () {
  91007. return "AnaglyphFreeCamera";
  91008. };
  91009. return AnaglyphFreeCamera;
  91010. }(BABYLON.FreeCamera));
  91011. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91012. /**
  91013. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91014. */
  91015. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91016. __extends(AnaglyphArcRotateCamera, _super);
  91017. /**
  91018. * Creates a new AnaglyphArcRotateCamera
  91019. * @param name defines camera name
  91020. * @param alpha defines alpha angle (in radians)
  91021. * @param beta defines beta angle (in radians)
  91022. * @param radius defines radius
  91023. * @param target defines camera target
  91024. * @param interaxialDistance defines distance between each color axis
  91025. * @param scene defines the hosting scene
  91026. */
  91027. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91028. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91029. _this.interaxialDistance = interaxialDistance;
  91030. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91031. return _this;
  91032. }
  91033. /**
  91034. * Gets camera class name
  91035. * @returns AnaglyphArcRotateCamera
  91036. */
  91037. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91038. return "AnaglyphArcRotateCamera";
  91039. };
  91040. return AnaglyphArcRotateCamera;
  91041. }(BABYLON.ArcRotateCamera));
  91042. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91043. /**
  91044. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91045. */
  91046. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91047. __extends(AnaglyphGamepadCamera, _super);
  91048. /**
  91049. * Creates a new AnaglyphGamepadCamera
  91050. * @param name defines camera name
  91051. * @param position defines initial position
  91052. * @param interaxialDistance defines distance between each color axis
  91053. * @param scene defines the hosting scene
  91054. */
  91055. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91056. var _this = _super.call(this, name, position, scene) || this;
  91057. _this.interaxialDistance = interaxialDistance;
  91058. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91059. return _this;
  91060. }
  91061. /**
  91062. * Gets camera class name
  91063. * @returns AnaglyphGamepadCamera
  91064. */
  91065. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91066. return "AnaglyphGamepadCamera";
  91067. };
  91068. return AnaglyphGamepadCamera;
  91069. }(BABYLON.GamepadCamera));
  91070. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91071. /**
  91072. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91073. */
  91074. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91075. __extends(AnaglyphUniversalCamera, _super);
  91076. /**
  91077. * Creates a new AnaglyphUniversalCamera
  91078. * @param name defines camera name
  91079. * @param position defines initial position
  91080. * @param interaxialDistance defines distance between each color axis
  91081. * @param scene defines the hosting scene
  91082. */
  91083. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91084. var _this = _super.call(this, name, position, scene) || this;
  91085. _this.interaxialDistance = interaxialDistance;
  91086. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91087. return _this;
  91088. }
  91089. /**
  91090. * Gets camera class name
  91091. * @returns AnaglyphUniversalCamera
  91092. */
  91093. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91094. return "AnaglyphUniversalCamera";
  91095. };
  91096. return AnaglyphUniversalCamera;
  91097. }(BABYLON.UniversalCamera));
  91098. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91099. /**
  91100. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91101. */
  91102. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91103. __extends(StereoscopicFreeCamera, _super);
  91104. /**
  91105. * Creates a new StereoscopicFreeCamera
  91106. * @param name defines camera name
  91107. * @param position defines initial position
  91108. * @param interaxialDistance defines distance between each color axis
  91109. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91110. * @param scene defines the hosting scene
  91111. */
  91112. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91113. var _this = _super.call(this, name, position, scene) || this;
  91114. _this.interaxialDistance = interaxialDistance;
  91115. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91116. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91117. return _this;
  91118. }
  91119. /**
  91120. * Gets camera class name
  91121. * @returns StereoscopicFreeCamera
  91122. */
  91123. StereoscopicFreeCamera.prototype.getClassName = function () {
  91124. return "StereoscopicFreeCamera";
  91125. };
  91126. return StereoscopicFreeCamera;
  91127. }(BABYLON.FreeCamera));
  91128. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91129. /**
  91130. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91131. */
  91132. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91133. __extends(StereoscopicArcRotateCamera, _super);
  91134. /**
  91135. * Creates a new StereoscopicArcRotateCamera
  91136. * @param name defines camera name
  91137. * @param alpha defines alpha angle (in radians)
  91138. * @param beta defines beta angle (in radians)
  91139. * @param radius defines radius
  91140. * @param target defines camera target
  91141. * @param interaxialDistance defines distance between each color axis
  91142. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91143. * @param scene defines the hosting scene
  91144. */
  91145. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91146. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91147. _this.interaxialDistance = interaxialDistance;
  91148. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91149. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91150. return _this;
  91151. }
  91152. /**
  91153. * Gets camera class name
  91154. * @returns StereoscopicArcRotateCamera
  91155. */
  91156. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91157. return "StereoscopicArcRotateCamera";
  91158. };
  91159. return StereoscopicArcRotateCamera;
  91160. }(BABYLON.ArcRotateCamera));
  91161. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91162. /**
  91163. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91164. */
  91165. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91166. __extends(StereoscopicGamepadCamera, _super);
  91167. /**
  91168. * Creates a new StereoscopicGamepadCamera
  91169. * @param name defines camera name
  91170. * @param position defines initial position
  91171. * @param interaxialDistance defines distance between each color axis
  91172. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91173. * @param scene defines the hosting scene
  91174. */
  91175. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91176. var _this = _super.call(this, name, position, scene) || this;
  91177. _this.interaxialDistance = interaxialDistance;
  91178. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91179. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91180. return _this;
  91181. }
  91182. /**
  91183. * Gets camera class name
  91184. * @returns StereoscopicGamepadCamera
  91185. */
  91186. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91187. return "StereoscopicGamepadCamera";
  91188. };
  91189. return StereoscopicGamepadCamera;
  91190. }(BABYLON.GamepadCamera));
  91191. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91192. /**
  91193. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91194. */
  91195. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91196. __extends(StereoscopicUniversalCamera, _super);
  91197. /**
  91198. * Creates a new StereoscopicUniversalCamera
  91199. * @param name defines camera name
  91200. * @param position defines initial position
  91201. * @param interaxialDistance defines distance between each color axis
  91202. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91203. * @param scene defines the hosting scene
  91204. */
  91205. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91206. var _this = _super.call(this, name, position, scene) || this;
  91207. _this.interaxialDistance = interaxialDistance;
  91208. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91209. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91210. return _this;
  91211. }
  91212. /**
  91213. * Gets camera class name
  91214. * @returns StereoscopicUniversalCamera
  91215. */
  91216. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91217. return "StereoscopicUniversalCamera";
  91218. };
  91219. return StereoscopicUniversalCamera;
  91220. }(BABYLON.UniversalCamera));
  91221. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91222. })(BABYLON || (BABYLON = {}));
  91223. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91224. var BABYLON;
  91225. (function (BABYLON) {
  91226. var VRExperienceHelperGazer = /** @class */ (function () {
  91227. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91228. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91229. this.scene = scene;
  91230. this._pointerDownOnMeshAsked = false;
  91231. this._isActionableMesh = false;
  91232. this._teleportationRequestInitiated = false;
  91233. this._teleportationBackRequestInitiated = false;
  91234. this._rotationRightAsked = false;
  91235. this._rotationLeftAsked = false;
  91236. this._dpadPressed = true;
  91237. this._activePointer = false;
  91238. this._id = VRExperienceHelperGazer._idCounter++;
  91239. // Gaze tracker
  91240. if (!gazeTrackerToClone) {
  91241. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91242. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91243. this._gazeTracker.isPickable = false;
  91244. this._gazeTracker.isVisible = false;
  91245. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91246. targetMat.specularColor = BABYLON.Color3.Black();
  91247. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91248. targetMat.backFaceCulling = false;
  91249. this._gazeTracker.material = targetMat;
  91250. }
  91251. else {
  91252. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91253. }
  91254. }
  91255. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91256. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91257. };
  91258. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91259. this._pointerDownOnMeshAsked = true;
  91260. if (this._currentHit) {
  91261. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91262. }
  91263. };
  91264. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91265. if (this._currentHit) {
  91266. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91267. }
  91268. this._pointerDownOnMeshAsked = false;
  91269. };
  91270. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91271. this._activePointer = true;
  91272. };
  91273. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91274. this._activePointer = false;
  91275. };
  91276. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91277. if (distance === void 0) { distance = 100; }
  91278. };
  91279. VRExperienceHelperGazer.prototype.dispose = function () {
  91280. this._interactionsEnabled = false;
  91281. this._teleportationEnabled = false;
  91282. if (this._gazeTracker) {
  91283. this._gazeTracker.dispose();
  91284. }
  91285. };
  91286. VRExperienceHelperGazer._idCounter = 0;
  91287. return VRExperienceHelperGazer;
  91288. }());
  91289. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91290. __extends(VRExperienceHelperControllerGazer, _super);
  91291. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91292. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91293. _this.webVRController = webVRController;
  91294. // Laser pointer
  91295. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91296. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91297. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91298. laserPointerMaterial.alpha = 0.6;
  91299. _this._laserPointer.material = laserPointerMaterial;
  91300. _this._laserPointer.rotation.x = Math.PI / 2;
  91301. _this._laserPointer.position.z = -0.5;
  91302. _this._laserPointer.isVisible = false;
  91303. _this._laserPointer.isPickable = false;
  91304. if (!webVRController.mesh) {
  91305. // Create an empty mesh that is used prior to loading the high quality model
  91306. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91307. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91308. preloadPointerPose.rotation.x = -0.7;
  91309. preloadMesh.addChild(preloadPointerPose);
  91310. webVRController.attachToMesh(preloadMesh);
  91311. }
  91312. _this._setLaserPointerParent(webVRController.mesh);
  91313. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91314. _this._setLaserPointerParent(mesh);
  91315. });
  91316. return _this;
  91317. }
  91318. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91319. return this.webVRController.getForwardRay(length);
  91320. };
  91321. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91322. _super.prototype._activatePointer.call(this);
  91323. this._laserPointer.isVisible = true;
  91324. };
  91325. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91326. _super.prototype._deactivatePointer.call(this);
  91327. this._laserPointer.isVisible = false;
  91328. };
  91329. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91330. this._laserPointer.material.emissiveColor = color;
  91331. };
  91332. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91333. var makeNotPick = function (root) {
  91334. root.name += " laserPointer";
  91335. root.isPickable = false;
  91336. root.getChildMeshes().forEach(function (c) {
  91337. makeNotPick(c);
  91338. });
  91339. };
  91340. makeNotPick(mesh);
  91341. var childMeshes = mesh.getChildMeshes();
  91342. this.webVRController._pointingPoseNode = null;
  91343. for (var i = 0; i < childMeshes.length; i++) {
  91344. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91345. mesh = childMeshes[i];
  91346. this.webVRController._pointingPoseNode = mesh;
  91347. break;
  91348. }
  91349. }
  91350. this._laserPointer.parent = mesh;
  91351. };
  91352. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91353. if (distance === void 0) { distance = 100; }
  91354. this._laserPointer.scaling.y = distance;
  91355. this._laserPointer.position.z = -distance / 2;
  91356. };
  91357. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91358. _super.prototype.dispose.call(this);
  91359. this._laserPointer.dispose();
  91360. if (this._meshAttachedObserver) {
  91361. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  91362. }
  91363. };
  91364. return VRExperienceHelperControllerGazer;
  91365. }(VRExperienceHelperGazer));
  91366. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  91367. __extends(VRExperienceHelperCameraGazer, _super);
  91368. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91369. var _this = _super.call(this, scene) || this;
  91370. _this.getCamera = getCamera;
  91371. return _this;
  91372. }
  91373. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91374. var camera = this.getCamera();
  91375. if (camera) {
  91376. return camera.getForwardRay(length);
  91377. }
  91378. else {
  91379. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91380. }
  91381. };
  91382. return VRExperienceHelperCameraGazer;
  91383. }(VRExperienceHelperGazer));
  91384. /**
  91385. * Helps to quickly add VR support to an existing scene.
  91386. * See http://doc.babylonjs.com/how_to/webvr_helper
  91387. */
  91388. var VRExperienceHelper = /** @class */ (function () {
  91389. /**
  91390. * Instantiates a VRExperienceHelper.
  91391. * Helps to quickly add VR support to an existing scene.
  91392. * @param scene The scene the VRExperienceHelper belongs to.
  91393. * @param webVROptions Options to modify the vr experience helper's behavior.
  91394. */
  91395. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  91396. if (webVROptions === void 0) { webVROptions = {}; }
  91397. var _this = this;
  91398. this.webVROptions = webVROptions;
  91399. // Can the system support WebVR, even if a headset isn't plugged in?
  91400. this._webVRsupported = false;
  91401. // If WebVR is supported, is a headset plugged in and are we ready to present?
  91402. this._webVRready = false;
  91403. // Are we waiting for the requestPresent callback to complete?
  91404. this._webVRrequesting = false;
  91405. // Are we presenting to the headset right now?
  91406. this._webVRpresenting = false;
  91407. // Are we presenting in the fullscreen fallback?
  91408. this._fullscreenVRpresenting = false;
  91409. /**
  91410. * Observable raised when entering VR.
  91411. */
  91412. this.onEnteringVRObservable = new BABYLON.Observable();
  91413. /**
  91414. * Observable raised when exiting VR.
  91415. */
  91416. this.onExitingVRObservable = new BABYLON.Observable();
  91417. /**
  91418. * Observable raised when controller mesh is loaded.
  91419. */
  91420. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91421. this._useCustomVRButton = false;
  91422. this._teleportationRequested = false;
  91423. this._teleportActive = false;
  91424. this._floorMeshesCollection = [];
  91425. this._rotationAllowed = true;
  91426. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  91427. this._isDefaultTeleportationTarget = true;
  91428. this._teleportationFillColor = "#444444";
  91429. this._teleportationBorderColor = "#FFFFFF";
  91430. this._rotationAngle = 0;
  91431. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  91432. this._padSensibilityUp = 0.65;
  91433. this._padSensibilityDown = 0.35;
  91434. this.leftController = null;
  91435. this.rightController = null;
  91436. /**
  91437. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  91438. */
  91439. this.onNewMeshSelected = new BABYLON.Observable();
  91440. /**
  91441. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  91442. */
  91443. this.onNewMeshPicked = new BABYLON.Observable();
  91444. /**
  91445. * Observable raised before camera teleportation
  91446. */
  91447. this.onBeforeCameraTeleport = new BABYLON.Observable();
  91448. /**
  91449. * Observable raised after camera teleportation
  91450. */
  91451. this.onAfterCameraTeleport = new BABYLON.Observable();
  91452. /**
  91453. * Observable raised when current selected mesh gets unselected
  91454. */
  91455. this.onSelectedMeshUnselected = new BABYLON.Observable();
  91456. /**
  91457. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  91458. */
  91459. this.teleportationEnabled = true;
  91460. this._teleportationInitialized = false;
  91461. this._interactionsEnabled = false;
  91462. this._interactionsRequested = false;
  91463. this._displayGaze = true;
  91464. this._displayLaserPointer = true;
  91465. this._onResize = function () {
  91466. _this.moveButtonToBottomRight();
  91467. if (_this._fullscreenVRpresenting && _this._webVRready) {
  91468. _this.exitVR();
  91469. }
  91470. };
  91471. this._onFullscreenChange = function () {
  91472. if (document.fullscreen !== undefined) {
  91473. _this._fullscreenVRpresenting = document.fullscreen;
  91474. }
  91475. else if (document.mozFullScreen !== undefined) {
  91476. _this._fullscreenVRpresenting = document.mozFullScreen;
  91477. }
  91478. else if (document.webkitIsFullScreen !== undefined) {
  91479. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  91480. }
  91481. else if (document.msIsFullScreen !== undefined) {
  91482. _this._fullscreenVRpresenting = document.msIsFullScreen;
  91483. }
  91484. else if (document.msFullscreenElement !== undefined) {
  91485. _this._fullscreenVRpresenting = document.msFullscreenElement;
  91486. }
  91487. if (!_this._fullscreenVRpresenting && _this._canvas) {
  91488. _this.exitVR();
  91489. if (!_this._useCustomVRButton) {
  91490. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  91491. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  91492. }
  91493. }
  91494. };
  91495. this.beforeRender = function () {
  91496. if (_this.leftController && _this.leftController._activePointer) {
  91497. _this._castRayAndSelectObject(_this.leftController);
  91498. }
  91499. if (_this.rightController && _this.rightController._activePointer) {
  91500. _this._castRayAndSelectObject(_this.rightController);
  91501. }
  91502. if (_this._noControllerIsActive) {
  91503. _this._castRayAndSelectObject(_this._cameraGazer);
  91504. }
  91505. else {
  91506. _this._cameraGazer._gazeTracker.isVisible = false;
  91507. }
  91508. };
  91509. this._onNewGamepadConnected = function (gamepad) {
  91510. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  91511. if (gamepad.leftStick) {
  91512. gamepad.onleftstickchanged(function (stickValues) {
  91513. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  91514. // Listening to classic/xbox gamepad only if no VR controller is active
  91515. if ((!_this.leftController && !_this.rightController) ||
  91516. ((_this.leftController && !_this.leftController._activePointer) &&
  91517. (_this.rightController && !_this.rightController._activePointer))) {
  91518. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  91519. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  91520. }
  91521. }
  91522. });
  91523. }
  91524. if (gamepad.rightStick) {
  91525. gamepad.onrightstickchanged(function (stickValues) {
  91526. if (_this._teleportationInitialized) {
  91527. _this._checkRotate(stickValues, _this._cameraGazer);
  91528. }
  91529. });
  91530. }
  91531. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  91532. gamepad.onbuttondown(function (buttonPressed) {
  91533. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91534. _this._cameraGazer._selectionPointerDown();
  91535. }
  91536. });
  91537. gamepad.onbuttonup(function (buttonPressed) {
  91538. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91539. _this._cameraGazer._selectionPointerUp();
  91540. }
  91541. });
  91542. }
  91543. }
  91544. else {
  91545. var webVRController = gamepad;
  91546. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  91547. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  91548. _this.rightController = controller;
  91549. }
  91550. else {
  91551. _this.leftController = controller;
  91552. }
  91553. _this._tryEnableInteractionOnController(controller);
  91554. }
  91555. };
  91556. // 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
  91557. this._tryEnableInteractionOnController = function (controller) {
  91558. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  91559. _this._enableInteractionOnController(controller);
  91560. }
  91561. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  91562. _this._enableTeleportationOnController(controller);
  91563. }
  91564. };
  91565. this._onNewGamepadDisconnected = function (gamepad) {
  91566. if (gamepad instanceof BABYLON.WebVRController) {
  91567. if (gamepad.hand === "left" && _this.leftController != null) {
  91568. _this.leftController.dispose();
  91569. _this.leftController = null;
  91570. }
  91571. if (gamepad.hand === "right" && _this.rightController != null) {
  91572. _this.rightController.dispose();
  91573. _this.rightController = null;
  91574. }
  91575. }
  91576. };
  91577. this._workingVector = BABYLON.Vector3.Zero();
  91578. this._workingQuaternion = BABYLON.Quaternion.Identity();
  91579. this._workingMatrix = BABYLON.Matrix.Identity();
  91580. this._scene = scene;
  91581. this._canvas = scene.getEngine().getRenderingCanvas();
  91582. // Parse options
  91583. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  91584. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  91585. }
  91586. if (webVROptions.createDeviceOrientationCamera === undefined) {
  91587. webVROptions.createDeviceOrientationCamera = true;
  91588. }
  91589. if (webVROptions.laserToggle === undefined) {
  91590. webVROptions.laserToggle = true;
  91591. }
  91592. if (webVROptions.defaultHeight === undefined) {
  91593. webVROptions.defaultHeight = 1.7;
  91594. }
  91595. if (webVROptions.useCustomVRButton) {
  91596. this._useCustomVRButton = true;
  91597. if (webVROptions.customVRButton) {
  91598. this._btnVR = webVROptions.customVRButton;
  91599. }
  91600. }
  91601. if (webVROptions.rayLength) {
  91602. this._rayLength = webVROptions.rayLength;
  91603. }
  91604. this._defaultHeight = webVROptions.defaultHeight;
  91605. if (webVROptions.positionScale) {
  91606. this._rayLength *= webVROptions.positionScale;
  91607. this._defaultHeight *= webVROptions.positionScale;
  91608. }
  91609. // Set position
  91610. if (this._scene.activeCamera) {
  91611. this._position = this._scene.activeCamera.position.clone();
  91612. }
  91613. else {
  91614. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  91615. }
  91616. // Set non-vr camera
  91617. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  91618. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  91619. // Copy data from existing camera
  91620. if (this._scene.activeCamera) {
  91621. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91622. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  91623. // Set rotation from previous camera
  91624. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  91625. var targetCamera = this._scene.activeCamera;
  91626. if (targetCamera.rotationQuaternion) {
  91627. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  91628. }
  91629. else {
  91630. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  91631. }
  91632. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  91633. }
  91634. }
  91635. this._scene.activeCamera = this._deviceOrientationCamera;
  91636. if (this._canvas) {
  91637. this._scene.activeCamera.attachControl(this._canvas);
  91638. }
  91639. }
  91640. else {
  91641. this._existingCamera = this._scene.activeCamera;
  91642. }
  91643. // Create VR cameras
  91644. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91645. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  91646. }
  91647. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  91648. this._webVRCamera.useStandingMatrix();
  91649. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  91650. // Create default button
  91651. if (!this._useCustomVRButton) {
  91652. this._btnVR = document.createElement("BUTTON");
  91653. this._btnVR.className = "babylonVRicon";
  91654. this._btnVR.id = "babylonVRiconbtn";
  91655. this._btnVR.title = "Click to switch to VR";
  91656. 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) }";
  91657. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  91658. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  91659. // css += ".babylonVRicon.vrdisplaysupported { }";
  91660. // css += ".babylonVRicon.vrdisplayready { }";
  91661. // css += ".babylonVRicon.vrdisplayrequesting { }";
  91662. var style = document.createElement('style');
  91663. style.appendChild(document.createTextNode(css));
  91664. document.getElementsByTagName('head')[0].appendChild(style);
  91665. this.moveButtonToBottomRight();
  91666. }
  91667. // VR button click event
  91668. if (this._btnVR) {
  91669. this._btnVR.addEventListener("click", function () {
  91670. if (!_this.isInVRMode) {
  91671. _this.enterVR();
  91672. }
  91673. else {
  91674. _this.exitVR();
  91675. }
  91676. });
  91677. }
  91678. // Window events
  91679. window.addEventListener("resize", this._onResize);
  91680. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  91681. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  91682. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  91683. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  91684. document.onmsfullscreenchange = this._onFullscreenChange;
  91685. // Display vr button when headset is connected
  91686. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91687. this.displayVRButton();
  91688. }
  91689. else {
  91690. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  91691. if (e.vrDisplay) {
  91692. _this.displayVRButton();
  91693. }
  91694. });
  91695. }
  91696. // Exiting VR mode using 'ESC' key on desktop
  91697. this._onKeyDown = function (event) {
  91698. if (event.keyCode === 27 && _this.isInVRMode) {
  91699. _this.exitVR();
  91700. }
  91701. };
  91702. document.addEventListener("keydown", this._onKeyDown);
  91703. // Exiting VR mode double tapping the touch screen
  91704. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  91705. if (_this.isInVRMode) {
  91706. _this.exitVR();
  91707. if (_this._fullscreenVRpresenting) {
  91708. _this._scene.getEngine().switchFullscreen(true);
  91709. }
  91710. }
  91711. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  91712. // Listen for WebVR display changes
  91713. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  91714. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  91715. this._onVRRequestPresentStart = function () {
  91716. _this._webVRrequesting = true;
  91717. _this.updateButtonVisibility();
  91718. };
  91719. this._onVRRequestPresentComplete = function (success) {
  91720. _this._webVRrequesting = false;
  91721. _this.updateButtonVisibility();
  91722. };
  91723. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  91724. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  91725. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  91726. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91727. scene.onDisposeObservable.add(function () {
  91728. _this.dispose();
  91729. });
  91730. // Gamepad connection events
  91731. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  91732. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  91733. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  91734. this.updateButtonVisibility();
  91735. //create easing functions
  91736. this._circleEase = new BABYLON.CircleEase();
  91737. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91738. if (this.webVROptions.floorMeshes) {
  91739. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  91740. }
  91741. }
  91742. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  91743. /** Return this.onEnteringVRObservable
  91744. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  91745. */
  91746. get: function () {
  91747. return this.onEnteringVRObservable;
  91748. },
  91749. enumerable: true,
  91750. configurable: true
  91751. });
  91752. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  91753. /** Return this.onExitingVRObservable
  91754. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  91755. */
  91756. get: function () {
  91757. return this.onExitingVRObservable;
  91758. },
  91759. enumerable: true,
  91760. configurable: true
  91761. });
  91762. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  91763. /** Return this.onControllerMeshLoadedObservable
  91764. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  91765. */
  91766. get: function () {
  91767. return this.onControllerMeshLoadedObservable;
  91768. },
  91769. enumerable: true,
  91770. configurable: true
  91771. });
  91772. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  91773. /**
  91774. * The mesh used to display where the user is going to teleport.
  91775. */
  91776. get: function () {
  91777. return this._teleportationTarget;
  91778. },
  91779. /**
  91780. * Sets the mesh to be used to display where the user is going to teleport.
  91781. */
  91782. set: function (value) {
  91783. if (value) {
  91784. value.name = "teleportationTarget";
  91785. this._isDefaultTeleportationTarget = false;
  91786. this._teleportationTarget = value;
  91787. }
  91788. },
  91789. enumerable: true,
  91790. configurable: true
  91791. });
  91792. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  91793. /**
  91794. * The mesh used to display where the user is selecting,
  91795. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  91796. * See http://doc.babylonjs.com/resources/baking_transformations
  91797. */
  91798. get: function () {
  91799. return this._cameraGazer._gazeTracker;
  91800. },
  91801. set: function (value) {
  91802. if (value) {
  91803. this._cameraGazer._gazeTracker = value;
  91804. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  91805. this._cameraGazer._gazeTracker.isPickable = false;
  91806. this._cameraGazer._gazeTracker.isVisible = false;
  91807. this._cameraGazer._gazeTracker.name = "gazeTracker";
  91808. if (this.leftController) {
  91809. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91810. }
  91811. if (this.rightController) {
  91812. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91813. }
  91814. }
  91815. },
  91816. enumerable: true,
  91817. configurable: true
  91818. });
  91819. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  91820. /**
  91821. * If the ray of the gaze should be displayed.
  91822. */
  91823. get: function () {
  91824. return this._displayGaze;
  91825. },
  91826. /**
  91827. * Sets if the ray of the gaze should be displayed.
  91828. */
  91829. set: function (value) {
  91830. this._displayGaze = value;
  91831. if (!value) {
  91832. this._cameraGazer._gazeTracker.isVisible = false;
  91833. if (this.leftController) {
  91834. this.leftController._gazeTracker.isVisible = false;
  91835. }
  91836. if (this.rightController) {
  91837. this.rightController._gazeTracker.isVisible = false;
  91838. }
  91839. }
  91840. },
  91841. enumerable: true,
  91842. configurable: true
  91843. });
  91844. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  91845. /**
  91846. * If the ray of the LaserPointer should be displayed.
  91847. */
  91848. get: function () {
  91849. return this._displayLaserPointer;
  91850. },
  91851. /**
  91852. * Sets if the ray of the LaserPointer should be displayed.
  91853. */
  91854. set: function (value) {
  91855. this._displayLaserPointer = value;
  91856. if (!value) {
  91857. if (this.rightController) {
  91858. this.rightController._deactivatePointer();
  91859. this.rightController._gazeTracker.isVisible = false;
  91860. }
  91861. if (this.leftController) {
  91862. this.leftController._deactivatePointer();
  91863. this.leftController._gazeTracker.isVisible = false;
  91864. }
  91865. }
  91866. else {
  91867. if (this.rightController) {
  91868. this.rightController._activatePointer();
  91869. }
  91870. if (this.leftController) {
  91871. this.leftController._activatePointer();
  91872. }
  91873. }
  91874. },
  91875. enumerable: true,
  91876. configurable: true
  91877. });
  91878. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  91879. /**
  91880. * The deviceOrientationCamera used as the camera when not in VR.
  91881. */
  91882. get: function () {
  91883. return this._deviceOrientationCamera;
  91884. },
  91885. enumerable: true,
  91886. configurable: true
  91887. });
  91888. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  91889. /**
  91890. * Based on the current WebVR support, returns the current VR camera used.
  91891. */
  91892. get: function () {
  91893. if (this._webVRready) {
  91894. return this._webVRCamera;
  91895. }
  91896. else {
  91897. return this._scene.activeCamera;
  91898. }
  91899. },
  91900. enumerable: true,
  91901. configurable: true
  91902. });
  91903. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  91904. /**
  91905. * The webVRCamera which is used when in VR.
  91906. */
  91907. get: function () {
  91908. return this._webVRCamera;
  91909. },
  91910. enumerable: true,
  91911. configurable: true
  91912. });
  91913. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  91914. /**
  91915. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  91916. */
  91917. get: function () {
  91918. return this._vrDeviceOrientationCamera;
  91919. },
  91920. enumerable: true,
  91921. configurable: true
  91922. });
  91923. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  91924. get: function () {
  91925. var result = this._cameraGazer._teleportationRequestInitiated
  91926. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  91927. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  91928. return result;
  91929. },
  91930. enumerable: true,
  91931. configurable: true
  91932. });
  91933. // Raised when one of the controller has loaded successfully its associated default mesh
  91934. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  91935. if (this.leftController && this.leftController.webVRController == webVRController) {
  91936. if (webVRController.mesh) {
  91937. this.leftController._setLaserPointerParent(webVRController.mesh);
  91938. }
  91939. }
  91940. if (this.rightController && this.rightController.webVRController == webVRController) {
  91941. if (webVRController.mesh) {
  91942. this.rightController._setLaserPointerParent(webVRController.mesh);
  91943. }
  91944. }
  91945. try {
  91946. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  91947. }
  91948. catch (err) {
  91949. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  91950. }
  91951. };
  91952. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  91953. /**
  91954. * Gets a value indicating if we are currently in VR mode.
  91955. */
  91956. get: function () {
  91957. return this._webVRpresenting || this._fullscreenVRpresenting;
  91958. },
  91959. enumerable: true,
  91960. configurable: true
  91961. });
  91962. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  91963. var vrDisplay = this._scene.getEngine().getVRDevice();
  91964. if (vrDisplay) {
  91965. var wasPresenting = this._webVRpresenting;
  91966. // A VR display is connected
  91967. this._webVRpresenting = vrDisplay.isPresenting;
  91968. if (wasPresenting && !this._webVRpresenting)
  91969. this.exitVR();
  91970. }
  91971. else {
  91972. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  91973. }
  91974. this.updateButtonVisibility();
  91975. };
  91976. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  91977. this._webVRsupported = eventArgs.vrSupported;
  91978. this._webVRready = !!eventArgs.vrDisplay;
  91979. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  91980. this.updateButtonVisibility();
  91981. };
  91982. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  91983. if (this._canvas && !this._useCustomVRButton) {
  91984. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  91985. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  91986. }
  91987. };
  91988. VRExperienceHelper.prototype.displayVRButton = function () {
  91989. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  91990. document.body.appendChild(this._btnVR);
  91991. this._btnVRDisplayed = true;
  91992. }
  91993. };
  91994. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  91995. if (!this._btnVR || this._useCustomVRButton) {
  91996. return;
  91997. }
  91998. this._btnVR.className = "babylonVRicon";
  91999. if (this.isInVRMode) {
  92000. this._btnVR.className += " vrdisplaypresenting";
  92001. }
  92002. else {
  92003. if (this._webVRready)
  92004. this._btnVR.className += " vrdisplayready";
  92005. if (this._webVRsupported)
  92006. this._btnVR.className += " vrdisplaysupported";
  92007. if (this._webVRrequesting)
  92008. this._btnVR.className += " vrdisplayrequesting";
  92009. }
  92010. };
  92011. /**
  92012. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92013. * Otherwise, will use the fullscreen API.
  92014. */
  92015. VRExperienceHelper.prototype.enterVR = function () {
  92016. if (this.onEnteringVRObservable) {
  92017. try {
  92018. this.onEnteringVRObservable.notifyObservers(this);
  92019. }
  92020. catch (err) {
  92021. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92022. }
  92023. }
  92024. if (this._scene.activeCamera) {
  92025. this._position = this._scene.activeCamera.position.clone();
  92026. // make sure that we return to the last active camera
  92027. this._existingCamera = this._scene.activeCamera;
  92028. }
  92029. if (this._webVRrequesting)
  92030. return;
  92031. // If WebVR is supported and a headset is connected
  92032. if (this._webVRready) {
  92033. if (!this._webVRpresenting) {
  92034. this._webVRCamera.position = this._position;
  92035. this._scene.activeCamera = this._webVRCamera;
  92036. }
  92037. }
  92038. else if (this._vrDeviceOrientationCamera) {
  92039. this._vrDeviceOrientationCamera.position = this._position;
  92040. if (this._scene.activeCamera) {
  92041. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92042. }
  92043. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92044. this._scene.getEngine().switchFullscreen(true);
  92045. this.updateButtonVisibility();
  92046. }
  92047. if (this._scene.activeCamera && this._canvas) {
  92048. this._scene.activeCamera.attachControl(this._canvas);
  92049. }
  92050. if (this._interactionsEnabled) {
  92051. this._scene.registerBeforeRender(this.beforeRender);
  92052. }
  92053. };
  92054. /**
  92055. * Attempt to exit VR, or fullscreen.
  92056. */
  92057. VRExperienceHelper.prototype.exitVR = function () {
  92058. if (this.onExitingVRObservable) {
  92059. try {
  92060. this.onExitingVRObservable.notifyObservers(this);
  92061. }
  92062. catch (err) {
  92063. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92064. }
  92065. }
  92066. if (this._webVRpresenting) {
  92067. this._scene.getEngine().disableVR();
  92068. }
  92069. if (this._scene.activeCamera) {
  92070. this._position = this._scene.activeCamera.position.clone();
  92071. }
  92072. if (this._deviceOrientationCamera) {
  92073. this._deviceOrientationCamera.position = this._position;
  92074. this._scene.activeCamera = this._deviceOrientationCamera;
  92075. if (this._canvas) {
  92076. this._scene.activeCamera.attachControl(this._canvas);
  92077. }
  92078. }
  92079. else if (this._existingCamera) {
  92080. this._existingCamera.position = this._position;
  92081. this._scene.activeCamera = this._existingCamera;
  92082. }
  92083. this.updateButtonVisibility();
  92084. if (this._interactionsEnabled) {
  92085. this._scene.unregisterBeforeRender(this.beforeRender);
  92086. }
  92087. // resize to update width and height when exiting vr exits fullscreen
  92088. this._scene.getEngine().resize();
  92089. };
  92090. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92091. /**
  92092. * The position of the vr experience helper.
  92093. */
  92094. get: function () {
  92095. return this._position;
  92096. },
  92097. /**
  92098. * Sets the position of the vr experience helper.
  92099. */
  92100. set: function (value) {
  92101. this._position = value;
  92102. if (this._scene.activeCamera) {
  92103. this._scene.activeCamera.position = value;
  92104. }
  92105. },
  92106. enumerable: true,
  92107. configurable: true
  92108. });
  92109. /**
  92110. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92111. */
  92112. VRExperienceHelper.prototype.enableInteractions = function () {
  92113. var _this = this;
  92114. if (!this._interactionsEnabled) {
  92115. this._interactionsRequested = true;
  92116. if (this.leftController) {
  92117. this._enableInteractionOnController(this.leftController);
  92118. }
  92119. if (this.rightController) {
  92120. this._enableInteractionOnController(this.rightController);
  92121. }
  92122. this.raySelectionPredicate = function (mesh) {
  92123. return mesh.isVisible;
  92124. };
  92125. this.meshSelectionPredicate = function (mesh) {
  92126. return true;
  92127. };
  92128. this._raySelectionPredicate = function (mesh) {
  92129. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92130. && mesh.name.indexOf("teleportationTarget") === -1
  92131. && mesh.name.indexOf("torusTeleportation") === -1
  92132. && mesh.name.indexOf("laserPointer") === -1)) {
  92133. return _this.raySelectionPredicate(mesh);
  92134. }
  92135. return false;
  92136. };
  92137. this._interactionsEnabled = true;
  92138. }
  92139. };
  92140. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  92141. get: function () {
  92142. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  92143. },
  92144. enumerable: true,
  92145. configurable: true
  92146. });
  92147. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92148. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92149. if (this._floorMeshesCollection[i].id === mesh.id) {
  92150. return true;
  92151. }
  92152. }
  92153. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92154. return true;
  92155. }
  92156. return false;
  92157. };
  92158. /**
  92159. * Adds a floor mesh to be used for teleportation.
  92160. * @param floorMesh the mesh to be used for teleportation.
  92161. */
  92162. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92163. if (!this._floorMeshesCollection) {
  92164. return;
  92165. }
  92166. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92167. return;
  92168. }
  92169. this._floorMeshesCollection.push(floorMesh);
  92170. };
  92171. /**
  92172. * Removes a floor mesh from being used for teleportation.
  92173. * @param floorMesh the mesh to be removed.
  92174. */
  92175. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92176. if (!this._floorMeshesCollection) {
  92177. return;
  92178. }
  92179. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92180. if (meshIndex !== -1) {
  92181. this._floorMeshesCollection.splice(meshIndex, 1);
  92182. }
  92183. };
  92184. /**
  92185. * Enables interactions and teleportation using the VR controllers and gaze.
  92186. * @param vrTeleportationOptions options to modify teleportation behavior.
  92187. */
  92188. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92189. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92190. if (!this._teleportationInitialized) {
  92191. this._teleportationRequested = true;
  92192. this.enableInteractions();
  92193. if (vrTeleportationOptions.floorMeshName) {
  92194. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92195. }
  92196. if (vrTeleportationOptions.floorMeshes) {
  92197. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92198. }
  92199. if (this.leftController != null) {
  92200. this._enableTeleportationOnController(this.leftController);
  92201. }
  92202. if (this.rightController != null) {
  92203. this._enableTeleportationOnController(this.rightController);
  92204. }
  92205. // Creates an image processing post process for the vignette not relying
  92206. // on the main scene configuration for image processing to reduce setup and spaces
  92207. // (gamma/linear) conflicts.
  92208. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92209. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92210. imageProcessingConfiguration.vignetteEnabled = true;
  92211. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92212. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92213. this._teleportationInitialized = true;
  92214. if (this._isDefaultTeleportationTarget) {
  92215. this._createTeleportationCircles();
  92216. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92217. }
  92218. }
  92219. };
  92220. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92221. var _this = this;
  92222. var controllerMesh = controller.webVRController.mesh;
  92223. if (controllerMesh) {
  92224. controller._interactionsEnabled = true;
  92225. controller._activatePointer();
  92226. if (this.webVROptions.laserToggle) {
  92227. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92228. // Enabling / disabling laserPointer
  92229. if (_this._displayLaserPointer && stateObject.value === 1) {
  92230. if (controller._activePointer) {
  92231. controller._deactivatePointer();
  92232. }
  92233. else {
  92234. controller._activatePointer();
  92235. }
  92236. if (_this.displayGaze) {
  92237. controller._gazeTracker.isVisible = controller._activePointer;
  92238. }
  92239. }
  92240. });
  92241. }
  92242. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92243. var gazer = controller;
  92244. if (_this._noControllerIsActive) {
  92245. gazer = _this._cameraGazer;
  92246. }
  92247. if (!gazer._pointerDownOnMeshAsked) {
  92248. if (stateObject.value > _this._padSensibilityUp) {
  92249. gazer._selectionPointerDown();
  92250. }
  92251. }
  92252. else if (stateObject.value < _this._padSensibilityDown) {
  92253. gazer._selectionPointerUp();
  92254. }
  92255. });
  92256. }
  92257. };
  92258. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92259. // Dont teleport if another gaze already requested teleportation
  92260. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92261. return;
  92262. }
  92263. if (!gazer._teleportationRequestInitiated) {
  92264. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92265. gazer._activatePointer();
  92266. gazer._teleportationRequestInitiated = true;
  92267. }
  92268. }
  92269. else {
  92270. // Listening to the proper controller values changes to confirm teleportation
  92271. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92272. if (this._teleportActive) {
  92273. this._teleportCamera(this._haloCenter);
  92274. }
  92275. gazer._teleportationRequestInitiated = false;
  92276. }
  92277. }
  92278. };
  92279. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92280. // Only rotate when user is not currently selecting a teleportation location
  92281. if (gazer._teleportationRequestInitiated) {
  92282. return;
  92283. }
  92284. if (!gazer._rotationLeftAsked) {
  92285. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92286. gazer._rotationLeftAsked = true;
  92287. if (this._rotationAllowed) {
  92288. this._rotateCamera(false);
  92289. }
  92290. }
  92291. }
  92292. else {
  92293. if (stateObject.x > -this._padSensibilityDown) {
  92294. gazer._rotationLeftAsked = false;
  92295. }
  92296. }
  92297. if (!gazer._rotationRightAsked) {
  92298. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92299. gazer._rotationRightAsked = true;
  92300. if (this._rotationAllowed) {
  92301. this._rotateCamera(true);
  92302. }
  92303. }
  92304. }
  92305. else {
  92306. if (stateObject.x < this._padSensibilityDown) {
  92307. gazer._rotationRightAsked = false;
  92308. }
  92309. }
  92310. };
  92311. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92312. // Only teleport backwards when user is not currently selecting a teleportation location
  92313. if (gazer._teleportationRequestInitiated) {
  92314. return;
  92315. }
  92316. // Teleport backwards
  92317. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92318. if (!gazer._teleportationBackRequestInitiated) {
  92319. if (!this.currentVRCamera) {
  92320. return;
  92321. }
  92322. // Get rotation and position of the current camera
  92323. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92324. var position = this.currentVRCamera.position;
  92325. // If the camera has device position, use that instead
  92326. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92327. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92328. position = this.currentVRCamera.devicePosition;
  92329. }
  92330. // Get matrix with only the y rotation of the device rotation
  92331. rotation.toEulerAnglesToRef(this._workingVector);
  92332. this._workingVector.z = 0;
  92333. this._workingVector.x = 0;
  92334. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92335. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92336. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92337. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92338. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92339. var ray = new BABYLON.Ray(position, this._workingVector);
  92340. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92341. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92342. this._teleportCamera(hit.pickedPoint);
  92343. }
  92344. gazer._teleportationBackRequestInitiated = true;
  92345. }
  92346. }
  92347. else {
  92348. gazer._teleportationBackRequestInitiated = false;
  92349. }
  92350. };
  92351. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92352. var _this = this;
  92353. var controllerMesh = controller.webVRController.mesh;
  92354. if (controllerMesh) {
  92355. if (!controller._interactionsEnabled) {
  92356. this._enableInteractionOnController(controller);
  92357. }
  92358. controller._interactionsEnabled = true;
  92359. controller._teleportationEnabled = true;
  92360. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92361. controller._dpadPressed = false;
  92362. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  92363. controller._dpadPressed = stateObject.pressed;
  92364. if (!controller._dpadPressed) {
  92365. controller._rotationLeftAsked = false;
  92366. controller._rotationRightAsked = false;
  92367. controller._teleportationBackRequestInitiated = false;
  92368. }
  92369. });
  92370. }
  92371. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  92372. if (_this.teleportationEnabled) {
  92373. _this._checkTeleportBackwards(stateObject, controller);
  92374. _this._checkTeleportWithRay(stateObject, controller);
  92375. }
  92376. _this._checkRotate(stateObject, controller);
  92377. });
  92378. }
  92379. };
  92380. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92381. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92382. this._teleportationTarget.isPickable = false;
  92383. var length = 512;
  92384. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92385. dynamicTexture.hasAlpha = true;
  92386. var context = dynamicTexture.getContext();
  92387. var centerX = length / 2;
  92388. var centerY = length / 2;
  92389. var radius = 200;
  92390. context.beginPath();
  92391. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  92392. context.fillStyle = this._teleportationFillColor;
  92393. context.fill();
  92394. context.lineWidth = 10;
  92395. context.strokeStyle = this._teleportationBorderColor;
  92396. context.stroke();
  92397. context.closePath();
  92398. dynamicTexture.update();
  92399. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  92400. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  92401. this._teleportationTarget.material = teleportationCircleMaterial;
  92402. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  92403. torus.isPickable = false;
  92404. torus.parent = this._teleportationTarget;
  92405. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92406. var keys = [];
  92407. keys.push({
  92408. frame: 0,
  92409. value: 0
  92410. });
  92411. keys.push({
  92412. frame: 30,
  92413. value: 0.4
  92414. });
  92415. keys.push({
  92416. frame: 60,
  92417. value: 0
  92418. });
  92419. animationInnerCircle.setKeys(keys);
  92420. var easingFunction = new BABYLON.SineEase();
  92421. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92422. animationInnerCircle.setEasingFunction(easingFunction);
  92423. torus.animations = [];
  92424. torus.animations.push(animationInnerCircle);
  92425. this._scene.beginAnimation(torus, 0, 60, true);
  92426. this._hideTeleportationTarget();
  92427. };
  92428. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  92429. this._teleportActive = true;
  92430. if (this._teleportationInitialized) {
  92431. this._teleportationTarget.isVisible = true;
  92432. if (this._isDefaultTeleportationTarget) {
  92433. this._teleportationTarget.getChildren()[0].isVisible = true;
  92434. }
  92435. }
  92436. };
  92437. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  92438. this._teleportActive = false;
  92439. if (this._teleportationInitialized) {
  92440. this._teleportationTarget.isVisible = false;
  92441. if (this._isDefaultTeleportationTarget) {
  92442. this._teleportationTarget.getChildren()[0].isVisible = false;
  92443. }
  92444. }
  92445. };
  92446. VRExperienceHelper.prototype._rotateCamera = function (right) {
  92447. var _this = this;
  92448. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92449. return;
  92450. }
  92451. if (right) {
  92452. this._rotationAngle++;
  92453. }
  92454. else {
  92455. this._rotationAngle--;
  92456. }
  92457. this.currentVRCamera.animations = [];
  92458. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  92459. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92460. var animationRotationKeys = [];
  92461. animationRotationKeys.push({
  92462. frame: 0,
  92463. value: this.currentVRCamera.rotationQuaternion
  92464. });
  92465. animationRotationKeys.push({
  92466. frame: 6,
  92467. value: target
  92468. });
  92469. animationRotation.setKeys(animationRotationKeys);
  92470. animationRotation.setEasingFunction(this._circleEase);
  92471. this.currentVRCamera.animations.push(animationRotation);
  92472. this._postProcessMove.animations = [];
  92473. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92474. var vignetteWeightKeys = [];
  92475. vignetteWeightKeys.push({
  92476. frame: 0,
  92477. value: 0
  92478. });
  92479. vignetteWeightKeys.push({
  92480. frame: 3,
  92481. value: 4
  92482. });
  92483. vignetteWeightKeys.push({
  92484. frame: 6,
  92485. value: 0
  92486. });
  92487. animationPP.setKeys(vignetteWeightKeys);
  92488. animationPP.setEasingFunction(this._circleEase);
  92489. this._postProcessMove.animations.push(animationPP);
  92490. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92491. var vignetteStretchKeys = [];
  92492. vignetteStretchKeys.push({
  92493. frame: 0,
  92494. value: 0
  92495. });
  92496. vignetteStretchKeys.push({
  92497. frame: 3,
  92498. value: 10
  92499. });
  92500. vignetteStretchKeys.push({
  92501. frame: 6,
  92502. value: 0
  92503. });
  92504. animationPP2.setKeys(vignetteStretchKeys);
  92505. animationPP2.setEasingFunction(this._circleEase);
  92506. this._postProcessMove.animations.push(animationPP2);
  92507. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92508. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92509. this._postProcessMove.samples = 4;
  92510. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92511. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  92512. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92513. });
  92514. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  92515. };
  92516. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  92517. if (hit.pickedPoint) {
  92518. if (gazer._teleportationRequestInitiated) {
  92519. this._displayTeleportationTarget();
  92520. this._haloCenter.copyFrom(hit.pickedPoint);
  92521. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  92522. }
  92523. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  92524. if (pickNormal) {
  92525. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92526. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92527. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  92528. }
  92529. this._teleportationTarget.position.y += 0.1;
  92530. }
  92531. };
  92532. VRExperienceHelper.prototype._teleportCamera = function (location) {
  92533. var _this = this;
  92534. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92535. return;
  92536. }
  92537. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  92538. // offset of the headset from the anchor.
  92539. if (this.webVRCamera.leftCamera) {
  92540. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  92541. this._workingVector.subtractInPlace(this.webVRCamera.position);
  92542. location.subtractToRef(this._workingVector, this._workingVector);
  92543. }
  92544. else {
  92545. this._workingVector.copyFrom(location);
  92546. }
  92547. // Add height to account for user's height offset
  92548. if (this.isInVRMode) {
  92549. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  92550. }
  92551. else {
  92552. this._workingVector.y += this._defaultHeight;
  92553. }
  92554. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  92555. // Create animation from the camera's position to the new location
  92556. this.currentVRCamera.animations = [];
  92557. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92558. var animationCameraTeleportationKeys = [{
  92559. frame: 0,
  92560. value: this.currentVRCamera.position
  92561. },
  92562. {
  92563. frame: 11,
  92564. value: this._workingVector
  92565. }
  92566. ];
  92567. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  92568. animationCameraTeleportation.setEasingFunction(this._circleEase);
  92569. this.currentVRCamera.animations.push(animationCameraTeleportation);
  92570. this._postProcessMove.animations = [];
  92571. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92572. var vignetteWeightKeys = [];
  92573. vignetteWeightKeys.push({
  92574. frame: 0,
  92575. value: 0
  92576. });
  92577. vignetteWeightKeys.push({
  92578. frame: 5,
  92579. value: 8
  92580. });
  92581. vignetteWeightKeys.push({
  92582. frame: 11,
  92583. value: 0
  92584. });
  92585. animationPP.setKeys(vignetteWeightKeys);
  92586. this._postProcessMove.animations.push(animationPP);
  92587. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92588. var vignetteStretchKeys = [];
  92589. vignetteStretchKeys.push({
  92590. frame: 0,
  92591. value: 0
  92592. });
  92593. vignetteStretchKeys.push({
  92594. frame: 5,
  92595. value: 10
  92596. });
  92597. vignetteStretchKeys.push({
  92598. frame: 11,
  92599. value: 0
  92600. });
  92601. animationPP2.setKeys(vignetteStretchKeys);
  92602. this._postProcessMove.animations.push(animationPP2);
  92603. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92604. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92605. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92606. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  92607. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92608. });
  92609. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  92610. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  92611. });
  92612. this._hideTeleportationTarget();
  92613. };
  92614. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  92615. if (normal) {
  92616. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  92617. if (angle < Math.PI / 2) {
  92618. normal.scaleInPlace(-1);
  92619. }
  92620. }
  92621. return normal;
  92622. };
  92623. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  92624. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92625. return;
  92626. }
  92627. var ray = gazer._getForwardRay(this._rayLength);
  92628. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92629. if (hit) {
  92630. // Populate the contrllers mesh that can be used for drag/drop
  92631. if (gazer._laserPointer) {
  92632. hit.originMesh = gazer._laserPointer.parent;
  92633. }
  92634. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  92635. }
  92636. gazer._currentHit = hit;
  92637. // Moving the gazeTracker on the mesh face targetted
  92638. if (hit && hit.pickedPoint) {
  92639. if (this._displayGaze) {
  92640. var multiplier = 1;
  92641. gazer._gazeTracker.isVisible = true;
  92642. if (gazer._isActionableMesh) {
  92643. multiplier = 3;
  92644. }
  92645. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  92646. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  92647. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  92648. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  92649. // To avoid z-fighting
  92650. var deltaFighting = 0.002;
  92651. if (pickNormal) {
  92652. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92653. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92654. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  92655. }
  92656. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  92657. if (gazer._gazeTracker.position.x < 0) {
  92658. gazer._gazeTracker.position.x += deltaFighting;
  92659. }
  92660. else {
  92661. gazer._gazeTracker.position.x -= deltaFighting;
  92662. }
  92663. if (gazer._gazeTracker.position.y < 0) {
  92664. gazer._gazeTracker.position.y += deltaFighting;
  92665. }
  92666. else {
  92667. gazer._gazeTracker.position.y -= deltaFighting;
  92668. }
  92669. if (gazer._gazeTracker.position.z < 0) {
  92670. gazer._gazeTracker.position.z += deltaFighting;
  92671. }
  92672. else {
  92673. gazer._gazeTracker.position.z -= deltaFighting;
  92674. }
  92675. }
  92676. // Changing the size of the laser pointer based on the distance from the targetted point
  92677. gazer._updatePointerDistance(hit.distance);
  92678. }
  92679. else {
  92680. gazer._updatePointerDistance();
  92681. gazer._gazeTracker.isVisible = false;
  92682. }
  92683. if (hit && hit.pickedMesh) {
  92684. // The object selected is the floor, we're in a teleportation scenario
  92685. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  92686. // Moving the teleportation area to this targetted point
  92687. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  92688. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  92689. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92690. }
  92691. gazer._currentMeshSelected = null;
  92692. if (gazer._teleportationRequestInitiated) {
  92693. this._moveTeleportationSelectorTo(hit, gazer, ray);
  92694. }
  92695. return;
  92696. }
  92697. // If not, we're in a selection scenario
  92698. //this._teleportationAllowed = false;
  92699. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  92700. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  92701. this.onNewMeshPicked.notifyObservers(hit);
  92702. gazer._currentMeshSelected = hit.pickedMesh;
  92703. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  92704. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  92705. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  92706. gazer._isActionableMesh = true;
  92707. }
  92708. else {
  92709. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92710. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92711. gazer._isActionableMesh = false;
  92712. }
  92713. try {
  92714. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  92715. }
  92716. catch (err) {
  92717. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  92718. }
  92719. }
  92720. else {
  92721. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92722. gazer._currentMeshSelected = null;
  92723. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92724. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92725. }
  92726. }
  92727. }
  92728. else {
  92729. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92730. gazer._currentMeshSelected = null;
  92731. //this._teleportationAllowed = false;
  92732. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92733. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92734. }
  92735. };
  92736. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  92737. if (mesh) {
  92738. this.onSelectedMeshUnselected.notifyObservers(mesh);
  92739. }
  92740. };
  92741. /**
  92742. * Sets the color of the laser ray from the vr controllers.
  92743. * @param color new color for the ray.
  92744. */
  92745. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  92746. if (this.leftController) {
  92747. this.leftController._setLaserPointerColor(color);
  92748. }
  92749. if (this.rightController) {
  92750. this.rightController._setLaserPointerColor(color);
  92751. }
  92752. };
  92753. /**
  92754. * Sets the color of the ray from the vr headsets gaze.
  92755. * @param color new color for the ray.
  92756. */
  92757. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  92758. if (!this._cameraGazer._gazeTracker.material) {
  92759. return;
  92760. }
  92761. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  92762. if (this.leftController) {
  92763. this.leftController._gazeTracker.material.emissiveColor = color;
  92764. }
  92765. if (this.rightController) {
  92766. this.rightController._gazeTracker.material.emissiveColor = color;
  92767. }
  92768. };
  92769. /**
  92770. * Exits VR and disposes of the vr experience helper
  92771. */
  92772. VRExperienceHelper.prototype.dispose = function () {
  92773. if (this.isInVRMode) {
  92774. this.exitVR();
  92775. }
  92776. if (this._postProcessMove) {
  92777. this._postProcessMove.dispose();
  92778. }
  92779. if (this._webVRCamera) {
  92780. this._webVRCamera.dispose();
  92781. }
  92782. if (this._vrDeviceOrientationCamera) {
  92783. this._vrDeviceOrientationCamera.dispose();
  92784. }
  92785. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  92786. document.body.removeChild(this._btnVR);
  92787. }
  92788. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  92789. this._deviceOrientationCamera.dispose();
  92790. }
  92791. if (this._cameraGazer) {
  92792. this._cameraGazer.dispose();
  92793. }
  92794. if (this.leftController) {
  92795. this.leftController.dispose();
  92796. }
  92797. if (this.rightController) {
  92798. this.rightController.dispose();
  92799. }
  92800. if (this._teleportationTarget) {
  92801. this._teleportationTarget.dispose();
  92802. }
  92803. this._floorMeshesCollection = [];
  92804. document.removeEventListener("keydown", this._onKeyDown);
  92805. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92806. window.removeEventListener("resize", this._onResize);
  92807. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  92808. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  92809. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  92810. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  92811. document.onmsfullscreenchange = null;
  92812. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  92813. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  92814. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  92815. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92816. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  92817. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  92818. this._scene.unregisterBeforeRender(this.beforeRender);
  92819. };
  92820. /**
  92821. * Gets the name of the VRExperienceHelper class
  92822. * @returns "VRExperienceHelper"
  92823. */
  92824. VRExperienceHelper.prototype.getClassName = function () {
  92825. return "VRExperienceHelper";
  92826. };
  92827. return VRExperienceHelper;
  92828. }());
  92829. BABYLON.VRExperienceHelper = VRExperienceHelper;
  92830. })(BABYLON || (BABYLON = {}));
  92831. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  92832. // Mainly based on these 2 articles :
  92833. // 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
  92834. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  92835. var BABYLON;
  92836. (function (BABYLON) {
  92837. /**
  92838. * Defines the potential axis of a Joystick
  92839. */
  92840. var JoystickAxis;
  92841. (function (JoystickAxis) {
  92842. /** X axis */
  92843. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  92844. /** Y axis */
  92845. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  92846. /** Z axis */
  92847. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  92848. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  92849. /**
  92850. * Class used to define virtual joystick (used in touch mode)
  92851. */
  92852. var VirtualJoystick = /** @class */ (function () {
  92853. /**
  92854. * Creates a new virtual joystick
  92855. * @param leftJoystick defines that the joystick is for left hand (false by default)
  92856. */
  92857. function VirtualJoystick(leftJoystick) {
  92858. var _this = this;
  92859. if (leftJoystick) {
  92860. this._leftJoystick = true;
  92861. }
  92862. else {
  92863. this._leftJoystick = false;
  92864. }
  92865. VirtualJoystick._globalJoystickIndex++;
  92866. // By default left & right arrow keys are moving the X
  92867. // and up & down keys are moving the Y
  92868. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92869. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92870. this.reverseLeftRight = false;
  92871. this.reverseUpDown = false;
  92872. // collections of pointers
  92873. this._touches = new BABYLON.StringDictionary();
  92874. this.deltaPosition = BABYLON.Vector3.Zero();
  92875. this._joystickSensibility = 25;
  92876. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92877. this._onResize = function (evt) {
  92878. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92879. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92880. if (VirtualJoystick.vjCanvas) {
  92881. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  92882. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  92883. }
  92884. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  92885. };
  92886. // injecting a canvas element on top of the canvas 3D game
  92887. if (!VirtualJoystick.vjCanvas) {
  92888. window.addEventListener("resize", this._onResize, false);
  92889. VirtualJoystick.vjCanvas = document.createElement("canvas");
  92890. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92891. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92892. VirtualJoystick.vjCanvas.width = window.innerWidth;
  92893. VirtualJoystick.vjCanvas.height = window.innerHeight;
  92894. VirtualJoystick.vjCanvas.style.width = "100%";
  92895. VirtualJoystick.vjCanvas.style.height = "100%";
  92896. VirtualJoystick.vjCanvas.style.position = "absolute";
  92897. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  92898. VirtualJoystick.vjCanvas.style.top = "0px";
  92899. VirtualJoystick.vjCanvas.style.left = "0px";
  92900. VirtualJoystick.vjCanvas.style.zIndex = "5";
  92901. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  92902. // Support for jQuery PEP polyfill
  92903. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  92904. var context = VirtualJoystick.vjCanvas.getContext('2d');
  92905. if (!context) {
  92906. throw new Error("Unable to create canvas for virtual joystick");
  92907. }
  92908. VirtualJoystick.vjCanvasContext = context;
  92909. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  92910. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92911. document.body.appendChild(VirtualJoystick.vjCanvas);
  92912. }
  92913. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  92914. this.pressed = false;
  92915. // default joystick color
  92916. this._joystickColor = "cyan";
  92917. this._joystickPointerID = -1;
  92918. // current joystick position
  92919. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  92920. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  92921. // origin joystick position
  92922. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  92923. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  92924. this._onPointerDownHandlerRef = function (evt) {
  92925. _this._onPointerDown(evt);
  92926. };
  92927. this._onPointerMoveHandlerRef = function (evt) {
  92928. _this._onPointerMove(evt);
  92929. };
  92930. this._onPointerUpHandlerRef = function (evt) {
  92931. _this._onPointerUp(evt);
  92932. };
  92933. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  92934. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  92935. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  92936. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  92937. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  92938. evt.preventDefault(); // Disables system menu
  92939. }, false);
  92940. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92941. }
  92942. /**
  92943. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  92944. * @param newJoystickSensibility defines the new sensibility
  92945. */
  92946. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  92947. this._joystickSensibility = newJoystickSensibility;
  92948. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92949. };
  92950. VirtualJoystick.prototype._onPointerDown = function (e) {
  92951. var positionOnScreenCondition;
  92952. e.preventDefault();
  92953. if (this._leftJoystick === true) {
  92954. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  92955. }
  92956. else {
  92957. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  92958. }
  92959. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  92960. // First contact will be dedicated to the virtual joystick
  92961. this._joystickPointerID = e.pointerId;
  92962. this._joystickPointerStartPos.x = e.clientX;
  92963. this._joystickPointerStartPos.y = e.clientY;
  92964. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  92965. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  92966. this._deltaJoystickVector.x = 0;
  92967. this._deltaJoystickVector.y = 0;
  92968. this.pressed = true;
  92969. this._touches.add(e.pointerId.toString(), e);
  92970. }
  92971. else {
  92972. // You can only trigger the action buttons with a joystick declared
  92973. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  92974. this._action();
  92975. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  92976. }
  92977. }
  92978. };
  92979. VirtualJoystick.prototype._onPointerMove = function (e) {
  92980. // If the current pointer is the one associated to the joystick (first touch contact)
  92981. if (this._joystickPointerID == e.pointerId) {
  92982. this._joystickPointerPos.x = e.clientX;
  92983. this._joystickPointerPos.y = e.clientY;
  92984. this._deltaJoystickVector = this._joystickPointerPos.clone();
  92985. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  92986. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  92987. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  92988. switch (this._axisTargetedByLeftAndRight) {
  92989. case JoystickAxis.X:
  92990. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  92991. break;
  92992. case JoystickAxis.Y:
  92993. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  92994. break;
  92995. case JoystickAxis.Z:
  92996. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  92997. break;
  92998. }
  92999. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93000. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93001. switch (this._axisTargetedByUpAndDown) {
  93002. case JoystickAxis.X:
  93003. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93004. break;
  93005. case JoystickAxis.Y:
  93006. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93007. break;
  93008. case JoystickAxis.Z:
  93009. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93010. break;
  93011. }
  93012. }
  93013. else {
  93014. var data = this._touches.get(e.pointerId.toString());
  93015. if (data) {
  93016. data.x = e.clientX;
  93017. data.y = e.clientY;
  93018. }
  93019. }
  93020. };
  93021. VirtualJoystick.prototype._onPointerUp = function (e) {
  93022. if (this._joystickPointerID == e.pointerId) {
  93023. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93024. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93025. this._joystickPointerID = -1;
  93026. this.pressed = false;
  93027. }
  93028. else {
  93029. var touch = this._touches.get(e.pointerId.toString());
  93030. if (touch) {
  93031. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93032. }
  93033. }
  93034. this._deltaJoystickVector.x = 0;
  93035. this._deltaJoystickVector.y = 0;
  93036. this._touches.remove(e.pointerId.toString());
  93037. };
  93038. /**
  93039. * Change the color of the virtual joystick
  93040. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93041. */
  93042. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93043. this._joystickColor = newColor;
  93044. };
  93045. /**
  93046. * Defines a callback to call when the joystick is touched
  93047. * @param action defines the callback
  93048. */
  93049. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93050. this._action = action;
  93051. };
  93052. /**
  93053. * Defines which axis you'd like to control for left & right
  93054. * @param axis defines the axis to use
  93055. */
  93056. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93057. switch (axis) {
  93058. case JoystickAxis.X:
  93059. case JoystickAxis.Y:
  93060. case JoystickAxis.Z:
  93061. this._axisTargetedByLeftAndRight = axis;
  93062. break;
  93063. default:
  93064. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93065. break;
  93066. }
  93067. };
  93068. /**
  93069. * Defines which axis you'd like to control for up & down
  93070. * @param axis defines the axis to use
  93071. */
  93072. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93073. switch (axis) {
  93074. case JoystickAxis.X:
  93075. case JoystickAxis.Y:
  93076. case JoystickAxis.Z:
  93077. this._axisTargetedByUpAndDown = axis;
  93078. break;
  93079. default:
  93080. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93081. break;
  93082. }
  93083. };
  93084. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93085. var _this = this;
  93086. if (this.pressed) {
  93087. this._touches.forEach(function (key, touch) {
  93088. if (touch.pointerId === _this._joystickPointerID) {
  93089. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93090. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93091. VirtualJoystick.vjCanvasContext.beginPath();
  93092. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93093. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93094. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93095. VirtualJoystick.vjCanvasContext.stroke();
  93096. VirtualJoystick.vjCanvasContext.closePath();
  93097. VirtualJoystick.vjCanvasContext.beginPath();
  93098. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93099. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93100. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93101. VirtualJoystick.vjCanvasContext.stroke();
  93102. VirtualJoystick.vjCanvasContext.closePath();
  93103. VirtualJoystick.vjCanvasContext.beginPath();
  93104. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93105. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93106. VirtualJoystick.vjCanvasContext.stroke();
  93107. VirtualJoystick.vjCanvasContext.closePath();
  93108. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93109. }
  93110. else {
  93111. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93112. VirtualJoystick.vjCanvasContext.beginPath();
  93113. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93114. VirtualJoystick.vjCanvasContext.beginPath();
  93115. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93116. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93117. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93118. VirtualJoystick.vjCanvasContext.stroke();
  93119. VirtualJoystick.vjCanvasContext.closePath();
  93120. touch.prevX = touch.x;
  93121. touch.prevY = touch.y;
  93122. }
  93123. ;
  93124. });
  93125. }
  93126. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93127. };
  93128. /**
  93129. * Release internal HTML canvas
  93130. */
  93131. VirtualJoystick.prototype.releaseCanvas = function () {
  93132. if (VirtualJoystick.vjCanvas) {
  93133. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93134. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93135. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93136. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  93137. window.removeEventListener("resize", this._onResize);
  93138. document.body.removeChild(VirtualJoystick.vjCanvas);
  93139. VirtualJoystick.vjCanvas = null;
  93140. }
  93141. };
  93142. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  93143. VirtualJoystick._globalJoystickIndex = 0;
  93144. return VirtualJoystick;
  93145. }());
  93146. BABYLON.VirtualJoystick = VirtualJoystick;
  93147. })(BABYLON || (BABYLON = {}));
  93148. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93149. var BABYLON;
  93150. (function (BABYLON) {
  93151. // We're mainly based on the logic defined into the FreeCamera code
  93152. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93153. __extends(VirtualJoysticksCamera, _super);
  93154. function VirtualJoysticksCamera(name, position, scene) {
  93155. var _this = _super.call(this, name, position, scene) || this;
  93156. _this.inputs.addVirtualJoystick();
  93157. return _this;
  93158. }
  93159. VirtualJoysticksCamera.prototype.getClassName = function () {
  93160. return "VirtualJoysticksCamera";
  93161. };
  93162. return VirtualJoysticksCamera;
  93163. }(BABYLON.FreeCamera));
  93164. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93165. })(BABYLON || (BABYLON = {}));
  93166. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93167. var BABYLON;
  93168. (function (BABYLON) {
  93169. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93170. function FreeCameraVirtualJoystickInput() {
  93171. }
  93172. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93173. return this._leftjoystick;
  93174. };
  93175. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93176. return this._rightjoystick;
  93177. };
  93178. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93179. if (this._leftjoystick) {
  93180. var camera = this.camera;
  93181. var speed = camera._computeLocalCameraSpeed() * 50;
  93182. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93183. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93184. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93185. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93186. if (!this._leftjoystick.pressed) {
  93187. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93188. }
  93189. if (!this._rightjoystick.pressed) {
  93190. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93191. }
  93192. }
  93193. };
  93194. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93195. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93196. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93197. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93198. this._leftjoystick.setJoystickSensibility(0.15);
  93199. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93200. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93201. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93202. this._rightjoystick.reverseUpDown = true;
  93203. this._rightjoystick.setJoystickSensibility(0.05);
  93204. this._rightjoystick.setJoystickColor("yellow");
  93205. };
  93206. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93207. this._leftjoystick.releaseCanvas();
  93208. this._rightjoystick.releaseCanvas();
  93209. };
  93210. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93211. return "FreeCameraVirtualJoystickInput";
  93212. };
  93213. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93214. return "virtualJoystick";
  93215. };
  93216. return FreeCameraVirtualJoystickInput;
  93217. }());
  93218. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93219. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93220. })(BABYLON || (BABYLON = {}));
  93221. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93222. var BABYLON;
  93223. (function (BABYLON) {
  93224. var SimplificationSettings = /** @class */ (function () {
  93225. function SimplificationSettings(quality, distance, optimizeMesh) {
  93226. this.quality = quality;
  93227. this.distance = distance;
  93228. this.optimizeMesh = optimizeMesh;
  93229. }
  93230. return SimplificationSettings;
  93231. }());
  93232. BABYLON.SimplificationSettings = SimplificationSettings;
  93233. var SimplificationQueue = /** @class */ (function () {
  93234. function SimplificationQueue() {
  93235. this.running = false;
  93236. this._simplificationArray = [];
  93237. }
  93238. SimplificationQueue.prototype.addTask = function (task) {
  93239. this._simplificationArray.push(task);
  93240. };
  93241. SimplificationQueue.prototype.executeNext = function () {
  93242. var task = this._simplificationArray.pop();
  93243. if (task) {
  93244. this.running = true;
  93245. this.runSimplification(task);
  93246. }
  93247. else {
  93248. this.running = false;
  93249. }
  93250. };
  93251. SimplificationQueue.prototype.runSimplification = function (task) {
  93252. var _this = this;
  93253. if (task.parallelProcessing) {
  93254. //parallel simplifier
  93255. task.settings.forEach(function (setting) {
  93256. var simplifier = _this.getSimplifier(task);
  93257. simplifier.simplify(setting, function (newMesh) {
  93258. task.mesh.addLODLevel(setting.distance, newMesh);
  93259. newMesh.isVisible = true;
  93260. //check if it is the last
  93261. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93262. //all done, run the success callback.
  93263. task.successCallback();
  93264. }
  93265. _this.executeNext();
  93266. });
  93267. });
  93268. }
  93269. else {
  93270. //single simplifier.
  93271. var simplifier = this.getSimplifier(task);
  93272. var runDecimation = function (setting, callback) {
  93273. simplifier.simplify(setting, function (newMesh) {
  93274. task.mesh.addLODLevel(setting.distance, newMesh);
  93275. newMesh.isVisible = true;
  93276. //run the next quality level
  93277. callback();
  93278. });
  93279. };
  93280. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93281. runDecimation(task.settings[loop.index], function () {
  93282. loop.executeNext();
  93283. });
  93284. }, function () {
  93285. //execution ended, run the success callback.
  93286. if (task.successCallback) {
  93287. task.successCallback();
  93288. }
  93289. _this.executeNext();
  93290. });
  93291. }
  93292. };
  93293. SimplificationQueue.prototype.getSimplifier = function (task) {
  93294. switch (task.simplificationType) {
  93295. case SimplificationType.QUADRATIC:
  93296. default:
  93297. return new QuadraticErrorSimplification(task.mesh);
  93298. }
  93299. };
  93300. return SimplificationQueue;
  93301. }());
  93302. BABYLON.SimplificationQueue = SimplificationQueue;
  93303. /**
  93304. * The implemented types of simplification
  93305. * At the moment only Quadratic Error Decimation is implemented
  93306. */
  93307. var SimplificationType;
  93308. (function (SimplificationType) {
  93309. /** Quadratic error decimation */
  93310. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93311. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93312. var DecimationTriangle = /** @class */ (function () {
  93313. function DecimationTriangle(vertices) {
  93314. this.vertices = vertices;
  93315. this.error = new Array(4);
  93316. this.deleted = false;
  93317. this.isDirty = false;
  93318. this.deletePending = false;
  93319. this.borderFactor = 0;
  93320. }
  93321. return DecimationTriangle;
  93322. }());
  93323. BABYLON.DecimationTriangle = DecimationTriangle;
  93324. var DecimationVertex = /** @class */ (function () {
  93325. function DecimationVertex(position, id) {
  93326. this.position = position;
  93327. this.id = id;
  93328. this.isBorder = true;
  93329. this.q = new QuadraticMatrix();
  93330. this.triangleCount = 0;
  93331. this.triangleStart = 0;
  93332. this.originalOffsets = [];
  93333. }
  93334. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93335. this.position.copyFrom(newPosition);
  93336. };
  93337. return DecimationVertex;
  93338. }());
  93339. BABYLON.DecimationVertex = DecimationVertex;
  93340. var QuadraticMatrix = /** @class */ (function () {
  93341. function QuadraticMatrix(data) {
  93342. this.data = new Array(10);
  93343. for (var i = 0; i < 10; ++i) {
  93344. if (data && data[i]) {
  93345. this.data[i] = data[i];
  93346. }
  93347. else {
  93348. this.data[i] = 0;
  93349. }
  93350. }
  93351. }
  93352. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93353. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93354. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93355. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93356. return det;
  93357. };
  93358. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93359. for (var i = 0; i < 10; ++i) {
  93360. this.data[i] += matrix.data[i];
  93361. }
  93362. };
  93363. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  93364. for (var i = 0; i < 10; ++i) {
  93365. this.data[i] += data[i];
  93366. }
  93367. };
  93368. QuadraticMatrix.prototype.add = function (matrix) {
  93369. var m = new QuadraticMatrix();
  93370. for (var i = 0; i < 10; ++i) {
  93371. m.data[i] = this.data[i] + matrix.data[i];
  93372. }
  93373. return m;
  93374. };
  93375. QuadraticMatrix.FromData = function (a, b, c, d) {
  93376. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93377. };
  93378. //returning an array to avoid garbage collection
  93379. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93380. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93381. };
  93382. return QuadraticMatrix;
  93383. }());
  93384. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93385. var Reference = /** @class */ (function () {
  93386. function Reference(vertexId, triangleId) {
  93387. this.vertexId = vertexId;
  93388. this.triangleId = triangleId;
  93389. }
  93390. return Reference;
  93391. }());
  93392. BABYLON.Reference = Reference;
  93393. /**
  93394. * An implementation of the Quadratic Error simplification algorithm.
  93395. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  93396. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  93397. * @author RaananW
  93398. */
  93399. var QuadraticErrorSimplification = /** @class */ (function () {
  93400. function QuadraticErrorSimplification(_mesh) {
  93401. this._mesh = _mesh;
  93402. this.syncIterations = 5000;
  93403. this.aggressiveness = 7;
  93404. this.decimationIterations = 100;
  93405. this.boundingBoxEpsilon = BABYLON.Epsilon;
  93406. }
  93407. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  93408. var _this = this;
  93409. this.initDecimatedMesh();
  93410. //iterating through the submeshes array, one after the other.
  93411. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  93412. _this.initWithMesh(loop.index, function () {
  93413. _this.runDecimation(settings, loop.index, function () {
  93414. loop.executeNext();
  93415. });
  93416. }, settings.optimizeMesh);
  93417. }, function () {
  93418. setTimeout(function () {
  93419. successCallback(_this._reconstructedMesh);
  93420. }, 0);
  93421. });
  93422. };
  93423. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  93424. var _this = this;
  93425. var targetCount = ~~(this.triangles.length * settings.quality);
  93426. var deletedTriangles = 0;
  93427. var triangleCount = this.triangles.length;
  93428. var iterationFunction = function (iteration, callback) {
  93429. setTimeout(function () {
  93430. if (iteration % 5 === 0) {
  93431. _this.updateMesh(iteration === 0);
  93432. }
  93433. for (var i = 0; i < _this.triangles.length; ++i) {
  93434. _this.triangles[i].isDirty = false;
  93435. }
  93436. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  93437. var trianglesIterator = function (i) {
  93438. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  93439. var t = _this.triangles[tIdx];
  93440. if (!t)
  93441. return;
  93442. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  93443. return;
  93444. }
  93445. for (var j = 0; j < 3; ++j) {
  93446. if (t.error[j] < threshold) {
  93447. var deleted0 = [];
  93448. var deleted1 = [];
  93449. var v0 = t.vertices[j];
  93450. var v1 = t.vertices[(j + 1) % 3];
  93451. if (v0.isBorder || v1.isBorder)
  93452. continue;
  93453. var p = BABYLON.Vector3.Zero();
  93454. var n = BABYLON.Vector3.Zero();
  93455. var uv = BABYLON.Vector2.Zero();
  93456. var color = new BABYLON.Color4(0, 0, 0, 1);
  93457. _this.calculateError(v0, v1, p, n, uv, color);
  93458. var delTr = new Array();
  93459. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  93460. continue;
  93461. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  93462. continue;
  93463. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  93464. continue;
  93465. var uniqueArray = new Array();
  93466. delTr.forEach(function (deletedT) {
  93467. if (uniqueArray.indexOf(deletedT) === -1) {
  93468. deletedT.deletePending = true;
  93469. uniqueArray.push(deletedT);
  93470. }
  93471. });
  93472. if (uniqueArray.length % 2 !== 0) {
  93473. continue;
  93474. }
  93475. v0.q = v1.q.add(v0.q);
  93476. v0.updatePosition(p);
  93477. var tStart = _this.references.length;
  93478. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  93479. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  93480. var tCount = _this.references.length - tStart;
  93481. if (tCount <= v0.triangleCount) {
  93482. if (tCount) {
  93483. for (var c = 0; c < tCount; c++) {
  93484. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  93485. }
  93486. }
  93487. }
  93488. else {
  93489. v0.triangleStart = tStart;
  93490. }
  93491. v0.triangleCount = tCount;
  93492. break;
  93493. }
  93494. }
  93495. };
  93496. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  93497. }, 0);
  93498. };
  93499. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  93500. if (triangleCount - deletedTriangles <= targetCount)
  93501. loop.breakLoop();
  93502. else {
  93503. iterationFunction(loop.index, function () {
  93504. loop.executeNext();
  93505. });
  93506. }
  93507. }, function () {
  93508. setTimeout(function () {
  93509. //reconstruct this part of the mesh
  93510. _this.reconstructMesh(submeshIndex);
  93511. successCallback();
  93512. }, 0);
  93513. });
  93514. };
  93515. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  93516. var _this = this;
  93517. this.vertices = [];
  93518. this.triangles = [];
  93519. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93520. var indices = this._mesh.getIndices();
  93521. var submesh = this._mesh.subMeshes[submeshIndex];
  93522. var findInVertices = function (positionToSearch) {
  93523. if (optimizeMesh) {
  93524. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  93525. if (_this.vertices[ii].position.equals(positionToSearch)) {
  93526. return _this.vertices[ii];
  93527. }
  93528. }
  93529. }
  93530. return null;
  93531. };
  93532. var vertexReferences = [];
  93533. var vertexInit = function (i) {
  93534. if (!positionData) {
  93535. return;
  93536. }
  93537. var offset = i + submesh.verticesStart;
  93538. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  93539. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  93540. vertex.originalOffsets.push(offset);
  93541. if (vertex.id === _this.vertices.length) {
  93542. _this.vertices.push(vertex);
  93543. }
  93544. vertexReferences.push(vertex.id);
  93545. };
  93546. //var totalVertices = mesh.getTotalVertices();
  93547. var totalVertices = submesh.verticesCount;
  93548. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  93549. var indicesInit = function (i) {
  93550. if (!indices) {
  93551. return;
  93552. }
  93553. var offset = (submesh.indexStart / 3) + i;
  93554. var pos = (offset * 3);
  93555. var i0 = indices[pos + 0];
  93556. var i1 = indices[pos + 1];
  93557. var i2 = indices[pos + 2];
  93558. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  93559. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  93560. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  93561. var triangle = new DecimationTriangle([v0, v1, v2]);
  93562. triangle.originalOffset = pos;
  93563. _this.triangles.push(triangle);
  93564. };
  93565. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  93566. _this.init(callback);
  93567. });
  93568. });
  93569. };
  93570. QuadraticErrorSimplification.prototype.init = function (callback) {
  93571. var _this = this;
  93572. var triangleInit1 = function (i) {
  93573. var t = _this.triangles[i];
  93574. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  93575. for (var j = 0; j < 3; j++) {
  93576. 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))));
  93577. }
  93578. };
  93579. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  93580. var triangleInit2 = function (i) {
  93581. var t = _this.triangles[i];
  93582. for (var j = 0; j < 3; ++j) {
  93583. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  93584. }
  93585. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93586. };
  93587. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  93588. callback();
  93589. });
  93590. });
  93591. };
  93592. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  93593. var newTriangles = [];
  93594. var i;
  93595. for (i = 0; i < this.vertices.length; ++i) {
  93596. this.vertices[i].triangleCount = 0;
  93597. }
  93598. var t;
  93599. var j;
  93600. for (i = 0; i < this.triangles.length; ++i) {
  93601. if (!this.triangles[i].deleted) {
  93602. t = this.triangles[i];
  93603. for (j = 0; j < 3; ++j) {
  93604. t.vertices[j].triangleCount = 1;
  93605. }
  93606. newTriangles.push(t);
  93607. }
  93608. }
  93609. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  93610. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  93611. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  93612. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  93613. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  93614. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93615. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  93616. var vertexCount = 0;
  93617. for (i = 0; i < this.vertices.length; ++i) {
  93618. var vertex = this.vertices[i];
  93619. vertex.id = vertexCount;
  93620. if (vertex.triangleCount) {
  93621. vertex.originalOffsets.forEach(function (originalOffset) {
  93622. if (!normalData) {
  93623. return;
  93624. }
  93625. newPositionData.push(vertex.position.x);
  93626. newPositionData.push(vertex.position.y);
  93627. newPositionData.push(vertex.position.z);
  93628. newNormalData.push(normalData[originalOffset * 3]);
  93629. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  93630. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  93631. if (uvs && uvs.length) {
  93632. newUVsData.push(uvs[(originalOffset * 2)]);
  93633. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  93634. }
  93635. else if (colorsData && colorsData.length) {
  93636. newColorsData.push(colorsData[(originalOffset * 4)]);
  93637. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  93638. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  93639. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  93640. }
  93641. ++vertexCount;
  93642. });
  93643. }
  93644. }
  93645. var startingIndex = this._reconstructedMesh.getTotalIndices();
  93646. var startingVertex = this._reconstructedMesh.getTotalVertices();
  93647. var submeshesArray = this._reconstructedMesh.subMeshes;
  93648. this._reconstructedMesh.subMeshes = [];
  93649. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  93650. var originalIndices = this._mesh.getIndices();
  93651. for (i = 0; i < newTriangles.length; ++i) {
  93652. t = newTriangles[i]; //now get the new referencing point for each vertex
  93653. [0, 1, 2].forEach(function (idx) {
  93654. var id = originalIndices[t.originalOffset + idx];
  93655. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  93656. if (offset < 0)
  93657. offset = 0;
  93658. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  93659. });
  93660. }
  93661. //overwriting the old vertex buffers and indices.
  93662. this._reconstructedMesh.setIndices(newIndicesArray);
  93663. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  93664. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  93665. if (newUVsData.length > 0)
  93666. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  93667. if (newColorsData.length > 0)
  93668. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  93669. //create submesh
  93670. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  93671. if (submeshIndex > 0) {
  93672. this._reconstructedMesh.subMeshes = [];
  93673. submeshesArray.forEach(function (submesh) {
  93674. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  93675. });
  93676. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  93677. }
  93678. };
  93679. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  93680. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  93681. this._reconstructedMesh.material = this._mesh.material;
  93682. this._reconstructedMesh.parent = this._mesh.parent;
  93683. this._reconstructedMesh.isVisible = false;
  93684. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  93685. };
  93686. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  93687. for (var i = 0; i < vertex1.triangleCount; ++i) {
  93688. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  93689. if (t.deleted)
  93690. continue;
  93691. var s = this.references[vertex1.triangleStart + i].vertexId;
  93692. var v1 = t.vertices[(s + 1) % 3];
  93693. var v2 = t.vertices[(s + 2) % 3];
  93694. if ((v1 === vertex2 || v2 === vertex2)) {
  93695. deletedArray[i] = true;
  93696. delTr.push(t);
  93697. continue;
  93698. }
  93699. var d1 = v1.position.subtract(point);
  93700. d1 = d1.normalize();
  93701. var d2 = v2.position.subtract(point);
  93702. d2 = d2.normalize();
  93703. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  93704. return true;
  93705. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  93706. deletedArray[i] = false;
  93707. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  93708. return true;
  93709. }
  93710. return false;
  93711. };
  93712. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  93713. var newDeleted = deletedTriangles;
  93714. for (var i = 0; i < vertex.triangleCount; ++i) {
  93715. var ref = this.references[vertex.triangleStart + i];
  93716. var t = this.triangles[ref.triangleId];
  93717. if (t.deleted)
  93718. continue;
  93719. if (deletedArray[i] && t.deletePending) {
  93720. t.deleted = true;
  93721. newDeleted++;
  93722. continue;
  93723. }
  93724. t.vertices[ref.vertexId] = origVertex;
  93725. t.isDirty = true;
  93726. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  93727. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  93728. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  93729. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93730. this.references.push(ref);
  93731. }
  93732. return newDeleted;
  93733. };
  93734. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  93735. for (var i = 0; i < this.vertices.length; ++i) {
  93736. var vCount = [];
  93737. var vId = [];
  93738. var v = this.vertices[i];
  93739. var j;
  93740. for (j = 0; j < v.triangleCount; ++j) {
  93741. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  93742. for (var ii = 0; ii < 3; ii++) {
  93743. var ofs = 0;
  93744. var vv = triangle.vertices[ii];
  93745. while (ofs < vCount.length) {
  93746. if (vId[ofs] === vv.id)
  93747. break;
  93748. ++ofs;
  93749. }
  93750. if (ofs === vCount.length) {
  93751. vCount.push(1);
  93752. vId.push(vv.id);
  93753. }
  93754. else {
  93755. vCount[ofs]++;
  93756. }
  93757. }
  93758. }
  93759. for (j = 0; j < vCount.length; ++j) {
  93760. if (vCount[j] === 1) {
  93761. this.vertices[vId[j]].isBorder = true;
  93762. }
  93763. else {
  93764. this.vertices[vId[j]].isBorder = false;
  93765. }
  93766. }
  93767. }
  93768. };
  93769. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  93770. if (identifyBorders === void 0) { identifyBorders = false; }
  93771. var i;
  93772. if (!identifyBorders) {
  93773. var newTrianglesVector = [];
  93774. for (i = 0; i < this.triangles.length; ++i) {
  93775. if (!this.triangles[i].deleted) {
  93776. newTrianglesVector.push(this.triangles[i]);
  93777. }
  93778. }
  93779. this.triangles = newTrianglesVector;
  93780. }
  93781. for (i = 0; i < this.vertices.length; ++i) {
  93782. this.vertices[i].triangleCount = 0;
  93783. this.vertices[i].triangleStart = 0;
  93784. }
  93785. var t;
  93786. var j;
  93787. var v;
  93788. for (i = 0; i < this.triangles.length; ++i) {
  93789. t = this.triangles[i];
  93790. for (j = 0; j < 3; ++j) {
  93791. v = t.vertices[j];
  93792. v.triangleCount++;
  93793. }
  93794. }
  93795. var tStart = 0;
  93796. for (i = 0; i < this.vertices.length; ++i) {
  93797. this.vertices[i].triangleStart = tStart;
  93798. tStart += this.vertices[i].triangleCount;
  93799. this.vertices[i].triangleCount = 0;
  93800. }
  93801. var newReferences = new Array(this.triangles.length * 3);
  93802. for (i = 0; i < this.triangles.length; ++i) {
  93803. t = this.triangles[i];
  93804. for (j = 0; j < 3; ++j) {
  93805. v = t.vertices[j];
  93806. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  93807. v.triangleCount++;
  93808. }
  93809. }
  93810. this.references = newReferences;
  93811. if (identifyBorders) {
  93812. this.identifyBorder();
  93813. }
  93814. };
  93815. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  93816. var x = point.x;
  93817. var y = point.y;
  93818. var z = point.z;
  93819. 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
  93820. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  93821. };
  93822. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  93823. var q = vertex1.q.add(vertex2.q);
  93824. var border = vertex1.isBorder && vertex2.isBorder;
  93825. var error = 0;
  93826. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  93827. if (qDet !== 0 && !border) {
  93828. if (!pointResult) {
  93829. pointResult = BABYLON.Vector3.Zero();
  93830. }
  93831. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  93832. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  93833. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  93834. error = this.vertexError(q, pointResult);
  93835. }
  93836. else {
  93837. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  93838. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  93839. var error1 = this.vertexError(q, vertex1.position);
  93840. var error2 = this.vertexError(q, vertex2.position);
  93841. var error3 = this.vertexError(q, p3);
  93842. error = Math.min(error1, error2, error3);
  93843. if (error === error1) {
  93844. if (pointResult) {
  93845. pointResult.copyFrom(vertex1.position);
  93846. }
  93847. }
  93848. else if (error === error2) {
  93849. if (pointResult) {
  93850. pointResult.copyFrom(vertex2.position);
  93851. }
  93852. }
  93853. else {
  93854. if (pointResult) {
  93855. pointResult.copyFrom(p3);
  93856. }
  93857. }
  93858. }
  93859. return error;
  93860. };
  93861. return QuadraticErrorSimplification;
  93862. }());
  93863. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  93864. })(BABYLON || (BABYLON = {}));
  93865. //# sourceMappingURL=babylon.meshSimplification.js.map
  93866. var BABYLON;
  93867. (function (BABYLON) {
  93868. var MeshLODLevel = /** @class */ (function () {
  93869. function MeshLODLevel(distance, mesh) {
  93870. this.distance = distance;
  93871. this.mesh = mesh;
  93872. }
  93873. return MeshLODLevel;
  93874. }());
  93875. BABYLON.MeshLODLevel = MeshLODLevel;
  93876. })(BABYLON || (BABYLON = {}));
  93877. //# sourceMappingURL=babylon.meshLODLevel.js.map
  93878. var BABYLON;
  93879. (function (BABYLON) {
  93880. /**
  93881. * Defines the root class used to create scene optimization to use with SceneOptimizer
  93882. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93883. */
  93884. var SceneOptimization = /** @class */ (function () {
  93885. /**
  93886. * Creates the SceneOptimization object
  93887. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93888. * @param desc defines the description associated with the optimization
  93889. */
  93890. function SceneOptimization(
  93891. /**
  93892. * Defines the priority of this optimization (0 by default which means first in the list)
  93893. */
  93894. priority) {
  93895. if (priority === void 0) { priority = 0; }
  93896. this.priority = priority;
  93897. }
  93898. /**
  93899. * Gets a string describing the action executed by the current optimization
  93900. * @returns description string
  93901. */
  93902. SceneOptimization.prototype.getDescription = function () {
  93903. return "";
  93904. };
  93905. /**
  93906. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93907. * @param scene defines the current scene where to apply this optimization
  93908. * @param optimizer defines the current optimizer
  93909. * @returns true if everything that can be done was applied
  93910. */
  93911. SceneOptimization.prototype.apply = function (scene, optimizer) {
  93912. return true;
  93913. };
  93914. ;
  93915. return SceneOptimization;
  93916. }());
  93917. BABYLON.SceneOptimization = SceneOptimization;
  93918. /**
  93919. * Defines an optimization used to reduce the size of render target textures
  93920. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93921. */
  93922. var TextureOptimization = /** @class */ (function (_super) {
  93923. __extends(TextureOptimization, _super);
  93924. /**
  93925. * Creates the TextureOptimization object
  93926. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93927. * @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
  93928. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93929. */
  93930. function TextureOptimization(
  93931. /**
  93932. * Defines the priority of this optimization (0 by default which means first in the list)
  93933. */
  93934. priority,
  93935. /**
  93936. * 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
  93937. */
  93938. maximumSize,
  93939. /**
  93940. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93941. */
  93942. step) {
  93943. if (priority === void 0) { priority = 0; }
  93944. if (maximumSize === void 0) { maximumSize = 1024; }
  93945. if (step === void 0) { step = 0.5; }
  93946. var _this = _super.call(this, priority) || this;
  93947. _this.priority = priority;
  93948. _this.maximumSize = maximumSize;
  93949. _this.step = step;
  93950. return _this;
  93951. }
  93952. /**
  93953. * Gets a string describing the action executed by the current optimization
  93954. * @returns description string
  93955. */
  93956. TextureOptimization.prototype.getDescription = function () {
  93957. return "Reducing render target texture size to " + this.maximumSize;
  93958. };
  93959. /**
  93960. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93961. * @param scene defines the current scene where to apply this optimization
  93962. * @param optimizer defines the current optimizer
  93963. * @returns true if everything that can be done was applied
  93964. */
  93965. TextureOptimization.prototype.apply = function (scene, optimizer) {
  93966. var allDone = true;
  93967. for (var index = 0; index < scene.textures.length; index++) {
  93968. var texture = scene.textures[index];
  93969. if (!texture.canRescale || texture.getContext) {
  93970. continue;
  93971. }
  93972. var currentSize = texture.getSize();
  93973. var maxDimension = Math.max(currentSize.width, currentSize.height);
  93974. if (maxDimension > this.maximumSize) {
  93975. texture.scale(this.step);
  93976. allDone = false;
  93977. }
  93978. }
  93979. return allDone;
  93980. };
  93981. return TextureOptimization;
  93982. }(SceneOptimization));
  93983. BABYLON.TextureOptimization = TextureOptimization;
  93984. /**
  93985. * Defines an optimization used to increase or decrease the rendering resolution
  93986. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93987. */
  93988. var HardwareScalingOptimization = /** @class */ (function (_super) {
  93989. __extends(HardwareScalingOptimization, _super);
  93990. /**
  93991. * Creates the HardwareScalingOptimization object
  93992. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93993. * @param maximumScale defines the maximum scale to use (2 by default)
  93994. * @param step defines the step to use between two passes (0.5 by default)
  93995. */
  93996. function HardwareScalingOptimization(
  93997. /**
  93998. * Defines the priority of this optimization (0 by default which means first in the list)
  93999. */
  94000. priority,
  94001. /**
  94002. * Defines the maximum scale to use (2 by default)
  94003. */
  94004. maximumScale,
  94005. /**
  94006. * Defines the step to use between two passes (0.5 by default)
  94007. */
  94008. step) {
  94009. if (priority === void 0) { priority = 0; }
  94010. if (maximumScale === void 0) { maximumScale = 2; }
  94011. if (step === void 0) { step = 0.25; }
  94012. var _this = _super.call(this, priority) || this;
  94013. _this.priority = priority;
  94014. _this.maximumScale = maximumScale;
  94015. _this.step = step;
  94016. _this._currentScale = -1;
  94017. _this._directionOffset = 1;
  94018. return _this;
  94019. }
  94020. /**
  94021. * Gets a string describing the action executed by the current optimization
  94022. * @return description string
  94023. */
  94024. HardwareScalingOptimization.prototype.getDescription = function () {
  94025. return "Setting hardware scaling level to " + this._currentScale;
  94026. };
  94027. /**
  94028. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94029. * @param scene defines the current scene where to apply this optimization
  94030. * @param optimizer defines the current optimizer
  94031. * @returns true if everything that can be done was applied
  94032. */
  94033. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94034. if (this._currentScale === -1) {
  94035. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94036. if (this._currentScale > this.maximumScale) {
  94037. this._directionOffset = -1;
  94038. }
  94039. }
  94040. this._currentScale += this._directionOffset * this.step;
  94041. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94042. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94043. };
  94044. ;
  94045. return HardwareScalingOptimization;
  94046. }(SceneOptimization));
  94047. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94048. /**
  94049. * Defines an optimization used to remove shadows
  94050. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94051. */
  94052. var ShadowsOptimization = /** @class */ (function (_super) {
  94053. __extends(ShadowsOptimization, _super);
  94054. function ShadowsOptimization() {
  94055. return _super !== null && _super.apply(this, arguments) || this;
  94056. }
  94057. /**
  94058. * Gets a string describing the action executed by the current optimization
  94059. * @return description string
  94060. */
  94061. ShadowsOptimization.prototype.getDescription = function () {
  94062. return "Turning shadows on/off";
  94063. };
  94064. /**
  94065. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94066. * @param scene defines the current scene where to apply this optimization
  94067. * @param optimizer defines the current optimizer
  94068. * @returns true if everything that can be done was applied
  94069. */
  94070. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94071. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94072. return true;
  94073. };
  94074. ;
  94075. return ShadowsOptimization;
  94076. }(SceneOptimization));
  94077. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94078. /**
  94079. * Defines an optimization used to turn post-processes off
  94080. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94081. */
  94082. var PostProcessesOptimization = /** @class */ (function (_super) {
  94083. __extends(PostProcessesOptimization, _super);
  94084. function PostProcessesOptimization() {
  94085. return _super !== null && _super.apply(this, arguments) || this;
  94086. }
  94087. /**
  94088. * Gets a string describing the action executed by the current optimization
  94089. * @return description string
  94090. */
  94091. PostProcessesOptimization.prototype.getDescription = function () {
  94092. return "Turning post-processes on/off";
  94093. };
  94094. /**
  94095. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94096. * @param scene defines the current scene where to apply this optimization
  94097. * @param optimizer defines the current optimizer
  94098. * @returns true if everything that can be done was applied
  94099. */
  94100. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94101. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94102. return true;
  94103. };
  94104. ;
  94105. return PostProcessesOptimization;
  94106. }(SceneOptimization));
  94107. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94108. /**
  94109. * Defines an optimization used to turn lens flares off
  94110. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94111. */
  94112. var LensFlaresOptimization = /** @class */ (function (_super) {
  94113. __extends(LensFlaresOptimization, _super);
  94114. function LensFlaresOptimization() {
  94115. return _super !== null && _super.apply(this, arguments) || this;
  94116. }
  94117. /**
  94118. * Gets a string describing the action executed by the current optimization
  94119. * @return description string
  94120. */
  94121. LensFlaresOptimization.prototype.getDescription = function () {
  94122. return "Turning lens flares on/off";
  94123. };
  94124. /**
  94125. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94126. * @param scene defines the current scene where to apply this optimization
  94127. * @param optimizer defines the current optimizer
  94128. * @returns true if everything that can be done was applied
  94129. */
  94130. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94131. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94132. return true;
  94133. };
  94134. ;
  94135. return LensFlaresOptimization;
  94136. }(SceneOptimization));
  94137. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  94138. /**
  94139. * Defines an optimization based on user defined callback.
  94140. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94141. */
  94142. var CustomOptimization = /** @class */ (function (_super) {
  94143. __extends(CustomOptimization, _super);
  94144. function CustomOptimization() {
  94145. return _super !== null && _super.apply(this, arguments) || this;
  94146. }
  94147. /**
  94148. * Gets a string describing the action executed by the current optimization
  94149. * @returns description string
  94150. */
  94151. CustomOptimization.prototype.getDescription = function () {
  94152. if (this.onGetDescription) {
  94153. return this.onGetDescription();
  94154. }
  94155. return "Running user defined callback";
  94156. };
  94157. /**
  94158. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94159. * @param scene defines the current scene where to apply this optimization
  94160. * @param optimizer defines the current optimizer
  94161. * @returns true if everything that can be done was applied
  94162. */
  94163. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94164. if (this.onApply) {
  94165. return this.onApply(scene, optimizer);
  94166. }
  94167. return true;
  94168. };
  94169. ;
  94170. return CustomOptimization;
  94171. }(SceneOptimization));
  94172. BABYLON.CustomOptimization = CustomOptimization;
  94173. /**
  94174. * Defines an optimization used to turn particles off
  94175. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94176. */
  94177. var ParticlesOptimization = /** @class */ (function (_super) {
  94178. __extends(ParticlesOptimization, _super);
  94179. function ParticlesOptimization() {
  94180. return _super !== null && _super.apply(this, arguments) || this;
  94181. }
  94182. /**
  94183. * Gets a string describing the action executed by the current optimization
  94184. * @return description string
  94185. */
  94186. ParticlesOptimization.prototype.getDescription = function () {
  94187. return "Turning particles on/off";
  94188. };
  94189. /**
  94190. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94191. * @param scene defines the current scene where to apply this optimization
  94192. * @param optimizer defines the current optimizer
  94193. * @returns true if everything that can be done was applied
  94194. */
  94195. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94196. scene.particlesEnabled = optimizer.isInImprovementMode;
  94197. return true;
  94198. };
  94199. ;
  94200. return ParticlesOptimization;
  94201. }(SceneOptimization));
  94202. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94203. /**
  94204. * Defines an optimization used to turn render targets off
  94205. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94206. */
  94207. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94208. __extends(RenderTargetsOptimization, _super);
  94209. function RenderTargetsOptimization() {
  94210. return _super !== null && _super.apply(this, arguments) || this;
  94211. }
  94212. /**
  94213. * Gets a string describing the action executed by the current optimization
  94214. * @return description string
  94215. */
  94216. RenderTargetsOptimization.prototype.getDescription = function () {
  94217. return "Turning render targets off";
  94218. };
  94219. /**
  94220. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94221. * @param scene defines the current scene where to apply this optimization
  94222. * @param optimizer defines the current optimizer
  94223. * @returns true if everything that can be done was applied
  94224. */
  94225. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94226. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94227. return true;
  94228. };
  94229. ;
  94230. return RenderTargetsOptimization;
  94231. }(SceneOptimization));
  94232. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94233. /**
  94234. * Defines an optimization used to merge meshes with compatible materials
  94235. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94236. */
  94237. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94238. __extends(MergeMeshesOptimization, _super);
  94239. function MergeMeshesOptimization() {
  94240. var _this = _super !== null && _super.apply(this, arguments) || this;
  94241. _this._canBeMerged = function (abstractMesh) {
  94242. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94243. return false;
  94244. }
  94245. var mesh = abstractMesh;
  94246. if (!mesh.isVisible || !mesh.isEnabled()) {
  94247. return false;
  94248. }
  94249. if (mesh.instances.length > 0) {
  94250. return false;
  94251. }
  94252. if (mesh.skeleton || mesh.hasLODLevels) {
  94253. return false;
  94254. }
  94255. if (mesh.parent) {
  94256. return false;
  94257. }
  94258. return true;
  94259. };
  94260. return _this;
  94261. }
  94262. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94263. /**
  94264. * Gets or sets a boolean which defines if optimization octree has to be updated
  94265. */
  94266. get: function () {
  94267. return MergeMeshesOptimization._UpdateSelectionTree;
  94268. },
  94269. /**
  94270. * Gets or sets a boolean which defines if optimization octree has to be updated
  94271. */
  94272. set: function (value) {
  94273. MergeMeshesOptimization._UpdateSelectionTree = value;
  94274. },
  94275. enumerable: true,
  94276. configurable: true
  94277. });
  94278. /**
  94279. * Gets a string describing the action executed by the current optimization
  94280. * @return description string
  94281. */
  94282. MergeMeshesOptimization.prototype.getDescription = function () {
  94283. return "Merging similar meshes together";
  94284. };
  94285. /**
  94286. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94287. * @param scene defines the current scene where to apply this optimization
  94288. * @param optimizer defines the current optimizer
  94289. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94290. * @returns true if everything that can be done was applied
  94291. */
  94292. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94293. var globalPool = scene.meshes.slice(0);
  94294. var globalLength = globalPool.length;
  94295. for (var index = 0; index < globalLength; index++) {
  94296. var currentPool = new Array();
  94297. var current = globalPool[index];
  94298. // Checks
  94299. if (!this._canBeMerged(current)) {
  94300. continue;
  94301. }
  94302. currentPool.push(current);
  94303. // Find compatible meshes
  94304. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94305. var otherMesh = globalPool[subIndex];
  94306. if (!this._canBeMerged(otherMesh)) {
  94307. continue;
  94308. }
  94309. if (otherMesh.material !== current.material) {
  94310. continue;
  94311. }
  94312. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94313. continue;
  94314. }
  94315. currentPool.push(otherMesh);
  94316. globalLength--;
  94317. globalPool.splice(subIndex, 1);
  94318. subIndex--;
  94319. }
  94320. if (currentPool.length < 2) {
  94321. continue;
  94322. }
  94323. // Merge meshes
  94324. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94325. }
  94326. if (updateSelectionTree != undefined) {
  94327. if (updateSelectionTree) {
  94328. scene.createOrUpdateSelectionOctree();
  94329. }
  94330. }
  94331. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94332. scene.createOrUpdateSelectionOctree();
  94333. }
  94334. return true;
  94335. };
  94336. ;
  94337. MergeMeshesOptimization._UpdateSelectionTree = false;
  94338. return MergeMeshesOptimization;
  94339. }(SceneOptimization));
  94340. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94341. /**
  94342. * Defines a list of options used by SceneOptimizer
  94343. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94344. */
  94345. var SceneOptimizerOptions = /** @class */ (function () {
  94346. /**
  94347. * Creates a new list of options used by SceneOptimizer
  94348. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94349. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94350. */
  94351. function SceneOptimizerOptions(
  94352. /**
  94353. * Defines the target frame rate to reach (60 by default)
  94354. */
  94355. targetFrameRate,
  94356. /**
  94357. * Defines the interval between two checkes (2000ms by default)
  94358. */
  94359. trackerDuration) {
  94360. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  94361. if (trackerDuration === void 0) { trackerDuration = 2000; }
  94362. this.targetFrameRate = targetFrameRate;
  94363. this.trackerDuration = trackerDuration;
  94364. /**
  94365. * Gets the list of optimizations to apply
  94366. */
  94367. this.optimizations = new Array();
  94368. }
  94369. /**
  94370. * Add a new optimization
  94371. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  94372. * @returns the current SceneOptimizerOptions
  94373. */
  94374. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94375. this.optimizations.push(optimization);
  94376. return this;
  94377. };
  94378. /**
  94379. * Add a new custom optimization
  94380. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94381. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94382. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94383. * @returns the current SceneOptimizerOptions
  94384. */
  94385. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94386. if (priority === void 0) { priority = 0; }
  94387. var optimization = new CustomOptimization(priority);
  94388. optimization.onApply = onApply;
  94389. optimization.onGetDescription = onGetDescription;
  94390. this.optimizations.push(optimization);
  94391. return this;
  94392. };
  94393. /**
  94394. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  94395. * @param targetFrameRate defines the target frame rate (60 by default)
  94396. * @returns a SceneOptimizerOptions object
  94397. */
  94398. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  94399. var result = new SceneOptimizerOptions(targetFrameRate);
  94400. var priority = 0;
  94401. result.addOptimization(new MergeMeshesOptimization(priority));
  94402. result.addOptimization(new ShadowsOptimization(priority));
  94403. result.addOptimization(new LensFlaresOptimization(priority));
  94404. // Next priority
  94405. priority++;
  94406. result.addOptimization(new PostProcessesOptimization(priority));
  94407. result.addOptimization(new ParticlesOptimization(priority));
  94408. // Next priority
  94409. priority++;
  94410. result.addOptimization(new TextureOptimization(priority, 1024));
  94411. return result;
  94412. };
  94413. /**
  94414. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  94415. * @param targetFrameRate defines the target frame rate (60 by default)
  94416. * @returns a SceneOptimizerOptions object
  94417. */
  94418. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  94419. var result = new SceneOptimizerOptions(targetFrameRate);
  94420. var priority = 0;
  94421. result.addOptimization(new MergeMeshesOptimization(priority));
  94422. result.addOptimization(new ShadowsOptimization(priority));
  94423. result.addOptimization(new LensFlaresOptimization(priority));
  94424. // Next priority
  94425. priority++;
  94426. result.addOptimization(new PostProcessesOptimization(priority));
  94427. result.addOptimization(new ParticlesOptimization(priority));
  94428. // Next priority
  94429. priority++;
  94430. result.addOptimization(new TextureOptimization(priority, 512));
  94431. // Next priority
  94432. priority++;
  94433. result.addOptimization(new RenderTargetsOptimization(priority));
  94434. // Next priority
  94435. priority++;
  94436. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  94437. return result;
  94438. };
  94439. /**
  94440. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  94441. * @param targetFrameRate defines the target frame rate (60 by default)
  94442. * @returns a SceneOptimizerOptions object
  94443. */
  94444. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  94445. var result = new SceneOptimizerOptions(targetFrameRate);
  94446. var priority = 0;
  94447. result.addOptimization(new MergeMeshesOptimization(priority));
  94448. result.addOptimization(new ShadowsOptimization(priority));
  94449. result.addOptimization(new LensFlaresOptimization(priority));
  94450. // Next priority
  94451. priority++;
  94452. result.addOptimization(new PostProcessesOptimization(priority));
  94453. result.addOptimization(new ParticlesOptimization(priority));
  94454. // Next priority
  94455. priority++;
  94456. result.addOptimization(new TextureOptimization(priority, 256));
  94457. // Next priority
  94458. priority++;
  94459. result.addOptimization(new RenderTargetsOptimization(priority));
  94460. // Next priority
  94461. priority++;
  94462. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  94463. return result;
  94464. };
  94465. return SceneOptimizerOptions;
  94466. }());
  94467. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  94468. /**
  94469. * Class used to run optimizations in order to reach a target frame rate
  94470. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94471. */
  94472. var SceneOptimizer = /** @class */ (function () {
  94473. /**
  94474. * Creates a new SceneOptimizer
  94475. * @param scene defines the scene to work on
  94476. * @param options defines the options to use with the SceneOptimizer
  94477. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  94478. * @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)
  94479. */
  94480. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  94481. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  94482. if (improvementMode === void 0) { improvementMode = false; }
  94483. var _this = this;
  94484. this._isRunning = false;
  94485. this._currentPriorityLevel = 0;
  94486. this._targetFrameRate = 60;
  94487. this._trackerDuration = 2000;
  94488. this._currentFrameRate = 0;
  94489. this._improvementMode = false;
  94490. /**
  94491. * Defines an observable called when the optimizer reaches the target frame rate
  94492. */
  94493. this.onSuccessObservable = new BABYLON.Observable();
  94494. /**
  94495. * Defines an observable called when the optimizer enables an optimization
  94496. */
  94497. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  94498. /**
  94499. * Defines an observable called when the optimizer is not able to reach the target frame rate
  94500. */
  94501. this.onFailureObservable = new BABYLON.Observable();
  94502. if (!options) {
  94503. this._options = new SceneOptimizerOptions();
  94504. }
  94505. else {
  94506. this._options = options;
  94507. }
  94508. if (this._options.targetFrameRate) {
  94509. this._targetFrameRate = this._options.targetFrameRate;
  94510. }
  94511. if (this._options.trackerDuration) {
  94512. this._trackerDuration = this._options.trackerDuration;
  94513. }
  94514. if (autoGeneratePriorities) {
  94515. var priority = 0;
  94516. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  94517. var optim = _a[_i];
  94518. optim.priority = priority++;
  94519. }
  94520. }
  94521. this._improvementMode = improvementMode;
  94522. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94523. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  94524. _this._sceneDisposeObserver = null;
  94525. _this.dispose();
  94526. });
  94527. }
  94528. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  94529. /**
  94530. * Gets a boolean indicating if the optimizer is in improvement mode
  94531. */
  94532. get: function () {
  94533. return this._improvementMode;
  94534. },
  94535. enumerable: true,
  94536. configurable: true
  94537. });
  94538. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  94539. /**
  94540. * Gets the current priority level (0 at start)
  94541. */
  94542. get: function () {
  94543. return this._currentPriorityLevel;
  94544. },
  94545. enumerable: true,
  94546. configurable: true
  94547. });
  94548. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  94549. /**
  94550. * Gets the current frame rate checked by the SceneOptimizer
  94551. */
  94552. get: function () {
  94553. return this._currentFrameRate;
  94554. },
  94555. enumerable: true,
  94556. configurable: true
  94557. });
  94558. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  94559. /**
  94560. * Gets or sets the current target frame rate (60 by default)
  94561. */
  94562. get: function () {
  94563. return this._targetFrameRate;
  94564. },
  94565. /**
  94566. * Gets or sets the current target frame rate (60 by default)
  94567. */
  94568. set: function (value) {
  94569. this._targetFrameRate = value;
  94570. },
  94571. enumerable: true,
  94572. configurable: true
  94573. });
  94574. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  94575. /**
  94576. * Gets or sets the current interval between two checks (every 2000ms by default)
  94577. */
  94578. get: function () {
  94579. return this._trackerDuration;
  94580. },
  94581. /**
  94582. * Gets or sets the current interval between two checks (every 2000ms by default)
  94583. */
  94584. set: function (value) {
  94585. this._trackerDuration = value;
  94586. },
  94587. enumerable: true,
  94588. configurable: true
  94589. });
  94590. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  94591. /**
  94592. * Gets the list of active optimizations
  94593. */
  94594. get: function () {
  94595. return this._options.optimizations;
  94596. },
  94597. enumerable: true,
  94598. configurable: true
  94599. });
  94600. /**
  94601. * Stops the current optimizer
  94602. */
  94603. SceneOptimizer.prototype.stop = function () {
  94604. this._isRunning = false;
  94605. };
  94606. /**
  94607. * Reset the optimizer to initial step (current priority level = 0)
  94608. */
  94609. SceneOptimizer.prototype.reset = function () {
  94610. this._currentPriorityLevel = 0;
  94611. };
  94612. /**
  94613. * Start the optimizer. By default it will try to reach a specific framerate
  94614. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  94615. */
  94616. SceneOptimizer.prototype.start = function () {
  94617. var _this = this;
  94618. if (this._isRunning) {
  94619. return;
  94620. }
  94621. this._isRunning = true;
  94622. // Let's wait for the scene to be ready before running our check
  94623. this._scene.executeWhenReady(function () {
  94624. setTimeout(function () {
  94625. _this._checkCurrentState();
  94626. }, _this._trackerDuration);
  94627. });
  94628. };
  94629. SceneOptimizer.prototype._checkCurrentState = function () {
  94630. var _this = this;
  94631. if (!this._isRunning) {
  94632. return;
  94633. }
  94634. var scene = this._scene;
  94635. var options = this._options;
  94636. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  94637. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  94638. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  94639. this._isRunning = false;
  94640. this.onSuccessObservable.notifyObservers(this);
  94641. return;
  94642. }
  94643. // Apply current level of optimizations
  94644. var allDone = true;
  94645. var noOptimizationApplied = true;
  94646. for (var index = 0; index < options.optimizations.length; index++) {
  94647. var optimization = options.optimizations[index];
  94648. if (optimization.priority === this._currentPriorityLevel) {
  94649. noOptimizationApplied = false;
  94650. allDone = allDone && optimization.apply(scene, this);
  94651. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  94652. }
  94653. }
  94654. // If no optimization was applied, this is a failure :(
  94655. if (noOptimizationApplied) {
  94656. this._isRunning = false;
  94657. this.onFailureObservable.notifyObservers(this);
  94658. return;
  94659. }
  94660. // If all optimizations were done, move to next level
  94661. if (allDone) {
  94662. this._currentPriorityLevel++;
  94663. }
  94664. // Let's the system running for a specific amount of time before checking FPS
  94665. scene.executeWhenReady(function () {
  94666. setTimeout(function () {
  94667. _this._checkCurrentState();
  94668. }, _this._trackerDuration);
  94669. });
  94670. };
  94671. /**
  94672. * Release all resources
  94673. */
  94674. SceneOptimizer.prototype.dispose = function () {
  94675. this.stop();
  94676. this.onSuccessObservable.clear();
  94677. this.onFailureObservable.clear();
  94678. this.onNewOptimizationAppliedObservable.clear();
  94679. if (this._sceneDisposeObserver) {
  94680. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94681. }
  94682. };
  94683. /**
  94684. * Helper function to create a SceneOptimizer with one single line of code
  94685. * @param scene defines the scene to work on
  94686. * @param options defines the options to use with the SceneOptimizer
  94687. * @param onSuccess defines a callback to call on success
  94688. * @param onFailure defines a callback to call on failure
  94689. * @returns the new SceneOptimizer object
  94690. */
  94691. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  94692. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  94693. if (onSuccess) {
  94694. optimizer.onSuccessObservable.add(function () {
  94695. onSuccess();
  94696. });
  94697. }
  94698. if (onFailure) {
  94699. optimizer.onFailureObservable.add(function () {
  94700. onFailure();
  94701. });
  94702. }
  94703. optimizer.start();
  94704. return optimizer;
  94705. };
  94706. return SceneOptimizer;
  94707. }());
  94708. BABYLON.SceneOptimizer = SceneOptimizer;
  94709. })(BABYLON || (BABYLON = {}));
  94710. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  94711. var BABYLON;
  94712. (function (BABYLON) {
  94713. var OutlineRenderer = /** @class */ (function () {
  94714. function OutlineRenderer(scene) {
  94715. this.zOffset = 1;
  94716. this._scene = scene;
  94717. }
  94718. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  94719. var _this = this;
  94720. if (useOverlay === void 0) { useOverlay = false; }
  94721. var scene = this._scene;
  94722. var engine = this._scene.getEngine();
  94723. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94724. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  94725. return;
  94726. }
  94727. var mesh = subMesh.getRenderingMesh();
  94728. var material = subMesh.getMaterial();
  94729. if (!material || !scene.activeCamera) {
  94730. return;
  94731. }
  94732. engine.enableEffect(this._effect);
  94733. // Logarithmic depth
  94734. if (material.useLogarithmicDepth) {
  94735. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  94736. }
  94737. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  94738. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  94739. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  94740. // Bones
  94741. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94742. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94743. }
  94744. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  94745. // Alpha test
  94746. if (material && material.needAlphaTesting()) {
  94747. var alphaTexture = material.getAlphaTestTexture();
  94748. if (alphaTexture) {
  94749. this._effect.setTexture("diffuseSampler", alphaTexture);
  94750. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  94751. }
  94752. }
  94753. engine.setZOffset(-this.zOffset);
  94754. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  94755. engine.setZOffset(0);
  94756. };
  94757. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  94758. var defines = [];
  94759. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  94760. var mesh = subMesh.getMesh();
  94761. var material = subMesh.getMaterial();
  94762. if (material) {
  94763. // Alpha test
  94764. if (material.needAlphaTesting()) {
  94765. defines.push("#define ALPHATEST");
  94766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94767. attribs.push(BABYLON.VertexBuffer.UVKind);
  94768. defines.push("#define UV1");
  94769. }
  94770. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  94771. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94772. defines.push("#define UV2");
  94773. }
  94774. }
  94775. //Logarithmic depth
  94776. if (material.useLogarithmicDepth) {
  94777. defines.push("#define LOGARITHMICDEPTH");
  94778. }
  94779. }
  94780. // Bones
  94781. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94782. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94783. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94784. if (mesh.numBoneInfluencers > 4) {
  94785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94787. }
  94788. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94789. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  94790. }
  94791. else {
  94792. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94793. }
  94794. // Instances
  94795. if (useInstances) {
  94796. defines.push("#define INSTANCES");
  94797. attribs.push("world0");
  94798. attribs.push("world1");
  94799. attribs.push("world2");
  94800. attribs.push("world3");
  94801. }
  94802. // Get correct effect
  94803. var join = defines.join("\n");
  94804. if (this._cachedDefines !== join) {
  94805. this._cachedDefines = join;
  94806. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  94807. }
  94808. return this._effect.isReady();
  94809. };
  94810. return OutlineRenderer;
  94811. }());
  94812. BABYLON.OutlineRenderer = OutlineRenderer;
  94813. })(BABYLON || (BABYLON = {}));
  94814. //# sourceMappingURL=babylon.outlineRenderer.js.map
  94815. var BABYLON;
  94816. (function (BABYLON) {
  94817. var FaceAdjacencies = /** @class */ (function () {
  94818. function FaceAdjacencies() {
  94819. this.edges = new Array();
  94820. this.edgesConnectedCount = 0;
  94821. }
  94822. return FaceAdjacencies;
  94823. }());
  94824. var EdgesRenderer = /** @class */ (function () {
  94825. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  94826. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  94827. if (epsilon === void 0) { epsilon = 0.95; }
  94828. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  94829. this.edgesWidthScalerForOrthographic = 1000.0;
  94830. this.edgesWidthScalerForPerspective = 50.0;
  94831. this._linesPositions = new Array();
  94832. this._linesNormals = new Array();
  94833. this._linesIndices = new Array();
  94834. this._buffers = {};
  94835. this._checkVerticesInsteadOfIndices = false;
  94836. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  94837. this.isEnabled = true;
  94838. this._source = source;
  94839. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  94840. this._epsilon = epsilon;
  94841. this._prepareRessources();
  94842. this._generateEdgesLines();
  94843. }
  94844. EdgesRenderer.prototype._prepareRessources = function () {
  94845. if (this._lineShader) {
  94846. return;
  94847. }
  94848. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  94849. attributes: ["position", "normal"],
  94850. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  94851. });
  94852. this._lineShader.disableDepthWrite = true;
  94853. this._lineShader.backFaceCulling = false;
  94854. };
  94855. EdgesRenderer.prototype._rebuild = function () {
  94856. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94857. if (buffer) {
  94858. buffer._rebuild();
  94859. }
  94860. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94861. if (buffer) {
  94862. buffer._rebuild();
  94863. }
  94864. var scene = this._source.getScene();
  94865. var engine = scene.getEngine();
  94866. this._ib = engine.createIndexBuffer(this._linesIndices);
  94867. };
  94868. EdgesRenderer.prototype.dispose = function () {
  94869. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94870. if (buffer) {
  94871. buffer.dispose();
  94872. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  94873. }
  94874. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94875. if (buffer) {
  94876. buffer.dispose();
  94877. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  94878. }
  94879. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  94880. this._lineShader.dispose();
  94881. };
  94882. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  94883. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  94884. return 0;
  94885. }
  94886. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  94887. return 1;
  94888. }
  94889. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  94890. return 2;
  94891. }
  94892. return -1;
  94893. };
  94894. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  94895. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  94896. return 0;
  94897. }
  94898. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  94899. return 1;
  94900. }
  94901. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  94902. return 2;
  94903. }
  94904. return -1;
  94905. };
  94906. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  94907. var needToCreateLine;
  94908. if (edge === undefined) {
  94909. needToCreateLine = true;
  94910. }
  94911. else {
  94912. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  94913. needToCreateLine = dotProduct < this._epsilon;
  94914. }
  94915. if (needToCreateLine) {
  94916. var offset = this._linesPositions.length / 3;
  94917. var normal = p0.subtract(p1);
  94918. normal.normalize();
  94919. // Positions
  94920. this._linesPositions.push(p0.x);
  94921. this._linesPositions.push(p0.y);
  94922. this._linesPositions.push(p0.z);
  94923. this._linesPositions.push(p0.x);
  94924. this._linesPositions.push(p0.y);
  94925. this._linesPositions.push(p0.z);
  94926. this._linesPositions.push(p1.x);
  94927. this._linesPositions.push(p1.y);
  94928. this._linesPositions.push(p1.z);
  94929. this._linesPositions.push(p1.x);
  94930. this._linesPositions.push(p1.y);
  94931. this._linesPositions.push(p1.z);
  94932. // Normals
  94933. this._linesNormals.push(p1.x);
  94934. this._linesNormals.push(p1.y);
  94935. this._linesNormals.push(p1.z);
  94936. this._linesNormals.push(-1);
  94937. this._linesNormals.push(p1.x);
  94938. this._linesNormals.push(p1.y);
  94939. this._linesNormals.push(p1.z);
  94940. this._linesNormals.push(1);
  94941. this._linesNormals.push(p0.x);
  94942. this._linesNormals.push(p0.y);
  94943. this._linesNormals.push(p0.z);
  94944. this._linesNormals.push(-1);
  94945. this._linesNormals.push(p0.x);
  94946. this._linesNormals.push(p0.y);
  94947. this._linesNormals.push(p0.z);
  94948. this._linesNormals.push(1);
  94949. // Indices
  94950. this._linesIndices.push(offset);
  94951. this._linesIndices.push(offset + 1);
  94952. this._linesIndices.push(offset + 2);
  94953. this._linesIndices.push(offset);
  94954. this._linesIndices.push(offset + 2);
  94955. this._linesIndices.push(offset + 3);
  94956. }
  94957. };
  94958. EdgesRenderer.prototype._generateEdgesLines = function () {
  94959. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94960. var indices = this._source.getIndices();
  94961. if (!indices || !positions) {
  94962. return;
  94963. }
  94964. // First let's find adjacencies
  94965. var adjacencies = new Array();
  94966. var faceNormals = new Array();
  94967. var index;
  94968. var faceAdjacencies;
  94969. // Prepare faces
  94970. for (index = 0; index < indices.length; index += 3) {
  94971. faceAdjacencies = new FaceAdjacencies();
  94972. var p0Index = indices[index];
  94973. var p1Index = indices[index + 1];
  94974. var p2Index = indices[index + 2];
  94975. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  94976. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  94977. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  94978. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  94979. faceNormal.normalize();
  94980. faceNormals.push(faceNormal);
  94981. adjacencies.push(faceAdjacencies);
  94982. }
  94983. // Scan
  94984. for (index = 0; index < adjacencies.length; index++) {
  94985. faceAdjacencies = adjacencies[index];
  94986. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  94987. var otherFaceAdjacencies = adjacencies[otherIndex];
  94988. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  94989. break;
  94990. }
  94991. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  94992. continue;
  94993. }
  94994. var otherP0 = indices[otherIndex * 3];
  94995. var otherP1 = indices[otherIndex * 3 + 1];
  94996. var otherP2 = indices[otherIndex * 3 + 2];
  94997. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  94998. var otherEdgeIndex = 0;
  94999. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95000. continue;
  95001. }
  95002. switch (edgeIndex) {
  95003. case 0:
  95004. if (this._checkVerticesInsteadOfIndices) {
  95005. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95006. }
  95007. else {
  95008. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95009. }
  95010. break;
  95011. case 1:
  95012. if (this._checkVerticesInsteadOfIndices) {
  95013. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95014. }
  95015. else {
  95016. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95017. }
  95018. break;
  95019. case 2:
  95020. if (this._checkVerticesInsteadOfIndices) {
  95021. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95022. }
  95023. else {
  95024. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95025. }
  95026. break;
  95027. }
  95028. if (otherEdgeIndex === -1) {
  95029. continue;
  95030. }
  95031. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95032. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95033. faceAdjacencies.edgesConnectedCount++;
  95034. otherFaceAdjacencies.edgesConnectedCount++;
  95035. if (faceAdjacencies.edgesConnectedCount === 3) {
  95036. break;
  95037. }
  95038. }
  95039. }
  95040. }
  95041. // Create lines
  95042. for (index = 0; index < adjacencies.length; index++) {
  95043. // 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
  95044. var current = adjacencies[index];
  95045. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95046. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95047. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95048. }
  95049. // Merge into a single mesh
  95050. var engine = this._source.getScene().getEngine();
  95051. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95052. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95053. this._ib = engine.createIndexBuffer(this._linesIndices);
  95054. this._indicesCount = this._linesIndices.length;
  95055. };
  95056. EdgesRenderer.prototype.render = function () {
  95057. var scene = this._source.getScene();
  95058. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95059. return;
  95060. }
  95061. var engine = scene.getEngine();
  95062. this._lineShader._preBind();
  95063. // VBOs
  95064. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95065. scene.resetCachedMaterial();
  95066. this._lineShader.setColor4("color", this._source.edgesColor);
  95067. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95068. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95069. }
  95070. else {
  95071. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95072. }
  95073. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95074. this._lineShader.bind(this._source.getWorldMatrix());
  95075. // Draw order
  95076. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95077. this._lineShader.unbind();
  95078. engine.setDepthWrite(true);
  95079. };
  95080. return EdgesRenderer;
  95081. }());
  95082. BABYLON.EdgesRenderer = EdgesRenderer;
  95083. })(BABYLON || (BABYLON = {}));
  95084. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95085. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95086. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95087. s = arguments[i];
  95088. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95089. t[p] = s[p];
  95090. }
  95091. return t;
  95092. };
  95093. var BABYLON;
  95094. (function (BABYLON) {
  95095. /**
  95096. * The effect layer Helps adding post process effect blended with the main pass.
  95097. *
  95098. * This can be for instance use to generate glow or higlight effects on the scene.
  95099. *
  95100. * The effect layer class can not be used directly and is intented to inherited from to be
  95101. * customized per effects.
  95102. */
  95103. var EffectLayer = /** @class */ (function () {
  95104. /**
  95105. * Instantiates a new effect Layer and references it in the scene.
  95106. * @param name The name of the layer
  95107. * @param scene The scene to use the layer in
  95108. */
  95109. function EffectLayer(
  95110. /** The Friendly of the effect in the scene */
  95111. name, scene) {
  95112. this._vertexBuffers = {};
  95113. this._maxSize = 0;
  95114. this._mainTextureDesiredSize = { width: 0, height: 0 };
  95115. this._shouldRender = true;
  95116. this._postProcesses = [];
  95117. this._textures = [];
  95118. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  95119. /**
  95120. * The clear color of the texture used to generate the glow map.
  95121. */
  95122. this.neutralColor = new BABYLON.Color4();
  95123. /**
  95124. * Specifies wether the highlight layer is enabled or not.
  95125. */
  95126. this.isEnabled = true;
  95127. /**
  95128. * An event triggered when the effect layer has been disposed.
  95129. */
  95130. this.onDisposeObservable = new BABYLON.Observable();
  95131. /**
  95132. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  95133. */
  95134. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  95135. /**
  95136. * An event triggered when the generated texture is being merged in the scene.
  95137. */
  95138. this.onBeforeComposeObservable = new BABYLON.Observable();
  95139. /**
  95140. * An event triggered when the generated texture has been merged in the scene.
  95141. */
  95142. this.onAfterComposeObservable = new BABYLON.Observable();
  95143. /**
  95144. * An event triggered when the efffect layer changes its size.
  95145. */
  95146. this.onSizeChangedObservable = new BABYLON.Observable();
  95147. this.name = name;
  95148. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95149. this._engine = scene.getEngine();
  95150. this._maxSize = this._engine.getCaps().maxTextureSize;
  95151. this._scene.effectLayers.push(this);
  95152. // Generate Buffers
  95153. this._generateIndexBuffer();
  95154. this._genrateVertexBuffer();
  95155. }
  95156. Object.defineProperty(EffectLayer.prototype, "camera", {
  95157. /**
  95158. * Gets the camera attached to the layer.
  95159. */
  95160. get: function () {
  95161. return this._effectLayerOptions.camera;
  95162. },
  95163. enumerable: true,
  95164. configurable: true
  95165. });
  95166. /**
  95167. * Initializes the effect layer with the required options.
  95168. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95169. */
  95170. EffectLayer.prototype._init = function (options) {
  95171. // Adapt options
  95172. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95173. this._setMainTextureSize();
  95174. this._createMainTexture();
  95175. this._createTextureAndPostProcesses();
  95176. this._mergeEffect = this._createMergeEffect();
  95177. };
  95178. /**
  95179. * Generates the index buffer of the full screen quad blending to the main canvas.
  95180. */
  95181. EffectLayer.prototype._generateIndexBuffer = function () {
  95182. // Indices
  95183. var indices = [];
  95184. indices.push(0);
  95185. indices.push(1);
  95186. indices.push(2);
  95187. indices.push(0);
  95188. indices.push(2);
  95189. indices.push(3);
  95190. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95191. };
  95192. /**
  95193. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95194. */
  95195. EffectLayer.prototype._genrateVertexBuffer = function () {
  95196. // VBO
  95197. var vertices = [];
  95198. vertices.push(1, 1);
  95199. vertices.push(-1, 1);
  95200. vertices.push(-1, -1);
  95201. vertices.push(1, -1);
  95202. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95203. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95204. };
  95205. /**
  95206. * Sets the main texture desired size which is the closest power of two
  95207. * of the engine canvas size.
  95208. */
  95209. EffectLayer.prototype._setMainTextureSize = function () {
  95210. if (this._effectLayerOptions.mainTextureFixedSize) {
  95211. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  95212. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  95213. }
  95214. else {
  95215. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  95216. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  95217. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  95218. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  95219. }
  95220. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  95221. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  95222. };
  95223. /**
  95224. * Creates the main texture for the effect layer.
  95225. */
  95226. EffectLayer.prototype._createMainTexture = function () {
  95227. var _this = this;
  95228. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  95229. width: this._mainTextureDesiredSize.width,
  95230. height: this._mainTextureDesiredSize.height
  95231. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95232. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  95233. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95234. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95235. this._mainTexture.anisotropicFilteringLevel = 1;
  95236. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95237. this._mainTexture.renderParticles = false;
  95238. this._mainTexture.renderList = null;
  95239. this._mainTexture.ignoreCameraViewport = true;
  95240. // Custom render function
  95241. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  95242. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  95243. var index;
  95244. var engine = _this._scene.getEngine();
  95245. if (depthOnlySubMeshes.length) {
  95246. engine.setColorWrite(false);
  95247. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  95248. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  95249. }
  95250. engine.setColorWrite(true);
  95251. }
  95252. for (index = 0; index < opaqueSubMeshes.length; index++) {
  95253. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  95254. }
  95255. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  95256. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  95257. }
  95258. for (index = 0; index < transparentSubMeshes.length; index++) {
  95259. _this._renderSubMesh(transparentSubMeshes.data[index]);
  95260. }
  95261. };
  95262. this._mainTexture.onClearObservable.add(function (engine) {
  95263. engine.clear(_this.neutralColor, true, true, true);
  95264. });
  95265. };
  95266. /**
  95267. * Checks for the readiness of the element composing the layer.
  95268. * @param subMesh the mesh to check for
  95269. * @param useInstances specify wether or not to use instances to render the mesh
  95270. * @param emissiveTexture the associated emissive texture used to generate the glow
  95271. * @return true if ready otherwise, false
  95272. */
  95273. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  95274. var material = subMesh.getMaterial();
  95275. if (!material) {
  95276. return false;
  95277. }
  95278. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  95279. return false;
  95280. }
  95281. var defines = [];
  95282. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95283. var mesh = subMesh.getMesh();
  95284. var uv1 = false;
  95285. var uv2 = false;
  95286. // Alpha test
  95287. if (material && material.needAlphaTesting()) {
  95288. var alphaTexture = material.getAlphaTestTexture();
  95289. if (alphaTexture) {
  95290. defines.push("#define ALPHATEST");
  95291. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95292. alphaTexture.coordinatesIndex === 1) {
  95293. defines.push("#define DIFFUSEUV2");
  95294. uv2 = true;
  95295. }
  95296. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95297. defines.push("#define DIFFUSEUV1");
  95298. uv1 = true;
  95299. }
  95300. }
  95301. }
  95302. // Emissive
  95303. if (emissiveTexture) {
  95304. defines.push("#define EMISSIVE");
  95305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95306. emissiveTexture.coordinatesIndex === 1) {
  95307. defines.push("#define EMISSIVEUV2");
  95308. uv2 = true;
  95309. }
  95310. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95311. defines.push("#define EMISSIVEUV1");
  95312. uv1 = true;
  95313. }
  95314. }
  95315. if (uv1) {
  95316. attribs.push(BABYLON.VertexBuffer.UVKind);
  95317. defines.push("#define UV1");
  95318. }
  95319. if (uv2) {
  95320. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95321. defines.push("#define UV2");
  95322. }
  95323. // Bones
  95324. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95325. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95326. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95327. if (mesh.numBoneInfluencers > 4) {
  95328. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95329. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95330. }
  95331. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95332. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  95333. }
  95334. else {
  95335. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95336. }
  95337. // Morph targets
  95338. var manager = mesh.morphTargetManager;
  95339. var morphInfluencers = 0;
  95340. if (manager) {
  95341. if (manager.numInfluencers > 0) {
  95342. defines.push("#define MORPHTARGETS");
  95343. morphInfluencers = manager.numInfluencers;
  95344. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  95345. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  95346. }
  95347. }
  95348. // Instances
  95349. if (useInstances) {
  95350. defines.push("#define INSTANCES");
  95351. attribs.push("world0");
  95352. attribs.push("world1");
  95353. attribs.push("world2");
  95354. attribs.push("world3");
  95355. }
  95356. // Get correct effect
  95357. var join = defines.join("\n");
  95358. if (this._cachedDefines !== join) {
  95359. this._cachedDefines = join;
  95360. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  95361. }
  95362. return this._effectLayerMapGenerationEffect.isReady();
  95363. };
  95364. /**
  95365. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  95366. */
  95367. EffectLayer.prototype.render = function () {
  95368. var currentEffect = this._mergeEffect;
  95369. // Check
  95370. if (!currentEffect.isReady())
  95371. return;
  95372. for (var i = 0; i < this._postProcesses.length; i++) {
  95373. if (!this._postProcesses[i].isReady()) {
  95374. return;
  95375. }
  95376. }
  95377. var engine = this._scene.getEngine();
  95378. this.onBeforeComposeObservable.notifyObservers(this);
  95379. // Render
  95380. engine.enableEffect(currentEffect);
  95381. engine.setState(false);
  95382. // VBOs
  95383. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95384. // Cache
  95385. var previousAlphaMode = engine.getAlphaMode();
  95386. // Go Blend.
  95387. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  95388. // Blends the map on the main canvas.
  95389. this._internalRender(currentEffect);
  95390. // Restore Alpha
  95391. engine.setAlphaMode(previousAlphaMode);
  95392. this.onAfterComposeObservable.notifyObservers(this);
  95393. // Handle size changes.
  95394. var size = this._mainTexture.getSize();
  95395. this._setMainTextureSize();
  95396. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  95397. // Recreate RTT and post processes on size change.
  95398. this.onSizeChangedObservable.notifyObservers(this);
  95399. this._disposeTextureAndPostProcesses();
  95400. this._createMainTexture();
  95401. this._createTextureAndPostProcesses();
  95402. }
  95403. };
  95404. /**
  95405. * Determine if a given mesh will be used in the current effect.
  95406. * @param mesh mesh to test
  95407. * @returns true if the mesh will be used
  95408. */
  95409. EffectLayer.prototype.hasMesh = function (mesh) {
  95410. return true;
  95411. };
  95412. /**
  95413. * Returns true if the layer contains information to display, otherwise false.
  95414. * @returns true if the glow layer should be rendered
  95415. */
  95416. EffectLayer.prototype.shouldRender = function () {
  95417. return this.isEnabled && this._shouldRender;
  95418. };
  95419. /**
  95420. * Returns true if the mesh should render, otherwise false.
  95421. * @param mesh The mesh to render
  95422. * @returns true if it should render otherwise false
  95423. */
  95424. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  95425. return true;
  95426. };
  95427. /**
  95428. * Returns true if the mesh should render, otherwise false.
  95429. * @param mesh The mesh to render
  95430. * @returns true if it should render otherwise false
  95431. */
  95432. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  95433. return true;
  95434. };
  95435. /**
  95436. * Renders the submesh passed in parameter to the generation map.
  95437. */
  95438. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  95439. var _this = this;
  95440. if (!this.shouldRender()) {
  95441. return;
  95442. }
  95443. var material = subMesh.getMaterial();
  95444. var mesh = subMesh.getRenderingMesh();
  95445. var scene = this._scene;
  95446. var engine = scene.getEngine();
  95447. if (!material) {
  95448. return;
  95449. }
  95450. // Do not block in blend mode.
  95451. if (material.needAlphaBlendingForMesh(mesh)) {
  95452. return;
  95453. }
  95454. // Culling
  95455. engine.setState(material.backFaceCulling);
  95456. // Managing instances
  95457. var batch = mesh._getInstancesRenderList(subMesh._id);
  95458. if (batch.mustReturn) {
  95459. return;
  95460. }
  95461. // Early Exit per mesh
  95462. if (!this._shouldRenderMesh(mesh)) {
  95463. return;
  95464. }
  95465. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95466. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  95467. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  95468. engine.enableEffect(this._effectLayerMapGenerationEffect);
  95469. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  95470. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  95471. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  95472. // Alpha test
  95473. if (material && material.needAlphaTesting()) {
  95474. var alphaTexture = material.getAlphaTestTexture();
  95475. if (alphaTexture) {
  95476. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  95477. var textureMatrix = alphaTexture.getTextureMatrix();
  95478. if (textureMatrix) {
  95479. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  95480. }
  95481. }
  95482. }
  95483. // Glow emissive only
  95484. if (this._emissiveTextureAndColor.texture) {
  95485. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  95486. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  95487. }
  95488. // Bones
  95489. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95490. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95491. }
  95492. // Morph targets
  95493. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  95494. // Draw
  95495. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  95496. }
  95497. else {
  95498. // Need to reset refresh rate of the shadowMap
  95499. this._mainTexture.resetRefreshCounter();
  95500. }
  95501. };
  95502. /**
  95503. * Rebuild the required buffers.
  95504. * @hidden Internal use only.
  95505. */
  95506. EffectLayer.prototype._rebuild = function () {
  95507. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95508. if (vb) {
  95509. vb._rebuild();
  95510. }
  95511. this._generateIndexBuffer();
  95512. };
  95513. /**
  95514. * Dispose only the render target textures and post process.
  95515. */
  95516. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  95517. this._mainTexture.dispose();
  95518. for (var i = 0; i < this._postProcesses.length; i++) {
  95519. if (this._postProcesses[i]) {
  95520. this._postProcesses[i].dispose();
  95521. }
  95522. }
  95523. this._postProcesses = [];
  95524. for (var i = 0; i < this._textures.length; i++) {
  95525. if (this._textures[i]) {
  95526. this._textures[i].dispose();
  95527. }
  95528. }
  95529. this._textures = [];
  95530. };
  95531. /**
  95532. * Dispose the highlight layer and free resources.
  95533. */
  95534. EffectLayer.prototype.dispose = function () {
  95535. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95536. if (vertexBuffer) {
  95537. vertexBuffer.dispose();
  95538. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95539. }
  95540. if (this._indexBuffer) {
  95541. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95542. this._indexBuffer = null;
  95543. }
  95544. // Clean textures and post processes
  95545. this._disposeTextureAndPostProcesses();
  95546. // Remove from scene
  95547. var index = this._scene.effectLayers.indexOf(this, 0);
  95548. if (index > -1) {
  95549. this._scene.effectLayers.splice(index, 1);
  95550. }
  95551. // Callback
  95552. this.onDisposeObservable.notifyObservers(this);
  95553. this.onDisposeObservable.clear();
  95554. this.onBeforeRenderMainTextureObservable.clear();
  95555. this.onBeforeComposeObservable.clear();
  95556. this.onAfterComposeObservable.clear();
  95557. this.onSizeChangedObservable.clear();
  95558. };
  95559. /**
  95560. * Gets the class name of the effect layer
  95561. * @returns the string with the class name of the effect layer
  95562. */
  95563. EffectLayer.prototype.getClassName = function () {
  95564. return "EffectLayer";
  95565. };
  95566. /**
  95567. * Creates an effect layer from parsed effect layer data
  95568. * @param parsedEffectLayer defines effect layer data
  95569. * @param scene defines the current scene
  95570. * @param rootUrl defines the root URL containing the effect layer information
  95571. * @returns a parsed effect Layer
  95572. */
  95573. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  95574. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  95575. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  95576. };
  95577. __decorate([
  95578. BABYLON.serialize()
  95579. ], EffectLayer.prototype, "name", void 0);
  95580. __decorate([
  95581. BABYLON.serializeAsColor4()
  95582. ], EffectLayer.prototype, "neutralColor", void 0);
  95583. __decorate([
  95584. BABYLON.serialize()
  95585. ], EffectLayer.prototype, "isEnabled", void 0);
  95586. __decorate([
  95587. BABYLON.serializeAsCameraReference()
  95588. ], EffectLayer.prototype, "camera", null);
  95589. return EffectLayer;
  95590. }());
  95591. BABYLON.EffectLayer = EffectLayer;
  95592. })(BABYLON || (BABYLON = {}));
  95593. //# sourceMappingURL=babylon.effectLayer.js.map
  95594. var BABYLON;
  95595. (function (BABYLON) {
  95596. /**
  95597. * Special Glow Blur post process only blurring the alpha channel
  95598. * It enforces keeping the most luminous color in the color channel.
  95599. */
  95600. var GlowBlurPostProcess = /** @class */ (function (_super) {
  95601. __extends(GlowBlurPostProcess, _super);
  95602. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  95603. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  95604. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  95605. _this.direction = direction;
  95606. _this.kernel = kernel;
  95607. _this.onApplyObservable.add(function (effect) {
  95608. effect.setFloat2("screenSize", _this.width, _this.height);
  95609. effect.setVector2("direction", _this.direction);
  95610. effect.setFloat("blurWidth", _this.kernel);
  95611. });
  95612. return _this;
  95613. }
  95614. return GlowBlurPostProcess;
  95615. }(BABYLON.PostProcess));
  95616. /**
  95617. * The highlight layer Helps adding a glow effect around a mesh.
  95618. *
  95619. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95620. * glowy meshes to your scene.
  95621. *
  95622. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  95623. */
  95624. var HighlightLayer = /** @class */ (function (_super) {
  95625. __extends(HighlightLayer, _super);
  95626. /**
  95627. * Instantiates a new highlight Layer and references it to the scene..
  95628. * @param name The name of the layer
  95629. * @param scene The scene to use the layer in
  95630. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  95631. */
  95632. function HighlightLayer(name, scene, options) {
  95633. var _this = _super.call(this, name, scene) || this;
  95634. _this.name = name;
  95635. /**
  95636. * Specifies whether or not the inner glow is ACTIVE in the layer.
  95637. */
  95638. _this.innerGlow = true;
  95639. /**
  95640. * Specifies whether or not the outer glow is ACTIVE in the layer.
  95641. */
  95642. _this.outerGlow = true;
  95643. /**
  95644. * An event triggered when the highlight layer is being blurred.
  95645. */
  95646. _this.onBeforeBlurObservable = new BABYLON.Observable();
  95647. /**
  95648. * An event triggered when the highlight layer has been blurred.
  95649. */
  95650. _this.onAfterBlurObservable = new BABYLON.Observable();
  95651. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  95652. _this._meshes = {};
  95653. _this._excludedMeshes = {};
  95654. _this.neutralColor = HighlightLayer.NeutralColor;
  95655. // Warn on stencil
  95656. if (!_this._engine.isStencilEnable) {
  95657. 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 }");
  95658. }
  95659. // Adapt options
  95660. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95661. // Initialize the layer
  95662. _this._init({
  95663. alphaBlendingMode: _this._options.alphaBlendingMode,
  95664. camera: _this._options.camera,
  95665. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95666. mainTextureRatio: _this._options.mainTextureRatio
  95667. });
  95668. // Do not render as long as no meshes have been added
  95669. _this._shouldRender = false;
  95670. return _this;
  95671. }
  95672. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  95673. /**
  95674. * Gets the horizontal size of the blur.
  95675. */
  95676. get: function () {
  95677. return this._horizontalBlurPostprocess.kernel;
  95678. },
  95679. /**
  95680. * Specifies the horizontal size of the blur.
  95681. */
  95682. set: function (value) {
  95683. this._horizontalBlurPostprocess.kernel = value;
  95684. },
  95685. enumerable: true,
  95686. configurable: true
  95687. });
  95688. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  95689. /**
  95690. * Gets the vertical size of the blur.
  95691. */
  95692. get: function () {
  95693. return this._verticalBlurPostprocess.kernel;
  95694. },
  95695. /**
  95696. * Specifies the vertical size of the blur.
  95697. */
  95698. set: function (value) {
  95699. this._verticalBlurPostprocess.kernel = value;
  95700. },
  95701. enumerable: true,
  95702. configurable: true
  95703. });
  95704. /**
  95705. * Get the effect name of the layer.
  95706. * @return The effect name
  95707. */
  95708. HighlightLayer.prototype.getEffectName = function () {
  95709. return HighlightLayer.EffectName;
  95710. };
  95711. /**
  95712. * Create the merge effect. This is the shader use to blit the information back
  95713. * to the main canvas at the end of the scene rendering.
  95714. */
  95715. HighlightLayer.prototype._createMergeEffect = function () {
  95716. // Effect
  95717. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  95718. };
  95719. /**
  95720. * Creates the render target textures and post processes used in the highlight layer.
  95721. */
  95722. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  95723. var _this = this;
  95724. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  95725. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  95726. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95727. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95728. var textureType = 0;
  95729. if (this._engine.getCaps().textureHalfFloatRender) {
  95730. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95731. }
  95732. else {
  95733. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95734. }
  95735. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  95736. width: blurTextureWidth,
  95737. height: blurTextureHeight
  95738. }, this._scene, false, true, textureType);
  95739. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95740. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95741. this._blurTexture.anisotropicFilteringLevel = 16;
  95742. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  95743. this._blurTexture.renderParticles = false;
  95744. this._blurTexture.ignoreCameraViewport = true;
  95745. this._textures = [this._blurTexture];
  95746. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  95747. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95748. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  95749. effect.setTexture("textureSampler", _this._mainTexture);
  95750. });
  95751. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95752. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95753. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95754. });
  95755. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95756. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  95757. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95758. });
  95759. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95760. }
  95761. else {
  95762. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  95763. width: blurTextureWidth,
  95764. height: blurTextureHeight
  95765. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95766. this._horizontalBlurPostprocess.width = blurTextureWidth;
  95767. this._horizontalBlurPostprocess.height = blurTextureHeight;
  95768. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95769. effect.setTexture("textureSampler", _this._mainTexture);
  95770. });
  95771. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  95772. width: blurTextureWidth,
  95773. height: blurTextureHeight
  95774. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95775. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95776. }
  95777. this._mainTexture.onAfterUnbindObservable.add(function () {
  95778. _this.onBeforeBlurObservable.notifyObservers(_this);
  95779. var internalTexture = _this._blurTexture.getInternalTexture();
  95780. if (internalTexture) {
  95781. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  95782. }
  95783. _this.onAfterBlurObservable.notifyObservers(_this);
  95784. });
  95785. // Prevent autoClear.
  95786. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95787. };
  95788. /**
  95789. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95790. */
  95791. HighlightLayer.prototype.needStencil = function () {
  95792. return true;
  95793. };
  95794. /**
  95795. * Checks for the readiness of the element composing the layer.
  95796. * @param subMesh the mesh to check for
  95797. * @param useInstances specify wether or not to use instances to render the mesh
  95798. * @param emissiveTexture the associated emissive texture used to generate the glow
  95799. * @return true if ready otherwise, false
  95800. */
  95801. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  95802. var material = subMesh.getMaterial();
  95803. var mesh = subMesh.getRenderingMesh();
  95804. if (!material || !mesh || !this._meshes) {
  95805. return false;
  95806. }
  95807. var emissiveTexture = null;
  95808. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95809. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95810. emissiveTexture = material.emissiveTexture;
  95811. }
  95812. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95813. };
  95814. /**
  95815. * Implementation specific of rendering the generating effect on the main canvas.
  95816. * @param effect The effect used to render through
  95817. */
  95818. HighlightLayer.prototype._internalRender = function (effect) {
  95819. // Texture
  95820. effect.setTexture("textureSampler", this._blurTexture);
  95821. // Cache
  95822. var engine = this._engine;
  95823. var previousStencilBuffer = engine.getStencilBuffer();
  95824. var previousStencilFunction = engine.getStencilFunction();
  95825. var previousStencilMask = engine.getStencilMask();
  95826. var previousStencilOperationPass = engine.getStencilOperationPass();
  95827. var previousStencilOperationFail = engine.getStencilOperationFail();
  95828. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  95829. var previousStencilReference = engine.getStencilFunctionReference();
  95830. // Stencil operations
  95831. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  95832. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  95833. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  95834. // Draw order
  95835. engine.setStencilMask(0x00);
  95836. engine.setStencilBuffer(true);
  95837. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  95838. // 2 passes inner outer
  95839. if (this.outerGlow) {
  95840. effect.setFloat("offset", 0);
  95841. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  95842. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95843. }
  95844. if (this.innerGlow) {
  95845. effect.setFloat("offset", 1);
  95846. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  95847. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95848. }
  95849. // Restore Cache
  95850. engine.setStencilFunction(previousStencilFunction);
  95851. engine.setStencilMask(previousStencilMask);
  95852. engine.setStencilBuffer(previousStencilBuffer);
  95853. engine.setStencilOperationPass(previousStencilOperationPass);
  95854. engine.setStencilOperationFail(previousStencilOperationFail);
  95855. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  95856. engine.setStencilFunctionReference(previousStencilReference);
  95857. };
  95858. /**
  95859. * Returns true if the layer contains information to display, otherwise false.
  95860. */
  95861. HighlightLayer.prototype.shouldRender = function () {
  95862. if (_super.prototype.shouldRender.call(this)) {
  95863. return this._meshes ? true : false;
  95864. }
  95865. return false;
  95866. };
  95867. /**
  95868. * Returns true if the mesh should render, otherwise false.
  95869. * @param mesh The mesh to render
  95870. * @returns true if it should render otherwise false
  95871. */
  95872. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  95873. // Excluded Mesh
  95874. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  95875. return false;
  95876. }
  95877. ;
  95878. return true;
  95879. };
  95880. /**
  95881. * Sets the required values for both the emissive texture and and the main color.
  95882. */
  95883. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95884. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95885. if (highlightLayerMesh) {
  95886. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  95887. }
  95888. else {
  95889. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95890. }
  95891. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95892. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95893. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  95894. }
  95895. else {
  95896. this._emissiveTextureAndColor.texture = null;
  95897. }
  95898. };
  95899. /**
  95900. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  95901. * @param mesh The mesh to exclude from the highlight layer
  95902. */
  95903. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  95904. if (!this._excludedMeshes) {
  95905. return;
  95906. }
  95907. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95908. if (!meshExcluded) {
  95909. this._excludedMeshes[mesh.uniqueId] = {
  95910. mesh: mesh,
  95911. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  95912. mesh.getEngine().setStencilBuffer(false);
  95913. }),
  95914. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  95915. mesh.getEngine().setStencilBuffer(true);
  95916. }),
  95917. };
  95918. }
  95919. };
  95920. /**
  95921. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  95922. * @param mesh The mesh to highlight
  95923. */
  95924. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  95925. if (!this._excludedMeshes) {
  95926. return;
  95927. }
  95928. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95929. if (meshExcluded) {
  95930. if (meshExcluded.beforeRender) {
  95931. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  95932. }
  95933. if (meshExcluded.afterRender) {
  95934. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  95935. }
  95936. }
  95937. this._excludedMeshes[mesh.uniqueId] = null;
  95938. };
  95939. /**
  95940. * Determine if a given mesh will be highlighted by the current HighlightLayer
  95941. * @param mesh mesh to test
  95942. * @returns true if the mesh will be highlighted by the current HighlightLayer
  95943. */
  95944. HighlightLayer.prototype.hasMesh = function (mesh) {
  95945. if (!this._meshes) {
  95946. return false;
  95947. }
  95948. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  95949. };
  95950. /**
  95951. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  95952. * @param mesh The mesh to highlight
  95953. * @param color The color of the highlight
  95954. * @param glowEmissiveOnly Extract the glow from the emissive texture
  95955. */
  95956. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  95957. var _this = this;
  95958. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  95959. if (!this._meshes) {
  95960. return;
  95961. }
  95962. var meshHighlight = this._meshes[mesh.uniqueId];
  95963. if (meshHighlight) {
  95964. meshHighlight.color = color;
  95965. }
  95966. else {
  95967. this._meshes[mesh.uniqueId] = {
  95968. mesh: mesh,
  95969. color: color,
  95970. // Lambda required for capture due to Observable this context
  95971. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  95972. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  95973. _this._defaultStencilReference(mesh);
  95974. }
  95975. else {
  95976. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  95977. }
  95978. }),
  95979. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  95980. glowEmissiveOnly: glowEmissiveOnly
  95981. };
  95982. }
  95983. this._shouldRender = true;
  95984. };
  95985. /**
  95986. * Remove a mesh from the highlight layer in order to make it stop glowing.
  95987. * @param mesh The mesh to highlight
  95988. */
  95989. HighlightLayer.prototype.removeMesh = function (mesh) {
  95990. if (!this._meshes) {
  95991. return;
  95992. }
  95993. var meshHighlight = this._meshes[mesh.uniqueId];
  95994. if (meshHighlight) {
  95995. if (meshHighlight.observerHighlight) {
  95996. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95997. }
  95998. if (meshHighlight.observerDefault) {
  95999. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96000. }
  96001. delete this._meshes[mesh.uniqueId];
  96002. }
  96003. this._shouldRender = false;
  96004. for (var meshHighlightToCheck in this._meshes) {
  96005. if (this._meshes[meshHighlightToCheck]) {
  96006. this._shouldRender = true;
  96007. break;
  96008. }
  96009. }
  96010. };
  96011. /**
  96012. * Force the stencil to the normal expected value for none glowing parts
  96013. */
  96014. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  96015. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  96016. };
  96017. /**
  96018. * Free any resources and references associated to a mesh.
  96019. * Internal use
  96020. * @param mesh The mesh to free.
  96021. */
  96022. HighlightLayer.prototype._disposeMesh = function (mesh) {
  96023. this.removeMesh(mesh);
  96024. this.removeExcludedMesh(mesh);
  96025. };
  96026. /**
  96027. * Dispose the highlight layer and free resources.
  96028. */
  96029. HighlightLayer.prototype.dispose = function () {
  96030. if (this._meshes) {
  96031. // Clean mesh references
  96032. for (var id in this._meshes) {
  96033. var meshHighlight = this._meshes[id];
  96034. if (meshHighlight && meshHighlight.mesh) {
  96035. if (meshHighlight.observerHighlight) {
  96036. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96037. }
  96038. if (meshHighlight.observerDefault) {
  96039. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96040. }
  96041. }
  96042. }
  96043. this._meshes = null;
  96044. }
  96045. if (this._excludedMeshes) {
  96046. for (var id in this._excludedMeshes) {
  96047. var meshHighlight = this._excludedMeshes[id];
  96048. if (meshHighlight) {
  96049. if (meshHighlight.beforeRender) {
  96050. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  96051. }
  96052. if (meshHighlight.afterRender) {
  96053. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  96054. }
  96055. }
  96056. }
  96057. this._excludedMeshes = null;
  96058. }
  96059. _super.prototype.dispose.call(this);
  96060. };
  96061. /**
  96062. * Gets the class name of the effect layer
  96063. * @returns the string with the class name of the effect layer
  96064. */
  96065. HighlightLayer.prototype.getClassName = function () {
  96066. return "HighlightLayer";
  96067. };
  96068. /**
  96069. * Serializes this Highlight layer
  96070. * @returns a serialized Highlight layer object
  96071. */
  96072. HighlightLayer.prototype.serialize = function () {
  96073. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96074. serializationObject.customType = "BABYLON.HighlightLayer";
  96075. // Highlighted meshes
  96076. serializationObject.meshes = [];
  96077. if (this._meshes) {
  96078. for (var m in this._meshes) {
  96079. var mesh = this._meshes[m];
  96080. if (mesh) {
  96081. serializationObject.meshes.push({
  96082. glowEmissiveOnly: mesh.glowEmissiveOnly,
  96083. color: mesh.color.asArray(),
  96084. meshId: mesh.mesh.id
  96085. });
  96086. }
  96087. }
  96088. }
  96089. // Excluded meshes
  96090. serializationObject.excludedMeshes = [];
  96091. if (this._excludedMeshes) {
  96092. for (var e in this._excludedMeshes) {
  96093. var excludedMesh = this._excludedMeshes[e];
  96094. if (excludedMesh) {
  96095. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  96096. }
  96097. }
  96098. }
  96099. return serializationObject;
  96100. };
  96101. /**
  96102. * Creates a Highlight layer from parsed Highlight layer data
  96103. * @param parsedHightlightLayer defines the Highlight layer data
  96104. * @param scene defines the current scene
  96105. * @param rootUrl defines the root URL containing the Highlight layer information
  96106. * @returns a parsed Highlight layer
  96107. */
  96108. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  96109. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  96110. var index;
  96111. // Excluded meshes
  96112. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  96113. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  96114. if (mesh) {
  96115. hl.addExcludedMesh(mesh);
  96116. }
  96117. }
  96118. // Included meshes
  96119. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  96120. var highlightedMesh = parsedHightlightLayer.meshes[index];
  96121. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  96122. if (mesh) {
  96123. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  96124. }
  96125. }
  96126. return hl;
  96127. };
  96128. /**
  96129. * Effect Name of the highlight layer.
  96130. */
  96131. HighlightLayer.EffectName = "HighlightLayer";
  96132. /**
  96133. * The neutral color used during the preparation of the glow effect.
  96134. * This is black by default as the blend operation is a blend operation.
  96135. */
  96136. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  96137. /**
  96138. * Stencil value used for glowing meshes.
  96139. */
  96140. HighlightLayer.GlowingMeshStencilReference = 0x02;
  96141. /**
  96142. * Stencil value used for the other meshes in the scene.
  96143. */
  96144. HighlightLayer.NormalMeshStencilReference = 0x01;
  96145. __decorate([
  96146. BABYLON.serialize()
  96147. ], HighlightLayer.prototype, "innerGlow", void 0);
  96148. __decorate([
  96149. BABYLON.serialize()
  96150. ], HighlightLayer.prototype, "outerGlow", void 0);
  96151. __decorate([
  96152. BABYLON.serialize()
  96153. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96154. __decorate([
  96155. BABYLON.serialize()
  96156. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96157. __decorate([
  96158. BABYLON.serialize("options")
  96159. ], HighlightLayer.prototype, "_options", void 0);
  96160. return HighlightLayer;
  96161. }(BABYLON.EffectLayer));
  96162. BABYLON.HighlightLayer = HighlightLayer;
  96163. })(BABYLON || (BABYLON = {}));
  96164. //# sourceMappingURL=babylon.highlightLayer.js.map
  96165. var BABYLON;
  96166. (function (BABYLON) {
  96167. /**
  96168. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96169. *
  96170. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96171. * glowy meshes to your scene.
  96172. *
  96173. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96174. */
  96175. var GlowLayer = /** @class */ (function (_super) {
  96176. __extends(GlowLayer, _super);
  96177. /**
  96178. * Instantiates a new glow Layer and references it to the scene.
  96179. * @param name The name of the layer
  96180. * @param scene The scene to use the layer in
  96181. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96182. */
  96183. function GlowLayer(name, scene, options) {
  96184. var _this = _super.call(this, name, scene) || this;
  96185. _this._intensity = 1.0;
  96186. _this._includedOnlyMeshes = [];
  96187. _this._excludedMeshes = [];
  96188. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96189. // Adapt options
  96190. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  96191. // Initialize the layer
  96192. _this._init({
  96193. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  96194. camera: _this._options.camera,
  96195. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96196. mainTextureRatio: _this._options.mainTextureRatio
  96197. });
  96198. return _this;
  96199. }
  96200. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  96201. /**
  96202. * Gets the kernel size of the blur.
  96203. */
  96204. get: function () {
  96205. return this._horizontalBlurPostprocess1.kernel;
  96206. },
  96207. /**
  96208. * Sets the kernel size of the blur.
  96209. */
  96210. set: function (value) {
  96211. this._horizontalBlurPostprocess1.kernel = value;
  96212. this._verticalBlurPostprocess1.kernel = value;
  96213. this._horizontalBlurPostprocess2.kernel = value;
  96214. this._verticalBlurPostprocess2.kernel = value;
  96215. },
  96216. enumerable: true,
  96217. configurable: true
  96218. });
  96219. Object.defineProperty(GlowLayer.prototype, "intensity", {
  96220. /**
  96221. * Gets the glow intensity.
  96222. */
  96223. get: function () {
  96224. return this._intensity;
  96225. },
  96226. /**
  96227. * Sets the glow intensity.
  96228. */
  96229. set: function (value) {
  96230. this._intensity = value;
  96231. },
  96232. enumerable: true,
  96233. configurable: true
  96234. });
  96235. /**
  96236. * Get the effect name of the layer.
  96237. * @return The effect name
  96238. */
  96239. GlowLayer.prototype.getEffectName = function () {
  96240. return GlowLayer.EffectName;
  96241. };
  96242. /**
  96243. * Create the merge effect. This is the shader use to blit the information back
  96244. * to the main canvas at the end of the scene rendering.
  96245. */
  96246. GlowLayer.prototype._createMergeEffect = function () {
  96247. // Effect
  96248. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  96249. };
  96250. /**
  96251. * Creates the render target textures and post processes used in the glow layer.
  96252. */
  96253. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  96254. var _this = this;
  96255. var blurTextureWidth = this._mainTextureDesiredSize.width;
  96256. var blurTextureHeight = this._mainTextureDesiredSize.height;
  96257. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96258. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96259. var textureType = 0;
  96260. if (this._engine.getCaps().textureHalfFloatRender) {
  96261. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96262. }
  96263. else {
  96264. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96265. }
  96266. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  96267. width: blurTextureWidth,
  96268. height: blurTextureHeight
  96269. }, this._scene, false, true, textureType);
  96270. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96271. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96272. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96273. this._blurTexture1.renderParticles = false;
  96274. this._blurTexture1.ignoreCameraViewport = true;
  96275. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  96276. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  96277. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  96278. width: blurTextureWidth2,
  96279. height: blurTextureHeight2
  96280. }, this._scene, false, true, textureType);
  96281. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96282. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96283. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96284. this._blurTexture2.renderParticles = false;
  96285. this._blurTexture2.ignoreCameraViewport = true;
  96286. this._textures = [this._blurTexture1, this._blurTexture2];
  96287. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96288. width: blurTextureWidth,
  96289. height: blurTextureHeight
  96290. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96291. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  96292. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  96293. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  96294. effect.setTexture("textureSampler", _this._mainTexture);
  96295. });
  96296. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96297. width: blurTextureWidth,
  96298. height: blurTextureHeight
  96299. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96300. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96301. width: blurTextureWidth2,
  96302. height: blurTextureHeight2
  96303. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96304. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  96305. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  96306. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  96307. effect.setTexture("textureSampler", _this._blurTexture1);
  96308. });
  96309. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96310. width: blurTextureWidth2,
  96311. height: blurTextureHeight2
  96312. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96313. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96314. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  96315. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96316. this._mainTexture.samples = this._options.mainTextureSamples;
  96317. this._mainTexture.onAfterUnbindObservable.add(function () {
  96318. var internalTexture = _this._blurTexture1.getInternalTexture();
  96319. if (internalTexture) {
  96320. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  96321. internalTexture = _this._blurTexture2.getInternalTexture();
  96322. if (internalTexture) {
  96323. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  96324. }
  96325. }
  96326. });
  96327. // Prevent autoClear.
  96328. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96329. };
  96330. /**
  96331. * Checks for the readiness of the element composing the layer.
  96332. * @param subMesh the mesh to check for
  96333. * @param useInstances specify wether or not to use instances to render the mesh
  96334. * @param emissiveTexture the associated emissive texture used to generate the glow
  96335. * @return true if ready otherwise, false
  96336. */
  96337. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  96338. var material = subMesh.getMaterial();
  96339. var mesh = subMesh.getRenderingMesh();
  96340. if (!material || !mesh) {
  96341. return false;
  96342. }
  96343. var emissiveTexture = material.emissiveTexture;
  96344. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96345. };
  96346. /**
  96347. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96348. */
  96349. GlowLayer.prototype.needStencil = function () {
  96350. return false;
  96351. };
  96352. /**
  96353. * Implementation specific of rendering the generating effect on the main canvas.
  96354. * @param effect The effect used to render through
  96355. */
  96356. GlowLayer.prototype._internalRender = function (effect) {
  96357. // Texture
  96358. effect.setTexture("textureSampler", this._blurTexture1);
  96359. effect.setTexture("textureSampler2", this._blurTexture2);
  96360. effect.setFloat("offset", this._intensity);
  96361. // Cache
  96362. var engine = this._engine;
  96363. var previousStencilBuffer = engine.getStencilBuffer();
  96364. // Draw order
  96365. engine.setStencilBuffer(false);
  96366. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96367. // Draw order
  96368. engine.setStencilBuffer(previousStencilBuffer);
  96369. };
  96370. /**
  96371. * Sets the required values for both the emissive texture and and the main color.
  96372. */
  96373. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96374. var textureLevel = 1.0;
  96375. if (this.customEmissiveTextureSelector) {
  96376. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  96377. }
  96378. else {
  96379. if (material) {
  96380. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96381. if (this._emissiveTextureAndColor.texture) {
  96382. textureLevel = this._emissiveTextureAndColor.texture.level;
  96383. }
  96384. }
  96385. else {
  96386. this._emissiveTextureAndColor.texture = null;
  96387. }
  96388. }
  96389. if (this.customEmissiveColorSelector) {
  96390. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  96391. }
  96392. else {
  96393. if (material.emissiveColor) {
  96394. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  96395. }
  96396. else {
  96397. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96398. }
  96399. }
  96400. };
  96401. /**
  96402. * Returns true if the mesh should render, otherwise false.
  96403. * @param mesh The mesh to render
  96404. * @returns true if it should render otherwise false
  96405. */
  96406. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  96407. return this.hasMesh(mesh);
  96408. };
  96409. /**
  96410. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  96411. * @param mesh The mesh to exclude from the glow layer
  96412. */
  96413. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  96414. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  96415. this._excludedMeshes.push(mesh.uniqueId);
  96416. }
  96417. };
  96418. /**
  96419. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  96420. * @param mesh The mesh to remove
  96421. */
  96422. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  96423. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  96424. if (index !== -1) {
  96425. this._excludedMeshes.splice(index, 1);
  96426. }
  96427. };
  96428. /**
  96429. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  96430. * @param mesh The mesh to include in the glow layer
  96431. */
  96432. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  96433. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  96434. this._includedOnlyMeshes.push(mesh.uniqueId);
  96435. }
  96436. };
  96437. /**
  96438. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  96439. * @param mesh The mesh to remove
  96440. */
  96441. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  96442. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  96443. if (index !== -1) {
  96444. this._includedOnlyMeshes.splice(index, 1);
  96445. }
  96446. };
  96447. /**
  96448. * Determine if a given mesh will be used in the glow layer
  96449. * @param mesh The mesh to test
  96450. * @returns true if the mesh will be highlighted by the current glow layer
  96451. */
  96452. GlowLayer.prototype.hasMesh = function (mesh) {
  96453. // Included Mesh
  96454. if (this._includedOnlyMeshes.length) {
  96455. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  96456. }
  96457. ;
  96458. // Excluded Mesh
  96459. if (this._excludedMeshes.length) {
  96460. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  96461. }
  96462. ;
  96463. return true;
  96464. };
  96465. /**
  96466. * Free any resources and references associated to a mesh.
  96467. * Internal use
  96468. * @param mesh The mesh to free.
  96469. */
  96470. GlowLayer.prototype._disposeMesh = function (mesh) {
  96471. this.removeIncludedOnlyMesh(mesh);
  96472. this.removeExcludedMesh(mesh);
  96473. };
  96474. /**
  96475. * Gets the class name of the effect layer
  96476. * @returns the string with the class name of the effect layer
  96477. */
  96478. GlowLayer.prototype.getClassName = function () {
  96479. return "GlowLayer";
  96480. };
  96481. /**
  96482. * Serializes this glow layer
  96483. * @returns a serialized glow layer object
  96484. */
  96485. GlowLayer.prototype.serialize = function () {
  96486. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96487. serializationObject.customType = "BABYLON.GlowLayer";
  96488. var index;
  96489. // Included meshes
  96490. serializationObject.includedMeshes = [];
  96491. if (this._includedOnlyMeshes.length) {
  96492. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  96493. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  96494. if (mesh) {
  96495. serializationObject.includedMeshes.push(mesh.id);
  96496. }
  96497. }
  96498. }
  96499. // Excluded meshes
  96500. serializationObject.excludedMeshes = [];
  96501. if (this._excludedMeshes.length) {
  96502. for (index = 0; index < this._excludedMeshes.length; index++) {
  96503. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  96504. if (mesh) {
  96505. serializationObject.excludedMeshes.push(mesh.id);
  96506. }
  96507. }
  96508. }
  96509. return serializationObject;
  96510. };
  96511. /**
  96512. * Creates a Glow Layer from parsed glow layer data
  96513. * @param parsedGlowLayer defines glow layer data
  96514. * @param scene defines the current scene
  96515. * @param rootUrl defines the root URL containing the glow layer information
  96516. * @returns a parsed Glow Layer
  96517. */
  96518. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  96519. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  96520. var index;
  96521. // Excluded meshes
  96522. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  96523. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  96524. if (mesh) {
  96525. gl.addExcludedMesh(mesh);
  96526. }
  96527. }
  96528. // Included meshes
  96529. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  96530. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  96531. if (mesh) {
  96532. gl.addIncludedOnlyMesh(mesh);
  96533. }
  96534. }
  96535. return gl;
  96536. };
  96537. /**
  96538. * Effect Name of the layer.
  96539. */
  96540. GlowLayer.EffectName = "GlowLayer";
  96541. /**
  96542. * The default blur kernel size used for the glow.
  96543. */
  96544. GlowLayer.DefaultBlurKernelSize = 32;
  96545. /**
  96546. * The default texture size ratio used for the glow.
  96547. */
  96548. GlowLayer.DefaultTextureRatio = 0.5;
  96549. __decorate([
  96550. BABYLON.serialize()
  96551. ], GlowLayer.prototype, "blurKernelSize", null);
  96552. __decorate([
  96553. BABYLON.serialize()
  96554. ], GlowLayer.prototype, "intensity", null);
  96555. __decorate([
  96556. BABYLON.serialize("options")
  96557. ], GlowLayer.prototype, "_options", void 0);
  96558. return GlowLayer;
  96559. }(BABYLON.EffectLayer));
  96560. BABYLON.GlowLayer = GlowLayer;
  96561. })(BABYLON || (BABYLON = {}));
  96562. //# sourceMappingURL=babylon.glowLayer.js.map
  96563. var BABYLON;
  96564. (function (BABYLON) {
  96565. /**
  96566. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  96567. */
  96568. var AssetTaskState;
  96569. (function (AssetTaskState) {
  96570. /**
  96571. * Initialization
  96572. */
  96573. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  96574. /**
  96575. * Running
  96576. */
  96577. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  96578. /**
  96579. * Done
  96580. */
  96581. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  96582. /**
  96583. * Error
  96584. */
  96585. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  96586. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  96587. /**
  96588. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  96589. */
  96590. var AbstractAssetTask = /** @class */ (function () {
  96591. /**
  96592. * Creates a new {BABYLON.AssetsManager}
  96593. * @param name defines the name of the task
  96594. */
  96595. function AbstractAssetTask(
  96596. /**
  96597. * Task name
  96598. */ name) {
  96599. this.name = name;
  96600. this._isCompleted = false;
  96601. this._taskState = AssetTaskState.INIT;
  96602. }
  96603. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  96604. /**
  96605. * Get if the task is completed
  96606. */
  96607. get: function () {
  96608. return this._isCompleted;
  96609. },
  96610. enumerable: true,
  96611. configurable: true
  96612. });
  96613. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  96614. /**
  96615. * Gets the current state of the task
  96616. */
  96617. get: function () {
  96618. return this._taskState;
  96619. },
  96620. enumerable: true,
  96621. configurable: true
  96622. });
  96623. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  96624. /**
  96625. * Gets the current error object (if task is in error)
  96626. */
  96627. get: function () {
  96628. return this._errorObject;
  96629. },
  96630. enumerable: true,
  96631. configurable: true
  96632. });
  96633. /**
  96634. * Internal only
  96635. * @hidden
  96636. */
  96637. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  96638. if (this._errorObject) {
  96639. return;
  96640. }
  96641. this._errorObject = {
  96642. message: message,
  96643. exception: exception
  96644. };
  96645. };
  96646. /**
  96647. * Execute the current task
  96648. * @param scene defines the scene where you want your assets to be loaded
  96649. * @param onSuccess is a callback called when the task is successfully executed
  96650. * @param onError is a callback called if an error occurs
  96651. */
  96652. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96653. var _this = this;
  96654. this._taskState = AssetTaskState.RUNNING;
  96655. this.runTask(scene, function () {
  96656. _this.onDoneCallback(onSuccess, onError);
  96657. }, function (msg, exception) {
  96658. _this.onErrorCallback(onError, msg, exception);
  96659. });
  96660. };
  96661. /**
  96662. * Execute the current task
  96663. * @param scene defines the scene where you want your assets to be loaded
  96664. * @param onSuccess is a callback called when the task is successfully executed
  96665. * @param onError is a callback called if an error occurs
  96666. */
  96667. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96668. throw new Error("runTask is not implemented");
  96669. };
  96670. /**
  96671. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  96672. * This can be used with failed tasks that have the reason for failure fixed.
  96673. */
  96674. AbstractAssetTask.prototype.reset = function () {
  96675. this._taskState = AssetTaskState.INIT;
  96676. };
  96677. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  96678. this._taskState = AssetTaskState.ERROR;
  96679. this._errorObject = {
  96680. message: message,
  96681. exception: exception
  96682. };
  96683. if (this.onError) {
  96684. this.onError(this, message, exception);
  96685. }
  96686. onError();
  96687. };
  96688. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  96689. try {
  96690. this._taskState = AssetTaskState.DONE;
  96691. this._isCompleted = true;
  96692. if (this.onSuccess) {
  96693. this.onSuccess(this);
  96694. }
  96695. onSuccess();
  96696. }
  96697. catch (e) {
  96698. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  96699. }
  96700. };
  96701. return AbstractAssetTask;
  96702. }());
  96703. BABYLON.AbstractAssetTask = AbstractAssetTask;
  96704. /**
  96705. * Class used to share progress information about assets loading
  96706. */
  96707. var AssetsProgressEvent = /** @class */ (function () {
  96708. /**
  96709. * Creates a {BABYLON.AssetsProgressEvent}
  96710. * @param remainingCount defines the number of remaining tasks to process
  96711. * @param totalCount defines the total number of tasks
  96712. * @param task defines the task that was just processed
  96713. */
  96714. function AssetsProgressEvent(remainingCount, totalCount, task) {
  96715. this.remainingCount = remainingCount;
  96716. this.totalCount = totalCount;
  96717. this.task = task;
  96718. }
  96719. return AssetsProgressEvent;
  96720. }());
  96721. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  96722. /**
  96723. * Define a task used by {BABYLON.AssetsManager} to load meshes
  96724. */
  96725. var MeshAssetTask = /** @class */ (function (_super) {
  96726. __extends(MeshAssetTask, _super);
  96727. /**
  96728. * Creates a new {BABYLON.MeshAssetTask}
  96729. * @param name defines the name of the task
  96730. * @param meshesNames defines the list of mesh's names you want to load
  96731. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  96732. * @param sceneFilename defines the filename of the scene to load from
  96733. */
  96734. function MeshAssetTask(
  96735. /**
  96736. * Defines the name of the task
  96737. */
  96738. name,
  96739. /**
  96740. * Defines the list of mesh's names you want to load
  96741. */
  96742. meshesNames,
  96743. /**
  96744. * Defines the root url to use as a base to load your meshes and associated resources
  96745. */
  96746. rootUrl,
  96747. /**
  96748. * Defines the filename of the scene to load from
  96749. */
  96750. sceneFilename) {
  96751. var _this = _super.call(this, name) || this;
  96752. _this.name = name;
  96753. _this.meshesNames = meshesNames;
  96754. _this.rootUrl = rootUrl;
  96755. _this.sceneFilename = sceneFilename;
  96756. return _this;
  96757. }
  96758. /**
  96759. * Execute the current task
  96760. * @param scene defines the scene where you want your assets to be loaded
  96761. * @param onSuccess is a callback called when the task is successfully executed
  96762. * @param onError is a callback called if an error occurs
  96763. */
  96764. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96765. var _this = this;
  96766. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  96767. _this.loadedMeshes = meshes;
  96768. _this.loadedParticleSystems = particleSystems;
  96769. _this.loadedSkeletons = skeletons;
  96770. onSuccess();
  96771. }, null, function (scene, message, exception) {
  96772. onError(message, exception);
  96773. });
  96774. };
  96775. return MeshAssetTask;
  96776. }(AbstractAssetTask));
  96777. BABYLON.MeshAssetTask = MeshAssetTask;
  96778. /**
  96779. * Define a task used by {BABYLON.AssetsManager} to load text content
  96780. */
  96781. var TextFileAssetTask = /** @class */ (function (_super) {
  96782. __extends(TextFileAssetTask, _super);
  96783. /**
  96784. * Creates a new TextFileAssetTask object
  96785. * @param name defines the name of the task
  96786. * @param url defines the location of the file to load
  96787. */
  96788. function TextFileAssetTask(
  96789. /**
  96790. * Defines the name of the task
  96791. */
  96792. name,
  96793. /**
  96794. * Defines the location of the file to load
  96795. */
  96796. url) {
  96797. var _this = _super.call(this, name) || this;
  96798. _this.name = name;
  96799. _this.url = url;
  96800. return _this;
  96801. }
  96802. /**
  96803. * Execute the current task
  96804. * @param scene defines the scene where you want your assets to be loaded
  96805. * @param onSuccess is a callback called when the task is successfully executed
  96806. * @param onError is a callback called if an error occurs
  96807. */
  96808. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96809. var _this = this;
  96810. scene._loadFile(this.url, function (data) {
  96811. _this.text = data;
  96812. onSuccess();
  96813. }, undefined, false, false, function (request, exception) {
  96814. if (request) {
  96815. onError(request.status + " " + request.statusText, exception);
  96816. }
  96817. });
  96818. };
  96819. return TextFileAssetTask;
  96820. }(AbstractAssetTask));
  96821. BABYLON.TextFileAssetTask = TextFileAssetTask;
  96822. /**
  96823. * Define a task used by {BABYLON.AssetsManager} to load binary data
  96824. */
  96825. var BinaryFileAssetTask = /** @class */ (function (_super) {
  96826. __extends(BinaryFileAssetTask, _super);
  96827. /**
  96828. * Creates a new BinaryFileAssetTask object
  96829. * @param name defines the name of the new task
  96830. * @param url defines the location of the file to load
  96831. */
  96832. function BinaryFileAssetTask(
  96833. /**
  96834. * Defines the name of the task
  96835. */
  96836. name,
  96837. /**
  96838. * Defines the location of the file to load
  96839. */
  96840. url) {
  96841. var _this = _super.call(this, name) || this;
  96842. _this.name = name;
  96843. _this.url = url;
  96844. return _this;
  96845. }
  96846. /**
  96847. * Execute the current task
  96848. * @param scene defines the scene where you want your assets to be loaded
  96849. * @param onSuccess is a callback called when the task is successfully executed
  96850. * @param onError is a callback called if an error occurs
  96851. */
  96852. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96853. var _this = this;
  96854. scene._loadFile(this.url, function (data) {
  96855. _this.data = data;
  96856. onSuccess();
  96857. }, undefined, true, true, function (request, exception) {
  96858. if (request) {
  96859. onError(request.status + " " + request.statusText, exception);
  96860. }
  96861. });
  96862. };
  96863. return BinaryFileAssetTask;
  96864. }(AbstractAssetTask));
  96865. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  96866. /**
  96867. * Define a task used by {BABYLON.AssetsManager} to load images
  96868. */
  96869. var ImageAssetTask = /** @class */ (function (_super) {
  96870. __extends(ImageAssetTask, _super);
  96871. /**
  96872. * Creates a new ImageAssetTask
  96873. * @param name defines the name of the task
  96874. * @param url defines the location of the image to load
  96875. */
  96876. function ImageAssetTask(
  96877. /**
  96878. * Defines the name of the task
  96879. */
  96880. name,
  96881. /**
  96882. * Defines the location of the image to load
  96883. */
  96884. url) {
  96885. var _this = _super.call(this, name) || this;
  96886. _this.name = name;
  96887. _this.url = url;
  96888. return _this;
  96889. }
  96890. /**
  96891. * Execute the current task
  96892. * @param scene defines the scene where you want your assets to be loaded
  96893. * @param onSuccess is a callback called when the task is successfully executed
  96894. * @param onError is a callback called if an error occurs
  96895. */
  96896. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96897. var _this = this;
  96898. var img = new Image();
  96899. BABYLON.Tools.SetCorsBehavior(this.url, img);
  96900. img.onload = function () {
  96901. _this.image = img;
  96902. onSuccess();
  96903. };
  96904. img.onerror = function (err) {
  96905. onError("Error loading image", err);
  96906. };
  96907. img.src = this.url;
  96908. };
  96909. return ImageAssetTask;
  96910. }(AbstractAssetTask));
  96911. BABYLON.ImageAssetTask = ImageAssetTask;
  96912. /**
  96913. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  96914. */
  96915. var TextureAssetTask = /** @class */ (function (_super) {
  96916. __extends(TextureAssetTask, _super);
  96917. /**
  96918. * Creates a new TextureAssetTask object
  96919. * @param name defines the name of the task
  96920. * @param url defines the location of the file to load
  96921. * @param noMipmap defines if mipmap should not be generated (default is false)
  96922. * @param invertY defines if texture must be inverted on Y axis (default is false)
  96923. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96924. */
  96925. function TextureAssetTask(
  96926. /**
  96927. * Defines the name of the task
  96928. */
  96929. name,
  96930. /**
  96931. * Defines the location of the file to load
  96932. */
  96933. url,
  96934. /**
  96935. * Defines if mipmap should not be generated (default is false)
  96936. */
  96937. noMipmap,
  96938. /**
  96939. * Defines if texture must be inverted on Y axis (default is false)
  96940. */
  96941. invertY,
  96942. /**
  96943. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96944. */
  96945. samplingMode) {
  96946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96947. var _this = _super.call(this, name) || this;
  96948. _this.name = name;
  96949. _this.url = url;
  96950. _this.noMipmap = noMipmap;
  96951. _this.invertY = invertY;
  96952. _this.samplingMode = samplingMode;
  96953. return _this;
  96954. }
  96955. /**
  96956. * Execute the current task
  96957. * @param scene defines the scene where you want your assets to be loaded
  96958. * @param onSuccess is a callback called when the task is successfully executed
  96959. * @param onError is a callback called if an error occurs
  96960. */
  96961. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96962. var onload = function () {
  96963. onSuccess();
  96964. };
  96965. var onerror = function (message, exception) {
  96966. onError(message, exception);
  96967. };
  96968. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  96969. };
  96970. return TextureAssetTask;
  96971. }(AbstractAssetTask));
  96972. BABYLON.TextureAssetTask = TextureAssetTask;
  96973. /**
  96974. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  96975. */
  96976. var CubeTextureAssetTask = /** @class */ (function (_super) {
  96977. __extends(CubeTextureAssetTask, _super);
  96978. /**
  96979. * Creates a new CubeTextureAssetTask
  96980. * @param name defines the name of the task
  96981. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96982. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96983. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96984. * @param files defines the explicit list of files (undefined by default)
  96985. */
  96986. function CubeTextureAssetTask(
  96987. /**
  96988. * Defines the name of the task
  96989. */
  96990. name,
  96991. /**
  96992. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96993. */
  96994. url,
  96995. /**
  96996. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96997. */
  96998. extensions,
  96999. /**
  97000. * Defines if mipmaps should not be generated (default is false)
  97001. */
  97002. noMipmap,
  97003. /**
  97004. * Defines the explicit list of files (undefined by default)
  97005. */
  97006. files) {
  97007. var _this = _super.call(this, name) || this;
  97008. _this.name = name;
  97009. _this.url = url;
  97010. _this.extensions = extensions;
  97011. _this.noMipmap = noMipmap;
  97012. _this.files = files;
  97013. return _this;
  97014. }
  97015. /**
  97016. * Execute the current task
  97017. * @param scene defines the scene where you want your assets to be loaded
  97018. * @param onSuccess is a callback called when the task is successfully executed
  97019. * @param onError is a callback called if an error occurs
  97020. */
  97021. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97022. var onload = function () {
  97023. onSuccess();
  97024. };
  97025. var onerror = function (message, exception) {
  97026. onError(message, exception);
  97027. };
  97028. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  97029. };
  97030. return CubeTextureAssetTask;
  97031. }(AbstractAssetTask));
  97032. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  97033. /**
  97034. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  97035. */
  97036. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  97037. __extends(HDRCubeTextureAssetTask, _super);
  97038. /**
  97039. * Creates a new HDRCubeTextureAssetTask object
  97040. * @param name defines the name of the task
  97041. * @param url defines the location of the file to load
  97042. * @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.
  97043. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97044. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97045. * @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)
  97046. * @param reserved Internal use only
  97047. */
  97048. function HDRCubeTextureAssetTask(
  97049. /**
  97050. * Defines the name of the task
  97051. */
  97052. name,
  97053. /**
  97054. * Defines the location of the file to load
  97055. */
  97056. url,
  97057. /**
  97058. * Defines the desired size (the more it increases the longer the generation will be)
  97059. */
  97060. size,
  97061. /**
  97062. * Defines if mipmaps should not be generated (default is false)
  97063. */
  97064. noMipmap,
  97065. /**
  97066. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97067. */
  97068. generateHarmonics,
  97069. /**
  97070. * 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)
  97071. */
  97072. gammaSpace,
  97073. /**
  97074. * Internal Use Only
  97075. */
  97076. reserved) {
  97077. if (noMipmap === void 0) { noMipmap = false; }
  97078. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97079. if (gammaSpace === void 0) { gammaSpace = false; }
  97080. if (reserved === void 0) { reserved = false; }
  97081. var _this = _super.call(this, name) || this;
  97082. _this.name = name;
  97083. _this.url = url;
  97084. _this.size = size;
  97085. _this.noMipmap = noMipmap;
  97086. _this.generateHarmonics = generateHarmonics;
  97087. _this.gammaSpace = gammaSpace;
  97088. _this.reserved = reserved;
  97089. return _this;
  97090. }
  97091. /**
  97092. * Execute the current task
  97093. * @param scene defines the scene where you want your assets to be loaded
  97094. * @param onSuccess is a callback called when the task is successfully executed
  97095. * @param onError is a callback called if an error occurs
  97096. */
  97097. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97098. var onload = function () {
  97099. onSuccess();
  97100. };
  97101. var onerror = function (message, exception) {
  97102. onError(message, exception);
  97103. };
  97104. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  97105. };
  97106. return HDRCubeTextureAssetTask;
  97107. }(AbstractAssetTask));
  97108. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  97109. /**
  97110. * This class can be used to easily import assets into a scene
  97111. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  97112. */
  97113. var AssetsManager = /** @class */ (function () {
  97114. /**
  97115. * Creates a new AssetsManager
  97116. * @param scene defines the scene to work on
  97117. */
  97118. function AssetsManager(scene) {
  97119. this._isLoading = false;
  97120. this._tasks = new Array();
  97121. this._waitingTasksCount = 0;
  97122. this._totalTasksCount = 0;
  97123. /**
  97124. * Observable called when all tasks are processed
  97125. */
  97126. this.onTaskSuccessObservable = new BABYLON.Observable();
  97127. /**
  97128. * Observable called when a task had an error
  97129. */
  97130. this.onTaskErrorObservable = new BABYLON.Observable();
  97131. /**
  97132. * Observable called when a task is successful
  97133. */
  97134. this.onTasksDoneObservable = new BABYLON.Observable();
  97135. /**
  97136. * Observable called when a task is done (whatever the result is)
  97137. */
  97138. this.onProgressObservable = new BABYLON.Observable();
  97139. /**
  97140. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  97141. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  97142. */
  97143. this.useDefaultLoadingScreen = true;
  97144. this._scene = scene;
  97145. }
  97146. /**
  97147. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97148. * @param taskName defines the name of the new task
  97149. * @param meshesNames defines the name of meshes to load
  97150. * @param rootUrl defines the root url to use to locate files
  97151. * @param sceneFilename defines the filename of the scene file
  97152. * @returns a new {BABYLON.MeshAssetTask} object
  97153. */
  97154. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97155. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97156. this._tasks.push(task);
  97157. return task;
  97158. };
  97159. /**
  97160. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97161. * @param taskName defines the name of the new task
  97162. * @param url defines the url of the file to load
  97163. * @returns a new {BABYLON.TextFileAssetTask} object
  97164. */
  97165. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97166. var task = new TextFileAssetTask(taskName, url);
  97167. this._tasks.push(task);
  97168. return task;
  97169. };
  97170. /**
  97171. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97172. * @param taskName defines the name of the new task
  97173. * @param url defines the url of the file to load
  97174. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97175. */
  97176. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97177. var task = new BinaryFileAssetTask(taskName, url);
  97178. this._tasks.push(task);
  97179. return task;
  97180. };
  97181. /**
  97182. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97183. * @param taskName defines the name of the new task
  97184. * @param url defines the url of the file to load
  97185. * @returns a new {BABYLON.ImageAssetTask} object
  97186. */
  97187. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97188. var task = new ImageAssetTask(taskName, url);
  97189. this._tasks.push(task);
  97190. return task;
  97191. };
  97192. /**
  97193. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  97194. * @param taskName defines the name of the new task
  97195. * @param url defines the url of the file to load
  97196. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97197. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  97198. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  97199. * @returns a new {BABYLON.TextureAssetTask} object
  97200. */
  97201. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  97202. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97203. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  97204. this._tasks.push(task);
  97205. return task;
  97206. };
  97207. /**
  97208. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  97209. * @param taskName defines the name of the new task
  97210. * @param url defines the url of the file to load
  97211. * @param extensions defines the extension to use to load the cube map (can be null)
  97212. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97213. * @param files defines the list of files to load (can be null)
  97214. * @returns a new {BABYLON.CubeTextureAssetTask} object
  97215. */
  97216. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  97217. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  97218. this._tasks.push(task);
  97219. return task;
  97220. };
  97221. /**
  97222. *
  97223. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  97224. * @param taskName defines the name of the new task
  97225. * @param url defines the url of the file to load
  97226. * @param size defines the size you want for the cubemap (can be null)
  97227. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97228. * @param generateHarmonics defines if you want to automatically generate (true by default)
  97229. * @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)
  97230. * @param reserved Internal use only
  97231. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  97232. */
  97233. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  97234. if (noMipmap === void 0) { noMipmap = false; }
  97235. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97236. if (gammaSpace === void 0) { gammaSpace = false; }
  97237. if (reserved === void 0) { reserved = false; }
  97238. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  97239. this._tasks.push(task);
  97240. return task;
  97241. };
  97242. /**
  97243. * Remove a task from the assets manager.
  97244. * @param task the task to remove
  97245. */
  97246. AssetsManager.prototype.removeTask = function (task) {
  97247. var index = this._tasks.indexOf(task);
  97248. if (index > -1) {
  97249. this._tasks.splice(index, 1);
  97250. }
  97251. };
  97252. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  97253. this._waitingTasksCount--;
  97254. try {
  97255. if (this.onProgress) {
  97256. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  97257. }
  97258. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  97259. }
  97260. catch (e) {
  97261. BABYLON.Tools.Error("Error running progress callbacks.");
  97262. console.log(e);
  97263. }
  97264. if (this._waitingTasksCount === 0) {
  97265. try {
  97266. if (this.onFinish) {
  97267. this.onFinish(this._tasks);
  97268. }
  97269. // Let's remove successfull tasks
  97270. var currentTasks = this._tasks.slice();
  97271. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  97272. var task = currentTasks_1[_i];
  97273. if (task.taskState === AssetTaskState.DONE) {
  97274. var index = this._tasks.indexOf(task);
  97275. if (index > -1) {
  97276. this._tasks.splice(index, 1);
  97277. }
  97278. }
  97279. }
  97280. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97281. }
  97282. catch (e) {
  97283. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  97284. console.log(e);
  97285. }
  97286. this._isLoading = false;
  97287. this._scene.getEngine().hideLoadingUI();
  97288. }
  97289. };
  97290. AssetsManager.prototype._runTask = function (task) {
  97291. var _this = this;
  97292. var done = function () {
  97293. try {
  97294. if (_this.onTaskSuccess) {
  97295. _this.onTaskSuccess(task);
  97296. }
  97297. _this.onTaskSuccessObservable.notifyObservers(task);
  97298. _this._decreaseWaitingTasksCount(task);
  97299. }
  97300. catch (e) {
  97301. error("Error executing task success callbacks", e);
  97302. }
  97303. };
  97304. var error = function (message, exception) {
  97305. task._setErrorObject(message, exception);
  97306. if (_this.onTaskError) {
  97307. _this.onTaskError(task);
  97308. }
  97309. _this.onTaskErrorObservable.notifyObservers(task);
  97310. _this._decreaseWaitingTasksCount(task);
  97311. };
  97312. task.run(this._scene, done, error);
  97313. };
  97314. /**
  97315. * Reset the {BABYLON.AssetsManager} and remove all tasks
  97316. * @return the current instance of the {BABYLON.AssetsManager}
  97317. */
  97318. AssetsManager.prototype.reset = function () {
  97319. this._isLoading = false;
  97320. this._tasks = new Array();
  97321. return this;
  97322. };
  97323. /**
  97324. * Start the loading process
  97325. * @return the current instance of the {BABYLON.AssetsManager}
  97326. */
  97327. AssetsManager.prototype.load = function () {
  97328. if (this._isLoading) {
  97329. return this;
  97330. }
  97331. this._isLoading = true;
  97332. this._waitingTasksCount = this._tasks.length;
  97333. this._totalTasksCount = this._tasks.length;
  97334. if (this._waitingTasksCount === 0) {
  97335. this._isLoading = false;
  97336. if (this.onFinish) {
  97337. this.onFinish(this._tasks);
  97338. }
  97339. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97340. return this;
  97341. }
  97342. if (this.useDefaultLoadingScreen) {
  97343. this._scene.getEngine().displayLoadingUI();
  97344. }
  97345. for (var index = 0; index < this._tasks.length; index++) {
  97346. var task = this._tasks[index];
  97347. if (task.taskState === AssetTaskState.INIT) {
  97348. this._runTask(task);
  97349. }
  97350. }
  97351. return this;
  97352. };
  97353. return AssetsManager;
  97354. }());
  97355. BABYLON.AssetsManager = AssetsManager;
  97356. })(BABYLON || (BABYLON = {}));
  97357. //# sourceMappingURL=babylon.assetsManager.js.map
  97358. var BABYLON;
  97359. (function (BABYLON) {
  97360. var serializedGeometries = [];
  97361. var serializeGeometry = function (geometry, serializationGeometries) {
  97362. if (serializedGeometries[geometry.id]) {
  97363. return;
  97364. }
  97365. if (geometry.doNotSerialize) {
  97366. return;
  97367. }
  97368. if (geometry instanceof BABYLON.BoxGeometry) {
  97369. serializationGeometries.boxes.push(geometry.serialize());
  97370. }
  97371. else if (geometry instanceof BABYLON.SphereGeometry) {
  97372. serializationGeometries.spheres.push(geometry.serialize());
  97373. }
  97374. else if (geometry instanceof BABYLON.CylinderGeometry) {
  97375. serializationGeometries.cylinders.push(geometry.serialize());
  97376. }
  97377. else if (geometry instanceof BABYLON.TorusGeometry) {
  97378. serializationGeometries.toruses.push(geometry.serialize());
  97379. }
  97380. else if (geometry instanceof BABYLON.GroundGeometry) {
  97381. serializationGeometries.grounds.push(geometry.serialize());
  97382. }
  97383. else if (geometry instanceof BABYLON.Plane) {
  97384. serializationGeometries.planes.push(geometry.serialize());
  97385. }
  97386. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  97387. serializationGeometries.torusKnots.push(geometry.serialize());
  97388. }
  97389. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  97390. throw new Error("Unknown primitive type");
  97391. }
  97392. else {
  97393. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  97394. }
  97395. serializedGeometries[geometry.id] = true;
  97396. };
  97397. var serializeMesh = function (mesh, serializationScene) {
  97398. var serializationObject = {};
  97399. // Geometry
  97400. var geometry = mesh._geometry;
  97401. if (geometry) {
  97402. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  97403. // 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
  97404. serializeGeometry(geometry, serializationScene.geometries);
  97405. }
  97406. }
  97407. // Custom
  97408. if (mesh.serialize) {
  97409. mesh.serialize(serializationObject);
  97410. }
  97411. return serializationObject;
  97412. };
  97413. var finalizeSingleMesh = function (mesh, serializationObject) {
  97414. //only works if the mesh is already loaded
  97415. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97416. //serialize material
  97417. if (mesh.material) {
  97418. if (mesh.material instanceof BABYLON.MultiMaterial) {
  97419. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  97420. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97421. serializationObject.multiMaterials.push(mesh.material.serialize());
  97422. }
  97423. }
  97424. else {
  97425. serializationObject.materials = serializationObject.materials || [];
  97426. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97427. serializationObject.materials.push(mesh.material.serialize());
  97428. }
  97429. }
  97430. }
  97431. //serialize geometry
  97432. var geometry = mesh._geometry;
  97433. if (geometry) {
  97434. if (!serializationObject.geometries) {
  97435. serializationObject.geometries = {};
  97436. serializationObject.geometries.boxes = [];
  97437. serializationObject.geometries.spheres = [];
  97438. serializationObject.geometries.cylinders = [];
  97439. serializationObject.geometries.toruses = [];
  97440. serializationObject.geometries.grounds = [];
  97441. serializationObject.geometries.planes = [];
  97442. serializationObject.geometries.torusKnots = [];
  97443. serializationObject.geometries.vertexData = [];
  97444. }
  97445. serializeGeometry(geometry, serializationObject.geometries);
  97446. }
  97447. // Skeletons
  97448. if (mesh.skeleton) {
  97449. serializationObject.skeletons = serializationObject.skeletons || [];
  97450. serializationObject.skeletons.push(mesh.skeleton.serialize());
  97451. }
  97452. //serialize the actual mesh
  97453. serializationObject.meshes = serializationObject.meshes || [];
  97454. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97455. }
  97456. };
  97457. var SceneSerializer = /** @class */ (function () {
  97458. function SceneSerializer() {
  97459. }
  97460. SceneSerializer.ClearCache = function () {
  97461. serializedGeometries = [];
  97462. };
  97463. SceneSerializer.Serialize = function (scene) {
  97464. var serializationObject = {};
  97465. SceneSerializer.ClearCache();
  97466. // Scene
  97467. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  97468. serializationObject.autoClear = scene.autoClear;
  97469. serializationObject.clearColor = scene.clearColor.asArray();
  97470. serializationObject.ambientColor = scene.ambientColor.asArray();
  97471. serializationObject.gravity = scene.gravity.asArray();
  97472. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  97473. serializationObject.workerCollisions = scene.workerCollisions;
  97474. // Fog
  97475. if (scene.fogMode && scene.fogMode !== 0) {
  97476. serializationObject.fogMode = scene.fogMode;
  97477. serializationObject.fogColor = scene.fogColor.asArray();
  97478. serializationObject.fogStart = scene.fogStart;
  97479. serializationObject.fogEnd = scene.fogEnd;
  97480. serializationObject.fogDensity = scene.fogDensity;
  97481. }
  97482. //Physics
  97483. if (scene.isPhysicsEnabled()) {
  97484. var physicEngine = scene.getPhysicsEngine();
  97485. if (physicEngine) {
  97486. serializationObject.physicsEnabled = true;
  97487. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  97488. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  97489. }
  97490. }
  97491. // Metadata
  97492. if (scene.metadata) {
  97493. serializationObject.metadata = scene.metadata;
  97494. }
  97495. // Morph targets
  97496. serializationObject.morphTargetManagers = [];
  97497. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  97498. var abstractMesh = _a[_i];
  97499. var manager = abstractMesh.morphTargetManager;
  97500. if (manager) {
  97501. serializationObject.morphTargetManagers.push(manager.serialize());
  97502. }
  97503. }
  97504. // Lights
  97505. serializationObject.lights = [];
  97506. var index;
  97507. var light;
  97508. for (index = 0; index < scene.lights.length; index++) {
  97509. light = scene.lights[index];
  97510. if (!light.doNotSerialize) {
  97511. serializationObject.lights.push(light.serialize());
  97512. }
  97513. }
  97514. // Cameras
  97515. serializationObject.cameras = [];
  97516. for (index = 0; index < scene.cameras.length; index++) {
  97517. var camera = scene.cameras[index];
  97518. if (!camera.doNotSerialize) {
  97519. serializationObject.cameras.push(camera.serialize());
  97520. }
  97521. }
  97522. if (scene.activeCamera) {
  97523. serializationObject.activeCameraID = scene.activeCamera.id;
  97524. }
  97525. // Animations
  97526. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  97527. // Materials
  97528. serializationObject.materials = [];
  97529. serializationObject.multiMaterials = [];
  97530. var material;
  97531. for (index = 0; index < scene.materials.length; index++) {
  97532. material = scene.materials[index];
  97533. if (!material.doNotSerialize) {
  97534. serializationObject.materials.push(material.serialize());
  97535. }
  97536. }
  97537. // MultiMaterials
  97538. serializationObject.multiMaterials = [];
  97539. for (index = 0; index < scene.multiMaterials.length; index++) {
  97540. var multiMaterial = scene.multiMaterials[index];
  97541. serializationObject.multiMaterials.push(multiMaterial.serialize());
  97542. }
  97543. // Environment texture
  97544. if (scene.environmentTexture) {
  97545. serializationObject.environmentTexture = scene.environmentTexture.name;
  97546. }
  97547. // Skeletons
  97548. serializationObject.skeletons = [];
  97549. for (index = 0; index < scene.skeletons.length; index++) {
  97550. var skeleton = scene.skeletons[index];
  97551. if (!skeleton.doNotSerialize) {
  97552. serializationObject.skeletons.push(skeleton.serialize());
  97553. }
  97554. }
  97555. // Transform nodes
  97556. serializationObject.transformNodes = [];
  97557. for (index = 0; index < scene.transformNodes.length; index++) {
  97558. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  97559. }
  97560. // Geometries
  97561. serializationObject.geometries = {};
  97562. serializationObject.geometries.boxes = [];
  97563. serializationObject.geometries.spheres = [];
  97564. serializationObject.geometries.cylinders = [];
  97565. serializationObject.geometries.toruses = [];
  97566. serializationObject.geometries.grounds = [];
  97567. serializationObject.geometries.planes = [];
  97568. serializationObject.geometries.torusKnots = [];
  97569. serializationObject.geometries.vertexData = [];
  97570. serializedGeometries = [];
  97571. var geometries = scene.getGeometries();
  97572. for (index = 0; index < geometries.length; index++) {
  97573. var geometry = geometries[index];
  97574. if (geometry.isReady()) {
  97575. serializeGeometry(geometry, serializationObject.geometries);
  97576. }
  97577. }
  97578. // Meshes
  97579. serializationObject.meshes = [];
  97580. for (index = 0; index < scene.meshes.length; index++) {
  97581. var abstractMesh = scene.meshes[index];
  97582. if (abstractMesh instanceof BABYLON.Mesh) {
  97583. var mesh = abstractMesh;
  97584. if (!mesh.doNotSerialize) {
  97585. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97586. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97587. }
  97588. }
  97589. }
  97590. }
  97591. // Particles Systems
  97592. serializationObject.particleSystems = [];
  97593. for (index = 0; index < scene.particleSystems.length; index++) {
  97594. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  97595. }
  97596. // Lens flares
  97597. serializationObject.lensFlareSystems = [];
  97598. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  97599. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  97600. }
  97601. // Shadows
  97602. serializationObject.shadowGenerators = [];
  97603. for (index = 0; index < scene.lights.length; index++) {
  97604. light = scene.lights[index];
  97605. var shadowGenerator = light.getShadowGenerator();
  97606. if (shadowGenerator) {
  97607. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  97608. }
  97609. }
  97610. // Action Manager
  97611. if (scene.actionManager) {
  97612. serializationObject.actions = scene.actionManager.serialize("scene");
  97613. }
  97614. // Audio
  97615. serializationObject.sounds = [];
  97616. for (index = 0; index < scene.soundTracks.length; index++) {
  97617. var soundtrack = scene.soundTracks[index];
  97618. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  97619. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  97620. }
  97621. }
  97622. // Effect layers
  97623. serializationObject.effectLayers = [];
  97624. for (index = 0; index < scene.effectLayers.length; index++) {
  97625. var layer = scene.effectLayers[index];
  97626. if (layer.serialize) {
  97627. serializationObject.effectLayers.push(layer.serialize());
  97628. }
  97629. }
  97630. return serializationObject;
  97631. };
  97632. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  97633. if (withParents === void 0) { withParents = false; }
  97634. if (withChildren === void 0) { withChildren = false; }
  97635. var serializationObject = {};
  97636. SceneSerializer.ClearCache();
  97637. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  97638. if (withParents || withChildren) {
  97639. //deliberate for loop! not for each, appended should be processed as well.
  97640. for (var i = 0; i < toSerialize.length; ++i) {
  97641. if (withChildren) {
  97642. toSerialize[i].getDescendants().forEach(function (node) {
  97643. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  97644. toSerialize.push(node);
  97645. }
  97646. });
  97647. }
  97648. //make sure the array doesn't contain the object already
  97649. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  97650. toSerialize.push(toSerialize[i].parent);
  97651. }
  97652. }
  97653. }
  97654. toSerialize.forEach(function (mesh) {
  97655. finalizeSingleMesh(mesh, serializationObject);
  97656. });
  97657. return serializationObject;
  97658. };
  97659. return SceneSerializer;
  97660. }());
  97661. BABYLON.SceneSerializer = SceneSerializer;
  97662. })(BABYLON || (BABYLON = {}));
  97663. //# sourceMappingURL=babylon.sceneSerializer.js.map
  97664. var BABYLON;
  97665. (function (BABYLON) {
  97666. var ReflectionProbe = /** @class */ (function () {
  97667. function ReflectionProbe(name, size, scene, generateMipMaps) {
  97668. if (generateMipMaps === void 0) { generateMipMaps = true; }
  97669. var _this = this;
  97670. this.name = name;
  97671. this._viewMatrix = BABYLON.Matrix.Identity();
  97672. this._target = BABYLON.Vector3.Zero();
  97673. this._add = BABYLON.Vector3.Zero();
  97674. this._invertYAxis = false;
  97675. this.position = BABYLON.Vector3.Zero();
  97676. this._scene = scene;
  97677. this._scene.reflectionProbes.push(this);
  97678. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  97679. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  97680. switch (faceIndex) {
  97681. case 0:
  97682. _this._add.copyFromFloats(1, 0, 0);
  97683. break;
  97684. case 1:
  97685. _this._add.copyFromFloats(-1, 0, 0);
  97686. break;
  97687. case 2:
  97688. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  97689. break;
  97690. case 3:
  97691. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  97692. break;
  97693. case 4:
  97694. _this._add.copyFromFloats(0, 0, 1);
  97695. break;
  97696. case 5:
  97697. _this._add.copyFromFloats(0, 0, -1);
  97698. break;
  97699. }
  97700. if (_this._attachedMesh) {
  97701. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  97702. }
  97703. _this.position.addToRef(_this._add, _this._target);
  97704. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  97705. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  97706. scene._forcedViewPosition = _this.position;
  97707. });
  97708. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  97709. scene._forcedViewPosition = null;
  97710. scene.updateTransformMatrix(true);
  97711. });
  97712. if (scene.activeCamera) {
  97713. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  97714. }
  97715. }
  97716. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  97717. get: function () {
  97718. return this._renderTargetTexture.samples;
  97719. },
  97720. set: function (value) {
  97721. this._renderTargetTexture.samples = value;
  97722. },
  97723. enumerable: true,
  97724. configurable: true
  97725. });
  97726. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  97727. get: function () {
  97728. return this._renderTargetTexture.refreshRate;
  97729. },
  97730. set: function (value) {
  97731. this._renderTargetTexture.refreshRate = value;
  97732. },
  97733. enumerable: true,
  97734. configurable: true
  97735. });
  97736. ReflectionProbe.prototype.getScene = function () {
  97737. return this._scene;
  97738. };
  97739. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  97740. get: function () {
  97741. return this._renderTargetTexture;
  97742. },
  97743. enumerable: true,
  97744. configurable: true
  97745. });
  97746. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  97747. get: function () {
  97748. return this._renderTargetTexture.renderList;
  97749. },
  97750. enumerable: true,
  97751. configurable: true
  97752. });
  97753. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  97754. this._attachedMesh = mesh;
  97755. };
  97756. /**
  97757. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  97758. *
  97759. * @param renderingGroupId The rendering group id corresponding to its index
  97760. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  97761. */
  97762. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  97763. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  97764. };
  97765. ReflectionProbe.prototype.dispose = function () {
  97766. var index = this._scene.reflectionProbes.indexOf(this);
  97767. if (index !== -1) {
  97768. // Remove from the scene if found
  97769. this._scene.reflectionProbes.splice(index, 1);
  97770. }
  97771. if (this._renderTargetTexture) {
  97772. this._renderTargetTexture.dispose();
  97773. this._renderTargetTexture = null;
  97774. }
  97775. };
  97776. return ReflectionProbe;
  97777. }());
  97778. BABYLON.ReflectionProbe = ReflectionProbe;
  97779. })(BABYLON || (BABYLON = {}));
  97780. //# sourceMappingURL=babylon.reflectionProbe.js.map
  97781. var BABYLON;
  97782. (function (BABYLON) {
  97783. var Layer = /** @class */ (function () {
  97784. function Layer(name, imgUrl, scene, isBackground, color) {
  97785. this.name = name;
  97786. this.scale = new BABYLON.Vector2(1, 1);
  97787. this.offset = new BABYLON.Vector2(0, 0);
  97788. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  97789. this.layerMask = 0x0FFFFFFF;
  97790. this._vertexBuffers = {};
  97791. // Events
  97792. /**
  97793. * An event triggered when the layer is disposed.
  97794. */
  97795. this.onDisposeObservable = new BABYLON.Observable();
  97796. /**
  97797. * An event triggered before rendering the scene
  97798. */
  97799. this.onBeforeRenderObservable = new BABYLON.Observable();
  97800. /**
  97801. * An event triggered after rendering the scene
  97802. */
  97803. this.onAfterRenderObservable = new BABYLON.Observable();
  97804. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  97805. this.isBackground = isBackground === undefined ? true : isBackground;
  97806. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  97807. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  97808. this._scene.layers.push(this);
  97809. var engine = this._scene.getEngine();
  97810. // VBO
  97811. var vertices = [];
  97812. vertices.push(1, 1);
  97813. vertices.push(-1, 1);
  97814. vertices.push(-1, -1);
  97815. vertices.push(1, -1);
  97816. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97817. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97818. this._createIndexBuffer();
  97819. // Effects
  97820. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  97821. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  97822. }
  97823. Object.defineProperty(Layer.prototype, "onDispose", {
  97824. set: function (callback) {
  97825. if (this._onDisposeObserver) {
  97826. this.onDisposeObservable.remove(this._onDisposeObserver);
  97827. }
  97828. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  97829. },
  97830. enumerable: true,
  97831. configurable: true
  97832. });
  97833. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  97834. set: function (callback) {
  97835. if (this._onBeforeRenderObserver) {
  97836. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  97837. }
  97838. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  97839. },
  97840. enumerable: true,
  97841. configurable: true
  97842. });
  97843. Object.defineProperty(Layer.prototype, "onAfterRender", {
  97844. set: function (callback) {
  97845. if (this._onAfterRenderObserver) {
  97846. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  97847. }
  97848. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  97849. },
  97850. enumerable: true,
  97851. configurable: true
  97852. });
  97853. Layer.prototype._createIndexBuffer = function () {
  97854. var engine = this._scene.getEngine();
  97855. // Indices
  97856. var indices = [];
  97857. indices.push(0);
  97858. indices.push(1);
  97859. indices.push(2);
  97860. indices.push(0);
  97861. indices.push(2);
  97862. indices.push(3);
  97863. this._indexBuffer = engine.createIndexBuffer(indices);
  97864. };
  97865. Layer.prototype._rebuild = function () {
  97866. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97867. if (vb) {
  97868. vb._rebuild();
  97869. }
  97870. this._createIndexBuffer();
  97871. };
  97872. Layer.prototype.render = function () {
  97873. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  97874. // Check
  97875. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  97876. return;
  97877. var engine = this._scene.getEngine();
  97878. this.onBeforeRenderObservable.notifyObservers(this);
  97879. // Render
  97880. engine.enableEffect(currentEffect);
  97881. engine.setState(false);
  97882. // Texture
  97883. currentEffect.setTexture("textureSampler", this.texture);
  97884. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  97885. // Color
  97886. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  97887. // Scale / offset
  97888. currentEffect.setVector2("offset", this.offset);
  97889. currentEffect.setVector2("scale", this.scale);
  97890. // VBOs
  97891. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97892. // Draw order
  97893. if (!this.alphaTest) {
  97894. engine.setAlphaMode(this.alphaBlendingMode);
  97895. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97896. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  97897. }
  97898. else {
  97899. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97900. }
  97901. this.onAfterRenderObservable.notifyObservers(this);
  97902. };
  97903. Layer.prototype.dispose = function () {
  97904. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97905. if (vertexBuffer) {
  97906. vertexBuffer.dispose();
  97907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97908. }
  97909. if (this._indexBuffer) {
  97910. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97911. this._indexBuffer = null;
  97912. }
  97913. if (this.texture) {
  97914. this.texture.dispose();
  97915. this.texture = null;
  97916. }
  97917. // Remove from scene
  97918. var index = this._scene.layers.indexOf(this);
  97919. this._scene.layers.splice(index, 1);
  97920. // Callback
  97921. this.onDisposeObservable.notifyObservers(this);
  97922. this.onDisposeObservable.clear();
  97923. this.onAfterRenderObservable.clear();
  97924. this.onBeforeRenderObservable.clear();
  97925. };
  97926. return Layer;
  97927. }());
  97928. BABYLON.Layer = Layer;
  97929. })(BABYLON || (BABYLON = {}));
  97930. //# sourceMappingURL=babylon.layer.js.map
  97931. var BABYLON;
  97932. (function (BABYLON) {
  97933. var TextureTools = /** @class */ (function () {
  97934. function TextureTools() {
  97935. }
  97936. /**
  97937. * Uses the GPU to create a copy texture rescaled at a given size
  97938. * @param texture Texture to copy from
  97939. * @param width Desired width
  97940. * @param height Desired height
  97941. * @return Generated texture
  97942. */
  97943. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  97944. if (useBilinearMode === void 0) { useBilinearMode = true; }
  97945. var scene = texture.getScene();
  97946. var engine = scene.getEngine();
  97947. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  97948. rtt.wrapU = texture.wrapU;
  97949. rtt.wrapV = texture.wrapV;
  97950. rtt.uOffset = texture.uOffset;
  97951. rtt.vOffset = texture.vOffset;
  97952. rtt.uScale = texture.uScale;
  97953. rtt.vScale = texture.vScale;
  97954. rtt.uAng = texture.uAng;
  97955. rtt.vAng = texture.vAng;
  97956. rtt.wAng = texture.wAng;
  97957. rtt.coordinatesIndex = texture.coordinatesIndex;
  97958. rtt.level = texture.level;
  97959. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  97960. rtt._texture.isReady = false;
  97961. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97962. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97963. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97964. passPostProcess.getEffect().executeWhenCompiled(function () {
  97965. passPostProcess.onApply = function (effect) {
  97966. effect.setTexture("textureSampler", texture);
  97967. };
  97968. var internalTexture = rtt.getInternalTexture();
  97969. if (internalTexture) {
  97970. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  97971. engine.unBindFramebuffer(internalTexture);
  97972. rtt.disposeFramebufferObjects();
  97973. passPostProcess.dispose();
  97974. internalTexture.isReady = true;
  97975. }
  97976. });
  97977. return rtt;
  97978. };
  97979. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  97980. if (!scene._environmentBRDFTexture) {
  97981. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97982. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97983. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97984. scene._environmentBRDFTexture = texture;
  97985. }
  97986. return scene._environmentBRDFTexture;
  97987. };
  97988. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8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4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  97989. return TextureTools;
  97990. }());
  97991. BABYLON.TextureTools = TextureTools;
  97992. })(BABYLON || (BABYLON = {}));
  97993. //# sourceMappingURL=babylon.textureTools.js.map
  97994. var BABYLON;
  97995. (function (BABYLON) {
  97996. var FramingBehavior = /** @class */ (function () {
  97997. function FramingBehavior() {
  97998. this._mode = FramingBehavior.FitFrustumSidesMode;
  97999. this._radiusScale = 1.0;
  98000. this._positionScale = 0.5;
  98001. this._defaultElevation = 0.3;
  98002. this._elevationReturnTime = 1500;
  98003. this._elevationReturnWaitTime = 1000;
  98004. this._zoomStopsAnimation = false;
  98005. this._framingTime = 1500;
  98006. this._isPointerDown = false;
  98007. this._lastInteractionTime = -Infinity;
  98008. // Framing control
  98009. this._animatables = new Array();
  98010. this._betaIsAnimating = false;
  98011. }
  98012. Object.defineProperty(FramingBehavior.prototype, "name", {
  98013. get: function () {
  98014. return "Framing";
  98015. },
  98016. enumerable: true,
  98017. configurable: true
  98018. });
  98019. Object.defineProperty(FramingBehavior.prototype, "mode", {
  98020. /**
  98021. * Gets current mode used by the behavior.
  98022. */
  98023. get: function () {
  98024. return this._mode;
  98025. },
  98026. /**
  98027. * Sets the current mode used by the behavior
  98028. */
  98029. set: function (mode) {
  98030. this._mode = mode;
  98031. },
  98032. enumerable: true,
  98033. configurable: true
  98034. });
  98035. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  98036. /**
  98037. * Gets the scale applied to the radius
  98038. */
  98039. get: function () {
  98040. return this._radiusScale;
  98041. },
  98042. /**
  98043. * Sets the scale applied to the radius (1 by default)
  98044. */
  98045. set: function (radius) {
  98046. this._radiusScale = radius;
  98047. },
  98048. enumerable: true,
  98049. configurable: true
  98050. });
  98051. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  98052. /**
  98053. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98054. */
  98055. get: function () {
  98056. return this._positionScale;
  98057. },
  98058. /**
  98059. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98060. */
  98061. set: function (scale) {
  98062. this._positionScale = scale;
  98063. },
  98064. enumerable: true,
  98065. configurable: true
  98066. });
  98067. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  98068. /**
  98069. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98070. * behaviour is triggered, in radians.
  98071. */
  98072. get: function () {
  98073. return this._defaultElevation;
  98074. },
  98075. /**
  98076. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98077. * behaviour is triggered, in radians.
  98078. */
  98079. set: function (elevation) {
  98080. this._defaultElevation = elevation;
  98081. },
  98082. enumerable: true,
  98083. configurable: true
  98084. });
  98085. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  98086. /**
  98087. * Gets the time (in milliseconds) taken to return to the default beta position.
  98088. * Negative value indicates camera should not return to default.
  98089. */
  98090. get: function () {
  98091. return this._elevationReturnTime;
  98092. },
  98093. /**
  98094. * Sets the time (in milliseconds) taken to return to the default beta position.
  98095. * Negative value indicates camera should not return to default.
  98096. */
  98097. set: function (speed) {
  98098. this._elevationReturnTime = speed;
  98099. },
  98100. enumerable: true,
  98101. configurable: true
  98102. });
  98103. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  98104. /**
  98105. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98106. */
  98107. get: function () {
  98108. return this._elevationReturnWaitTime;
  98109. },
  98110. /**
  98111. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98112. */
  98113. set: function (time) {
  98114. this._elevationReturnWaitTime = time;
  98115. },
  98116. enumerable: true,
  98117. configurable: true
  98118. });
  98119. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  98120. /**
  98121. * Gets the flag that indicates if user zooming should stop animation.
  98122. */
  98123. get: function () {
  98124. return this._zoomStopsAnimation;
  98125. },
  98126. /**
  98127. * Sets the flag that indicates if user zooming should stop animation.
  98128. */
  98129. set: function (flag) {
  98130. this._zoomStopsAnimation = flag;
  98131. },
  98132. enumerable: true,
  98133. configurable: true
  98134. });
  98135. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  98136. /**
  98137. * Gets the transition time when framing the mesh, in milliseconds
  98138. */
  98139. get: function () {
  98140. return this._framingTime;
  98141. },
  98142. /**
  98143. * Sets the transition time when framing the mesh, in milliseconds
  98144. */
  98145. set: function (time) {
  98146. this._framingTime = time;
  98147. },
  98148. enumerable: true,
  98149. configurable: true
  98150. });
  98151. FramingBehavior.prototype.init = function () {
  98152. // Do notihng
  98153. };
  98154. FramingBehavior.prototype.attach = function (camera) {
  98155. var _this = this;
  98156. this._attachedCamera = camera;
  98157. var scene = this._attachedCamera.getScene();
  98158. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  98159. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98160. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98161. _this._isPointerDown = true;
  98162. return;
  98163. }
  98164. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98165. _this._isPointerDown = false;
  98166. }
  98167. });
  98168. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98169. if (mesh) {
  98170. _this.zoomOnMesh(mesh);
  98171. }
  98172. });
  98173. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98174. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98175. _this._applyUserInteraction();
  98176. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  98177. // back to the default position after a given timeout
  98178. _this._maintainCameraAboveGround();
  98179. });
  98180. };
  98181. FramingBehavior.prototype.detach = function () {
  98182. if (!this._attachedCamera) {
  98183. return;
  98184. }
  98185. var scene = this._attachedCamera.getScene();
  98186. if (this._onPrePointerObservableObserver) {
  98187. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98188. }
  98189. if (this._onAfterCheckInputsObserver) {
  98190. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98191. }
  98192. if (this._onMeshTargetChangedObserver) {
  98193. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98194. }
  98195. this._attachedCamera = null;
  98196. };
  98197. /**
  98198. * Targets the given mesh and updates zoom level accordingly.
  98199. * @param mesh The mesh to target.
  98200. * @param radius Optional. If a cached radius position already exists, overrides default.
  98201. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98202. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98203. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98204. */
  98205. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98206. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98207. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98208. mesh.computeWorldMatrix(true);
  98209. var boundingBox = mesh.getBoundingInfo().boundingBox;
  98210. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  98211. };
  98212. /**
  98213. * Targets the given mesh with its children and updates zoom level accordingly.
  98214. * @param mesh The mesh to target.
  98215. * @param radius Optional. If a cached radius position already exists, overrides default.
  98216. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98217. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98218. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98219. */
  98220. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98221. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98222. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98223. mesh.computeWorldMatrix(true);
  98224. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  98225. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  98226. };
  98227. /**
  98228. * Targets the given meshes with their children and updates zoom level accordingly.
  98229. * @param meshes The mesh to target.
  98230. * @param radius Optional. If a cached radius position already exists, overrides default.
  98231. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98232. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98233. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98234. */
  98235. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  98236. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98237. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98238. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  98239. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  98240. for (var i = 0; i < meshes.length; i++) {
  98241. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  98242. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  98243. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  98244. }
  98245. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  98246. };
  98247. /**
  98248. * Targets the given mesh and updates zoom level accordingly.
  98249. * @param mesh The mesh to target.
  98250. * @param radius Optional. If a cached radius position already exists, overrides default.
  98251. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98252. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98253. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98254. */
  98255. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  98256. var _this = this;
  98257. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98258. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98259. var zoomTarget;
  98260. if (!this._attachedCamera) {
  98261. return;
  98262. }
  98263. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  98264. var bottom = minimumWorld.y;
  98265. var top = maximumWorld.y;
  98266. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  98267. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  98268. if (focusOnOriginXZ) {
  98269. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  98270. }
  98271. else {
  98272. var centerWorld = minimumWorld.add(radiusWorld);
  98273. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  98274. }
  98275. if (!this._vectorTransition) {
  98276. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  98277. }
  98278. this._betaIsAnimating = true;
  98279. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  98280. if (animatable) {
  98281. this._animatables.push(animatable);
  98282. }
  98283. // sets the radius and lower radius bounds
  98284. // Small delta ensures camera is not always at lower zoom limit.
  98285. var radius = 0;
  98286. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  98287. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98288. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  98289. radius = position;
  98290. }
  98291. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98292. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98293. if (this._attachedCamera.lowerRadiusLimit === null) {
  98294. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  98295. }
  98296. }
  98297. // Set sensibilities
  98298. var extend = maximumWorld.subtract(minimumWorld).length();
  98299. this._attachedCamera.panningSensibility = 5000 / extend;
  98300. this._attachedCamera.wheelPrecision = 100 / radius;
  98301. // transition to new radius
  98302. if (!this._radiusTransition) {
  98303. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98304. }
  98305. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  98306. _this.stopAllAnimations();
  98307. if (onAnimationEnd) {
  98308. onAnimationEnd();
  98309. }
  98310. if (_this._attachedCamera) {
  98311. _this._attachedCamera.storeState();
  98312. }
  98313. });
  98314. if (animatable) {
  98315. this._animatables.push(animatable);
  98316. }
  98317. };
  98318. /**
  98319. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  98320. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  98321. * frustum width.
  98322. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  98323. * to fully enclose the mesh in the viewing frustum.
  98324. */
  98325. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  98326. var size = maximumWorld.subtract(minimumWorld);
  98327. var boxVectorGlobalDiagonal = size.length();
  98328. var frustumSlope = this._getFrustumSlope();
  98329. // Formula for setting distance
  98330. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  98331. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  98332. // Horizon distance
  98333. var radius = radiusWithoutFraming * this._radiusScale;
  98334. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  98335. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  98336. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  98337. var camera = this._attachedCamera;
  98338. if (!camera) {
  98339. return 0;
  98340. }
  98341. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98342. // Don't exceed the requested limit
  98343. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  98344. }
  98345. // Don't exceed the upper radius limit
  98346. if (camera.upperRadiusLimit) {
  98347. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  98348. }
  98349. return distance;
  98350. };
  98351. /**
  98352. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  98353. * is automatically returned to its default position (expected to be above ground plane).
  98354. */
  98355. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  98356. var _this = this;
  98357. if (this._elevationReturnTime < 0) {
  98358. return;
  98359. }
  98360. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  98361. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  98362. var limitBeta = Math.PI * 0.5;
  98363. // Bring the camera back up if below the ground plane
  98364. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  98365. this._betaIsAnimating = true;
  98366. //Transition to new position
  98367. this.stopAllAnimations();
  98368. if (!this._betaTransition) {
  98369. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98370. }
  98371. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  98372. _this._clearAnimationLocks();
  98373. _this.stopAllAnimations();
  98374. });
  98375. if (animatabe) {
  98376. this._animatables.push(animatabe);
  98377. }
  98378. }
  98379. };
  98380. /**
  98381. * Returns the frustum slope based on the canvas ratio and camera FOV
  98382. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  98383. */
  98384. FramingBehavior.prototype._getFrustumSlope = function () {
  98385. // Calculate the viewport ratio
  98386. // Aspect Ratio is Height/Width.
  98387. var camera = this._attachedCamera;
  98388. if (!camera) {
  98389. return BABYLON.Vector2.Zero();
  98390. }
  98391. var engine = camera.getScene().getEngine();
  98392. var aspectRatio = engine.getAspectRatio(camera);
  98393. // Camera FOV is the vertical field of view (top-bottom) in radians.
  98394. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  98395. var frustumSlopeY = Math.tan(camera.fov / 2);
  98396. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  98397. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  98398. // along the forward vector.
  98399. var frustumSlopeX = frustumSlopeY * aspectRatio;
  98400. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  98401. };
  98402. /**
  98403. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  98404. */
  98405. FramingBehavior.prototype._clearAnimationLocks = function () {
  98406. this._betaIsAnimating = false;
  98407. };
  98408. /**
  98409. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98410. */
  98411. FramingBehavior.prototype._applyUserInteraction = function () {
  98412. if (this.isUserIsMoving) {
  98413. this._lastInteractionTime = BABYLON.Tools.Now;
  98414. this.stopAllAnimations();
  98415. this._clearAnimationLocks();
  98416. }
  98417. };
  98418. /**
  98419. * Stops and removes all animations that have been applied to the camera
  98420. */
  98421. FramingBehavior.prototype.stopAllAnimations = function () {
  98422. if (this._attachedCamera) {
  98423. this._attachedCamera.animations = [];
  98424. }
  98425. while (this._animatables.length) {
  98426. if (this._animatables[0]) {
  98427. this._animatables[0].onAnimationEnd = null;
  98428. this._animatables[0].stop();
  98429. }
  98430. this._animatables.shift();
  98431. }
  98432. };
  98433. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  98434. /**
  98435. * Gets a value indicating if the user is moving the camera
  98436. */
  98437. get: function () {
  98438. if (!this._attachedCamera) {
  98439. return false;
  98440. }
  98441. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98442. this._attachedCamera.inertialBetaOffset !== 0 ||
  98443. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98444. this._attachedCamera.inertialPanningX !== 0 ||
  98445. this._attachedCamera.inertialPanningY !== 0 ||
  98446. this._isPointerDown;
  98447. },
  98448. enumerable: true,
  98449. configurable: true
  98450. });
  98451. /**
  98452. * The easing function used by animations
  98453. */
  98454. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  98455. /**
  98456. * The easing mode used by animations
  98457. */
  98458. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  98459. // Statics
  98460. /**
  98461. * The camera can move all the way towards the mesh.
  98462. */
  98463. FramingBehavior.IgnoreBoundsSizeMode = 0;
  98464. /**
  98465. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  98466. */
  98467. FramingBehavior.FitFrustumSidesMode = 1;
  98468. return FramingBehavior;
  98469. }());
  98470. BABYLON.FramingBehavior = FramingBehavior;
  98471. })(BABYLON || (BABYLON = {}));
  98472. //# sourceMappingURL=babylon.framingBehavior.js.map
  98473. var BABYLON;
  98474. (function (BABYLON) {
  98475. /**
  98476. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  98477. */
  98478. var BouncingBehavior = /** @class */ (function () {
  98479. function BouncingBehavior() {
  98480. /**
  98481. * The duration of the animation, in milliseconds
  98482. */
  98483. this.transitionDuration = 450;
  98484. /**
  98485. * Length of the distance animated by the transition when lower radius is reached
  98486. */
  98487. this.lowerRadiusTransitionRange = 2;
  98488. /**
  98489. * Length of the distance animated by the transition when upper radius is reached
  98490. */
  98491. this.upperRadiusTransitionRange = -2;
  98492. this._autoTransitionRange = false;
  98493. // Animations
  98494. this._radiusIsAnimating = false;
  98495. this._radiusBounceTransition = null;
  98496. this._animatables = new Array();
  98497. }
  98498. Object.defineProperty(BouncingBehavior.prototype, "name", {
  98499. get: function () {
  98500. return "Bouncing";
  98501. },
  98502. enumerable: true,
  98503. configurable: true
  98504. });
  98505. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  98506. /**
  98507. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98508. */
  98509. get: function () {
  98510. return this._autoTransitionRange;
  98511. },
  98512. /**
  98513. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98514. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  98515. */
  98516. set: function (value) {
  98517. var _this = this;
  98518. if (this._autoTransitionRange === value) {
  98519. return;
  98520. }
  98521. this._autoTransitionRange = value;
  98522. var camera = this._attachedCamera;
  98523. if (!camera) {
  98524. return;
  98525. }
  98526. if (value) {
  98527. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98528. if (!mesh) {
  98529. return;
  98530. }
  98531. mesh.computeWorldMatrix(true);
  98532. var diagonal = mesh.getBoundingInfo().diagonalLength;
  98533. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  98534. _this.upperRadiusTransitionRange = diagonal * 0.05;
  98535. });
  98536. }
  98537. else if (this._onMeshTargetChangedObserver) {
  98538. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98539. }
  98540. },
  98541. enumerable: true,
  98542. configurable: true
  98543. });
  98544. BouncingBehavior.prototype.init = function () {
  98545. // Do notihng
  98546. };
  98547. BouncingBehavior.prototype.attach = function (camera) {
  98548. var _this = this;
  98549. this._attachedCamera = camera;
  98550. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98551. if (!_this._attachedCamera) {
  98552. return;
  98553. }
  98554. // Add the bounce animation to the lower radius limit
  98555. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  98556. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  98557. }
  98558. // Add the bounce animation to the upper radius limit
  98559. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  98560. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  98561. }
  98562. });
  98563. };
  98564. BouncingBehavior.prototype.detach = function () {
  98565. if (!this._attachedCamera) {
  98566. return;
  98567. }
  98568. if (this._onAfterCheckInputsObserver) {
  98569. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98570. }
  98571. if (this._onMeshTargetChangedObserver) {
  98572. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98573. }
  98574. this._attachedCamera = null;
  98575. };
  98576. /**
  98577. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  98578. * @param radiusLimit The limit to check against.
  98579. * @return Bool to indicate if at limit.
  98580. */
  98581. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  98582. if (!this._attachedCamera) {
  98583. return false;
  98584. }
  98585. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  98586. return true;
  98587. }
  98588. return false;
  98589. };
  98590. /**
  98591. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  98592. * @param radiusDelta The delta by which to animate to. Can be negative.
  98593. */
  98594. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  98595. var _this = this;
  98596. if (!this._attachedCamera) {
  98597. return;
  98598. }
  98599. if (!this._radiusBounceTransition) {
  98600. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  98601. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  98602. }
  98603. // Prevent zoom until bounce has completed
  98604. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  98605. this._attachedCamera.wheelPrecision = Infinity;
  98606. this._attachedCamera.inertialRadiusOffset = 0;
  98607. // Animate to the radius limit
  98608. this.stopAllAnimations();
  98609. this._radiusIsAnimating = true;
  98610. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  98611. if (animatable) {
  98612. this._animatables.push(animatable);
  98613. }
  98614. };
  98615. /**
  98616. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  98617. */
  98618. BouncingBehavior.prototype._clearAnimationLocks = function () {
  98619. this._radiusIsAnimating = false;
  98620. if (this._attachedCamera) {
  98621. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  98622. }
  98623. };
  98624. /**
  98625. * Stops and removes all animations that have been applied to the camera
  98626. */
  98627. BouncingBehavior.prototype.stopAllAnimations = function () {
  98628. if (this._attachedCamera) {
  98629. this._attachedCamera.animations = [];
  98630. }
  98631. while (this._animatables.length) {
  98632. this._animatables[0].onAnimationEnd = null;
  98633. this._animatables[0].stop();
  98634. this._animatables.shift();
  98635. }
  98636. };
  98637. /**
  98638. * The easing function used by animations
  98639. */
  98640. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  98641. /**
  98642. * The easing mode used by animations
  98643. */
  98644. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  98645. return BouncingBehavior;
  98646. }());
  98647. BABYLON.BouncingBehavior = BouncingBehavior;
  98648. })(BABYLON || (BABYLON = {}));
  98649. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  98650. var BABYLON;
  98651. (function (BABYLON) {
  98652. var AutoRotationBehavior = /** @class */ (function () {
  98653. function AutoRotationBehavior() {
  98654. this._zoomStopsAnimation = false;
  98655. this._idleRotationSpeed = 0.05;
  98656. this._idleRotationWaitTime = 2000;
  98657. this._idleRotationSpinupTime = 2000;
  98658. this._isPointerDown = false;
  98659. this._lastFrameTime = null;
  98660. this._lastInteractionTime = -Infinity;
  98661. this._cameraRotationSpeed = 0;
  98662. this._lastFrameRadius = 0;
  98663. }
  98664. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  98665. get: function () {
  98666. return "AutoRotation";
  98667. },
  98668. enumerable: true,
  98669. configurable: true
  98670. });
  98671. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  98672. /**
  98673. * Gets the flag that indicates if user zooming should stop animation.
  98674. */
  98675. get: function () {
  98676. return this._zoomStopsAnimation;
  98677. },
  98678. /**
  98679. * Sets the flag that indicates if user zooming should stop animation.
  98680. */
  98681. set: function (flag) {
  98682. this._zoomStopsAnimation = flag;
  98683. },
  98684. enumerable: true,
  98685. configurable: true
  98686. });
  98687. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  98688. /**
  98689. * Gets the default speed at which the camera rotates around the model.
  98690. */
  98691. get: function () {
  98692. return this._idleRotationSpeed;
  98693. },
  98694. /**
  98695. * Sets the default speed at which the camera rotates around the model.
  98696. */
  98697. set: function (speed) {
  98698. this._idleRotationSpeed = speed;
  98699. },
  98700. enumerable: true,
  98701. configurable: true
  98702. });
  98703. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  98704. /**
  98705. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  98706. */
  98707. get: function () {
  98708. return this._idleRotationWaitTime;
  98709. },
  98710. /**
  98711. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  98712. */
  98713. set: function (time) {
  98714. this._idleRotationWaitTime = time;
  98715. },
  98716. enumerable: true,
  98717. configurable: true
  98718. });
  98719. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  98720. /**
  98721. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98722. */
  98723. get: function () {
  98724. return this._idleRotationSpinupTime;
  98725. },
  98726. /**
  98727. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98728. */
  98729. set: function (time) {
  98730. this._idleRotationSpinupTime = time;
  98731. },
  98732. enumerable: true,
  98733. configurable: true
  98734. });
  98735. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  98736. /**
  98737. * Gets a value indicating if the camera is currently rotating because of this behavior
  98738. */
  98739. get: function () {
  98740. return Math.abs(this._cameraRotationSpeed) > 0;
  98741. },
  98742. enumerable: true,
  98743. configurable: true
  98744. });
  98745. AutoRotationBehavior.prototype.init = function () {
  98746. // Do notihng
  98747. };
  98748. AutoRotationBehavior.prototype.attach = function (camera) {
  98749. var _this = this;
  98750. this._attachedCamera = camera;
  98751. var scene = this._attachedCamera.getScene();
  98752. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98753. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98754. _this._isPointerDown = true;
  98755. return;
  98756. }
  98757. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98758. _this._isPointerDown = false;
  98759. }
  98760. });
  98761. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98762. var now = BABYLON.Tools.Now;
  98763. var dt = 0;
  98764. if (_this._lastFrameTime != null) {
  98765. dt = now - _this._lastFrameTime;
  98766. }
  98767. _this._lastFrameTime = now;
  98768. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98769. _this._applyUserInteraction();
  98770. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  98771. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  98772. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  98773. // Step camera rotation by rotation speed
  98774. if (_this._attachedCamera) {
  98775. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  98776. }
  98777. });
  98778. };
  98779. AutoRotationBehavior.prototype.detach = function () {
  98780. if (!this._attachedCamera) {
  98781. return;
  98782. }
  98783. var scene = this._attachedCamera.getScene();
  98784. if (this._onPrePointerObservableObserver) {
  98785. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98786. }
  98787. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98788. this._attachedCamera = null;
  98789. };
  98790. /**
  98791. * Returns true if user is scrolling.
  98792. * @return true if user is scrolling.
  98793. */
  98794. AutoRotationBehavior.prototype._userIsZooming = function () {
  98795. if (!this._attachedCamera) {
  98796. return false;
  98797. }
  98798. return this._attachedCamera.inertialRadiusOffset !== 0;
  98799. };
  98800. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  98801. if (!this._attachedCamera) {
  98802. return false;
  98803. }
  98804. var zoomHasHitLimit = false;
  98805. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  98806. zoomHasHitLimit = true;
  98807. }
  98808. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  98809. this._lastFrameRadius = this._attachedCamera.radius;
  98810. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  98811. };
  98812. /**
  98813. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98814. */
  98815. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  98816. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  98817. this._lastInteractionTime = BABYLON.Tools.Now;
  98818. }
  98819. };
  98820. // Tools
  98821. AutoRotationBehavior.prototype._userIsMoving = function () {
  98822. if (!this._attachedCamera) {
  98823. return false;
  98824. }
  98825. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98826. this._attachedCamera.inertialBetaOffset !== 0 ||
  98827. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98828. this._attachedCamera.inertialPanningX !== 0 ||
  98829. this._attachedCamera.inertialPanningY !== 0 ||
  98830. this._isPointerDown;
  98831. };
  98832. return AutoRotationBehavior;
  98833. }());
  98834. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  98835. })(BABYLON || (BABYLON = {}));
  98836. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  98837. var BABYLON;
  98838. (function (BABYLON) {
  98839. var NullEngineOptions = /** @class */ (function () {
  98840. function NullEngineOptions() {
  98841. this.renderWidth = 512;
  98842. this.renderHeight = 256;
  98843. this.textureSize = 512;
  98844. this.deterministicLockstep = false;
  98845. this.lockstepMaxSteps = 4;
  98846. }
  98847. return NullEngineOptions;
  98848. }());
  98849. BABYLON.NullEngineOptions = NullEngineOptions;
  98850. /**
  98851. * The null engine class provides support for headless version of babylon.js.
  98852. * This can be used in server side scenario or for testing purposes
  98853. */
  98854. var NullEngine = /** @class */ (function (_super) {
  98855. __extends(NullEngine, _super);
  98856. function NullEngine(options) {
  98857. if (options === void 0) { options = new NullEngineOptions(); }
  98858. var _this = _super.call(this, null) || this;
  98859. if (options.deterministicLockstep === undefined) {
  98860. options.deterministicLockstep = false;
  98861. }
  98862. if (options.lockstepMaxSteps === undefined) {
  98863. options.lockstepMaxSteps = 4;
  98864. }
  98865. _this._options = options;
  98866. // Init caps
  98867. // We consider we are on a webgl1 capable device
  98868. _this._caps = new BABYLON.EngineCapabilities();
  98869. _this._caps.maxTexturesImageUnits = 16;
  98870. _this._caps.maxVertexTextureImageUnits = 16;
  98871. _this._caps.maxTextureSize = 512;
  98872. _this._caps.maxCubemapTextureSize = 512;
  98873. _this._caps.maxRenderTextureSize = 512;
  98874. _this._caps.maxVertexAttribs = 16;
  98875. _this._caps.maxVaryingVectors = 16;
  98876. _this._caps.maxFragmentUniformVectors = 16;
  98877. _this._caps.maxVertexUniformVectors = 16;
  98878. // Extensions
  98879. _this._caps.standardDerivatives = false;
  98880. _this._caps.astc = null;
  98881. _this._caps.s3tc = null;
  98882. _this._caps.pvrtc = null;
  98883. _this._caps.etc1 = null;
  98884. _this._caps.etc2 = null;
  98885. _this._caps.textureAnisotropicFilterExtension = null;
  98886. _this._caps.maxAnisotropy = 0;
  98887. _this._caps.uintIndices = false;
  98888. _this._caps.fragmentDepthSupported = false;
  98889. _this._caps.highPrecisionShaderSupported = true;
  98890. _this._caps.colorBufferFloat = false;
  98891. _this._caps.textureFloat = false;
  98892. _this._caps.textureFloatLinearFiltering = false;
  98893. _this._caps.textureFloatRender = false;
  98894. _this._caps.textureHalfFloat = false;
  98895. _this._caps.textureHalfFloatLinearFiltering = false;
  98896. _this._caps.textureHalfFloatRender = false;
  98897. _this._caps.textureLOD = false;
  98898. _this._caps.drawBuffersExtension = false;
  98899. _this._caps.depthTextureExtension = false;
  98900. _this._caps.vertexArrayObject = false;
  98901. _this._caps.instancedArrays = false;
  98902. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  98903. // Wrappers
  98904. if (typeof URL === "undefined") {
  98905. URL = {
  98906. createObjectURL: function () { },
  98907. revokeObjectURL: function () { }
  98908. };
  98909. }
  98910. if (typeof Blob === "undefined") {
  98911. Blob = function () { };
  98912. }
  98913. return _this;
  98914. }
  98915. NullEngine.prototype.isDeterministicLockStep = function () {
  98916. return this._options.deterministicLockstep;
  98917. };
  98918. NullEngine.prototype.getLockstepMaxSteps = function () {
  98919. return this._options.lockstepMaxSteps;
  98920. };
  98921. NullEngine.prototype.getHardwareScalingLevel = function () {
  98922. return 1.0;
  98923. };
  98924. NullEngine.prototype.createVertexBuffer = function (vertices) {
  98925. return {
  98926. capacity: 0,
  98927. references: 1,
  98928. is32Bits: false
  98929. };
  98930. };
  98931. NullEngine.prototype.createIndexBuffer = function (indices) {
  98932. return {
  98933. capacity: 0,
  98934. references: 1,
  98935. is32Bits: false
  98936. };
  98937. };
  98938. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  98939. if (stencil === void 0) { stencil = false; }
  98940. };
  98941. NullEngine.prototype.getRenderWidth = function (useScreen) {
  98942. if (useScreen === void 0) { useScreen = false; }
  98943. if (!useScreen && this._currentRenderTarget) {
  98944. return this._currentRenderTarget.width;
  98945. }
  98946. return this._options.renderWidth;
  98947. };
  98948. NullEngine.prototype.getRenderHeight = function (useScreen) {
  98949. if (useScreen === void 0) { useScreen = false; }
  98950. if (!useScreen && this._currentRenderTarget) {
  98951. return this._currentRenderTarget.height;
  98952. }
  98953. return this._options.renderHeight;
  98954. };
  98955. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  98956. this._cachedViewport = viewport;
  98957. };
  98958. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  98959. return {
  98960. transformFeedback: null,
  98961. __SPECTOR_rebuildProgram: null
  98962. };
  98963. };
  98964. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  98965. return [];
  98966. };
  98967. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  98968. return [];
  98969. };
  98970. NullEngine.prototype.bindSamplers = function (effect) {
  98971. this._currentEffect = null;
  98972. };
  98973. NullEngine.prototype.enableEffect = function (effect) {
  98974. this._currentEffect = effect;
  98975. if (effect.onBind) {
  98976. effect.onBind(effect);
  98977. }
  98978. effect.onBindObservable.notifyObservers(effect);
  98979. };
  98980. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  98981. if (zOffset === void 0) { zOffset = 0; }
  98982. if (reverseSide === void 0) { reverseSide = false; }
  98983. };
  98984. NullEngine.prototype.setIntArray = function (uniform, array) {
  98985. };
  98986. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  98987. };
  98988. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  98989. };
  98990. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  98991. };
  98992. NullEngine.prototype.setFloatArray = function (uniform, array) {
  98993. };
  98994. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  98995. };
  98996. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  98997. };
  98998. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  98999. };
  99000. NullEngine.prototype.setArray = function (uniform, array) {
  99001. };
  99002. NullEngine.prototype.setArray2 = function (uniform, array) {
  99003. };
  99004. NullEngine.prototype.setArray3 = function (uniform, array) {
  99005. };
  99006. NullEngine.prototype.setArray4 = function (uniform, array) {
  99007. };
  99008. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  99009. };
  99010. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  99011. };
  99012. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  99013. };
  99014. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  99015. };
  99016. NullEngine.prototype.setFloat = function (uniform, value) {
  99017. };
  99018. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  99019. };
  99020. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  99021. };
  99022. NullEngine.prototype.setBool = function (uniform, bool) {
  99023. };
  99024. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  99025. };
  99026. NullEngine.prototype.setColor3 = function (uniform, color3) {
  99027. };
  99028. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  99029. };
  99030. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  99031. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  99032. if (this._alphaMode === mode) {
  99033. return;
  99034. }
  99035. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  99036. if (!noDepthWriteChange) {
  99037. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  99038. }
  99039. this._alphaMode = mode;
  99040. };
  99041. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  99042. };
  99043. NullEngine.prototype.wipeCaches = function (bruteForce) {
  99044. if (this.preventCacheWipeBetweenFrames) {
  99045. return;
  99046. }
  99047. this.resetTextureCache();
  99048. this._currentEffect = null;
  99049. if (bruteForce) {
  99050. this._currentProgram = null;
  99051. this._stencilState.reset();
  99052. this._depthCullingState.reset();
  99053. this._alphaState.reset();
  99054. }
  99055. this._cachedVertexBuffers = null;
  99056. this._cachedIndexBuffer = null;
  99057. this._cachedEffectForVertexBuffers = null;
  99058. };
  99059. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  99060. };
  99061. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  99062. };
  99063. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  99064. };
  99065. NullEngine.prototype._createTexture = function () {
  99066. return {};
  99067. };
  99068. NullEngine.prototype._releaseTexture = function (texture) {
  99069. };
  99070. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  99071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99072. if (onLoad === void 0) { onLoad = null; }
  99073. if (onError === void 0) { onError = null; }
  99074. if (buffer === void 0) { buffer = null; }
  99075. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  99076. var url = String(urlArg);
  99077. texture.url = url;
  99078. texture.generateMipMaps = !noMipmap;
  99079. texture.samplingMode = samplingMode;
  99080. texture.invertY = invertY;
  99081. texture.baseWidth = this._options.textureSize;
  99082. texture.baseHeight = this._options.textureSize;
  99083. texture.width = this._options.textureSize;
  99084. texture.height = this._options.textureSize;
  99085. if (format) {
  99086. texture.format = format;
  99087. }
  99088. texture.isReady = true;
  99089. if (onLoad) {
  99090. onLoad();
  99091. }
  99092. this._internalTexturesCache.push(texture);
  99093. return texture;
  99094. };
  99095. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  99096. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  99097. if (options !== undefined && typeof options === "object") {
  99098. fullOptions.generateMipMaps = options.generateMipMaps;
  99099. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  99100. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  99101. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  99102. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  99103. }
  99104. else {
  99105. fullOptions.generateMipMaps = options;
  99106. fullOptions.generateDepthBuffer = true;
  99107. fullOptions.generateStencilBuffer = false;
  99108. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99109. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  99110. }
  99111. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  99112. var width = size.width || size;
  99113. var height = size.height || size;
  99114. texture._depthStencilBuffer = {};
  99115. texture._framebuffer = {};
  99116. texture.baseWidth = width;
  99117. texture.baseHeight = height;
  99118. texture.width = width;
  99119. texture.height = height;
  99120. texture.isReady = true;
  99121. texture.samples = 1;
  99122. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  99123. texture.samplingMode = fullOptions.samplingMode;
  99124. texture.type = fullOptions.type;
  99125. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  99126. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  99127. this._internalTexturesCache.push(texture);
  99128. return texture;
  99129. };
  99130. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  99131. texture.samplingMode = samplingMode;
  99132. };
  99133. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  99134. if (this._currentRenderTarget) {
  99135. this.unBindFramebuffer(this._currentRenderTarget);
  99136. }
  99137. this._currentRenderTarget = texture;
  99138. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  99139. if (this._cachedViewport && !forceFullscreenViewport) {
  99140. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  99141. }
  99142. };
  99143. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  99144. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  99145. this._currentRenderTarget = null;
  99146. if (onBeforeUnbind) {
  99147. if (texture._MSAAFramebuffer) {
  99148. this._currentFramebuffer = texture._framebuffer;
  99149. }
  99150. onBeforeUnbind();
  99151. }
  99152. this._currentFramebuffer = null;
  99153. };
  99154. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  99155. var vbo = {
  99156. capacity: 1,
  99157. references: 1,
  99158. is32Bits: false
  99159. };
  99160. return vbo;
  99161. };
  99162. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  99163. if (offset === void 0) { offset = 0; }
  99164. };
  99165. /**
  99166. * Updates a dynamic vertex buffer.
  99167. * @param vertexBuffer the vertex buffer to update
  99168. * @param data the data used to update the vertex buffer
  99169. * @param byteOffset the byte offset of the data (optional)
  99170. * @param byteLength the byte length of the data (optional)
  99171. */
  99172. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  99173. };
  99174. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  99175. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  99176. this._boundTexturesCache[this._activeChannel] = texture;
  99177. return true;
  99178. }
  99179. return false;
  99180. };
  99181. NullEngine.prototype._bindTexture = function (channel, texture) {
  99182. if (channel < 0) {
  99183. return;
  99184. }
  99185. this._bindTextureDirectly(0, texture);
  99186. };
  99187. NullEngine.prototype._releaseBuffer = function (buffer) {
  99188. buffer.references--;
  99189. if (buffer.references === 0) {
  99190. return true;
  99191. }
  99192. return false;
  99193. };
  99194. NullEngine.prototype.releaseEffects = function () {
  99195. };
  99196. return NullEngine;
  99197. }(BABYLON.Engine));
  99198. BABYLON.NullEngine = NullEngine;
  99199. })(BABYLON || (BABYLON = {}));
  99200. //# sourceMappingURL=babylon.nullEngine.js.map
  99201. var BABYLON;
  99202. (function (BABYLON) {
  99203. /**
  99204. * This class can be used to get instrumentation data from a Babylon engine
  99205. */
  99206. var EngineInstrumentation = /** @class */ (function () {
  99207. function EngineInstrumentation(engine) {
  99208. this.engine = engine;
  99209. this._captureGPUFrameTime = false;
  99210. this._gpuFrameTime = new BABYLON.PerfCounter();
  99211. this._captureShaderCompilationTime = false;
  99212. this._shaderCompilationTime = new BABYLON.PerfCounter();
  99213. // Observers
  99214. this._onBeginFrameObserver = null;
  99215. this._onEndFrameObserver = null;
  99216. this._onBeforeShaderCompilationObserver = null;
  99217. this._onAfterShaderCompilationObserver = null;
  99218. }
  99219. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  99220. // Properties
  99221. /**
  99222. * Gets the perf counter used for GPU frame time
  99223. */
  99224. get: function () {
  99225. return this._gpuFrameTime;
  99226. },
  99227. enumerable: true,
  99228. configurable: true
  99229. });
  99230. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  99231. /**
  99232. * Gets the GPU frame time capture status
  99233. */
  99234. get: function () {
  99235. return this._captureGPUFrameTime;
  99236. },
  99237. /**
  99238. * Enable or disable the GPU frame time capture
  99239. */
  99240. set: function (value) {
  99241. var _this = this;
  99242. if (value === this._captureGPUFrameTime) {
  99243. return;
  99244. }
  99245. this._captureGPUFrameTime = value;
  99246. if (value) {
  99247. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  99248. if (!_this._gpuFrameTimeToken) {
  99249. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  99250. }
  99251. });
  99252. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  99253. if (!_this._gpuFrameTimeToken) {
  99254. return;
  99255. }
  99256. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  99257. if (time > -1) {
  99258. _this._gpuFrameTimeToken = null;
  99259. _this._gpuFrameTime.fetchNewFrame();
  99260. _this._gpuFrameTime.addCount(time, true);
  99261. }
  99262. });
  99263. }
  99264. else {
  99265. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99266. this._onBeginFrameObserver = null;
  99267. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99268. this._onEndFrameObserver = null;
  99269. }
  99270. },
  99271. enumerable: true,
  99272. configurable: true
  99273. });
  99274. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  99275. /**
  99276. * Gets the perf counter used for shader compilation time
  99277. */
  99278. get: function () {
  99279. return this._shaderCompilationTime;
  99280. },
  99281. enumerable: true,
  99282. configurable: true
  99283. });
  99284. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  99285. /**
  99286. * Gets the shader compilation time capture status
  99287. */
  99288. get: function () {
  99289. return this._captureShaderCompilationTime;
  99290. },
  99291. /**
  99292. * Enable or disable the shader compilation time capture
  99293. */
  99294. set: function (value) {
  99295. var _this = this;
  99296. if (value === this._captureShaderCompilationTime) {
  99297. return;
  99298. }
  99299. this._captureShaderCompilationTime = value;
  99300. if (value) {
  99301. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  99302. _this._shaderCompilationTime.fetchNewFrame();
  99303. _this._shaderCompilationTime.beginMonitoring();
  99304. });
  99305. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  99306. _this._shaderCompilationTime.endMonitoring();
  99307. });
  99308. }
  99309. else {
  99310. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99311. this._onBeforeShaderCompilationObserver = null;
  99312. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99313. this._onAfterShaderCompilationObserver = null;
  99314. }
  99315. },
  99316. enumerable: true,
  99317. configurable: true
  99318. });
  99319. EngineInstrumentation.prototype.dispose = function () {
  99320. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99321. this._onBeginFrameObserver = null;
  99322. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99323. this._onEndFrameObserver = null;
  99324. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99325. this._onBeforeShaderCompilationObserver = null;
  99326. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99327. this._onAfterShaderCompilationObserver = null;
  99328. this.engine = null;
  99329. };
  99330. return EngineInstrumentation;
  99331. }());
  99332. BABYLON.EngineInstrumentation = EngineInstrumentation;
  99333. })(BABYLON || (BABYLON = {}));
  99334. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  99335. var BABYLON;
  99336. (function (BABYLON) {
  99337. /**
  99338. * This class can be used to get instrumentation data from a Babylon engine
  99339. */
  99340. var SceneInstrumentation = /** @class */ (function () {
  99341. function SceneInstrumentation(scene) {
  99342. var _this = this;
  99343. this.scene = scene;
  99344. this._captureActiveMeshesEvaluationTime = false;
  99345. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  99346. this._captureRenderTargetsRenderTime = false;
  99347. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  99348. this._captureFrameTime = false;
  99349. this._frameTime = new BABYLON.PerfCounter();
  99350. this._captureRenderTime = false;
  99351. this._renderTime = new BABYLON.PerfCounter();
  99352. this._captureInterFrameTime = false;
  99353. this._interFrameTime = new BABYLON.PerfCounter();
  99354. this._captureParticlesRenderTime = false;
  99355. this._particlesRenderTime = new BABYLON.PerfCounter();
  99356. this._captureSpritesRenderTime = false;
  99357. this._spritesRenderTime = new BABYLON.PerfCounter();
  99358. this._capturePhysicsTime = false;
  99359. this._physicsTime = new BABYLON.PerfCounter();
  99360. this._captureAnimationsTime = false;
  99361. this._animationsTime = new BABYLON.PerfCounter();
  99362. this._captureCameraRenderTime = false;
  99363. this._cameraRenderTime = new BABYLON.PerfCounter();
  99364. // Observers
  99365. this._onBeforeActiveMeshesEvaluationObserver = null;
  99366. this._onAfterActiveMeshesEvaluationObserver = null;
  99367. this._onBeforeRenderTargetsRenderObserver = null;
  99368. this._onAfterRenderTargetsRenderObserver = null;
  99369. this._onAfterRenderObserver = null;
  99370. this._onBeforeDrawPhaseObserver = null;
  99371. this._onAfterDrawPhaseObserver = null;
  99372. this._onBeforeAnimationsObserver = null;
  99373. this._onBeforeParticlesRenderingObserver = null;
  99374. this._onAfterParticlesRenderingObserver = null;
  99375. this._onBeforeSpritesRenderingObserver = null;
  99376. this._onAfterSpritesRenderingObserver = null;
  99377. this._onBeforePhysicsObserver = null;
  99378. this._onAfterPhysicsObserver = null;
  99379. this._onAfterAnimationsObserver = null;
  99380. this._onBeforeCameraRenderObserver = null;
  99381. this._onAfterCameraRenderObserver = null;
  99382. // Before render
  99383. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  99384. if (_this._captureActiveMeshesEvaluationTime) {
  99385. _this._activeMeshesEvaluationTime.fetchNewFrame();
  99386. }
  99387. if (_this._captureRenderTargetsRenderTime) {
  99388. _this._renderTargetsRenderTime.fetchNewFrame();
  99389. }
  99390. if (_this._captureFrameTime) {
  99391. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  99392. _this._frameTime.beginMonitoring();
  99393. }
  99394. if (_this._captureInterFrameTime) {
  99395. _this._interFrameTime.endMonitoring();
  99396. }
  99397. if (_this._captureParticlesRenderTime) {
  99398. _this._particlesRenderTime.fetchNewFrame();
  99399. }
  99400. if (_this._captureSpritesRenderTime) {
  99401. _this._spritesRenderTime.fetchNewFrame();
  99402. }
  99403. if (_this._captureAnimationsTime) {
  99404. _this._animationsTime.beginMonitoring();
  99405. }
  99406. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  99407. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  99408. });
  99409. // After render
  99410. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  99411. if (_this._captureFrameTime) {
  99412. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  99413. _this._frameTime.endMonitoring();
  99414. }
  99415. if (_this._captureRenderTime) {
  99416. _this._renderTime.endMonitoring(false);
  99417. }
  99418. if (_this._captureInterFrameTime) {
  99419. _this._interFrameTime.beginMonitoring();
  99420. }
  99421. });
  99422. }
  99423. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  99424. // Properties
  99425. /**
  99426. * Gets the perf counter used for active meshes evaluation time
  99427. */
  99428. get: function () {
  99429. return this._activeMeshesEvaluationTime;
  99430. },
  99431. enumerable: true,
  99432. configurable: true
  99433. });
  99434. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  99435. /**
  99436. * Gets the active meshes evaluation time capture status
  99437. */
  99438. get: function () {
  99439. return this._captureActiveMeshesEvaluationTime;
  99440. },
  99441. /**
  99442. * Enable or disable the active meshes evaluation time capture
  99443. */
  99444. set: function (value) {
  99445. var _this = this;
  99446. if (value === this._captureActiveMeshesEvaluationTime) {
  99447. return;
  99448. }
  99449. this._captureActiveMeshesEvaluationTime = value;
  99450. if (value) {
  99451. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  99452. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  99453. _this._activeMeshesEvaluationTime.beginMonitoring();
  99454. });
  99455. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  99456. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  99457. _this._activeMeshesEvaluationTime.endMonitoring();
  99458. });
  99459. }
  99460. else {
  99461. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99462. this._onBeforeActiveMeshesEvaluationObserver = null;
  99463. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99464. this._onAfterActiveMeshesEvaluationObserver = null;
  99465. }
  99466. },
  99467. enumerable: true,
  99468. configurable: true
  99469. });
  99470. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  99471. /**
  99472. * Gets the perf counter used for render targets render time
  99473. */
  99474. get: function () {
  99475. return this._renderTargetsRenderTime;
  99476. },
  99477. enumerable: true,
  99478. configurable: true
  99479. });
  99480. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  99481. /**
  99482. * Gets the render targets render time capture status
  99483. */
  99484. get: function () {
  99485. return this._captureRenderTargetsRenderTime;
  99486. },
  99487. /**
  99488. * Enable or disable the render targets render time capture
  99489. */
  99490. set: function (value) {
  99491. var _this = this;
  99492. if (value === this._captureRenderTargetsRenderTime) {
  99493. return;
  99494. }
  99495. this._captureRenderTargetsRenderTime = value;
  99496. if (value) {
  99497. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  99498. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  99499. _this._renderTargetsRenderTime.beginMonitoring();
  99500. });
  99501. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  99502. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  99503. _this._renderTargetsRenderTime.endMonitoring(false);
  99504. });
  99505. }
  99506. else {
  99507. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99508. this._onBeforeRenderTargetsRenderObserver = null;
  99509. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99510. this._onAfterRenderTargetsRenderObserver = null;
  99511. }
  99512. },
  99513. enumerable: true,
  99514. configurable: true
  99515. });
  99516. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  99517. /**
  99518. * Gets the perf counter used for particles render time
  99519. */
  99520. get: function () {
  99521. return this._particlesRenderTime;
  99522. },
  99523. enumerable: true,
  99524. configurable: true
  99525. });
  99526. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  99527. /**
  99528. * Gets the particles render time capture status
  99529. */
  99530. get: function () {
  99531. return this._captureParticlesRenderTime;
  99532. },
  99533. /**
  99534. * Enable or disable the particles render time capture
  99535. */
  99536. set: function (value) {
  99537. var _this = this;
  99538. if (value === this._captureParticlesRenderTime) {
  99539. return;
  99540. }
  99541. this._captureParticlesRenderTime = value;
  99542. if (value) {
  99543. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  99544. BABYLON.Tools.StartPerformanceCounter("Particles");
  99545. _this._particlesRenderTime.beginMonitoring();
  99546. });
  99547. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  99548. BABYLON.Tools.EndPerformanceCounter("Particles");
  99549. _this._particlesRenderTime.endMonitoring(false);
  99550. });
  99551. }
  99552. else {
  99553. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99554. this._onBeforeParticlesRenderingObserver = null;
  99555. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99556. this._onAfterParticlesRenderingObserver = null;
  99557. }
  99558. },
  99559. enumerable: true,
  99560. configurable: true
  99561. });
  99562. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  99563. /**
  99564. * Gets the perf counter used for sprites render time
  99565. */
  99566. get: function () {
  99567. return this._spritesRenderTime;
  99568. },
  99569. enumerable: true,
  99570. configurable: true
  99571. });
  99572. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  99573. /**
  99574. * Gets the sprites render time capture status
  99575. */
  99576. get: function () {
  99577. return this._captureSpritesRenderTime;
  99578. },
  99579. /**
  99580. * Enable or disable the sprites render time capture
  99581. */
  99582. set: function (value) {
  99583. var _this = this;
  99584. if (value === this._captureSpritesRenderTime) {
  99585. return;
  99586. }
  99587. this._captureSpritesRenderTime = value;
  99588. if (value) {
  99589. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  99590. BABYLON.Tools.StartPerformanceCounter("Sprites");
  99591. _this._spritesRenderTime.beginMonitoring();
  99592. });
  99593. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  99594. BABYLON.Tools.EndPerformanceCounter("Sprites");
  99595. _this._spritesRenderTime.endMonitoring(false);
  99596. });
  99597. }
  99598. else {
  99599. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99600. this._onBeforeSpritesRenderingObserver = null;
  99601. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99602. this._onAfterSpritesRenderingObserver = null;
  99603. }
  99604. },
  99605. enumerable: true,
  99606. configurable: true
  99607. });
  99608. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  99609. /**
  99610. * Gets the perf counter used for physics time
  99611. */
  99612. get: function () {
  99613. return this._physicsTime;
  99614. },
  99615. enumerable: true,
  99616. configurable: true
  99617. });
  99618. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  99619. /**
  99620. * Gets the physics time capture status
  99621. */
  99622. get: function () {
  99623. return this._capturePhysicsTime;
  99624. },
  99625. /**
  99626. * Enable or disable the physics time capture
  99627. */
  99628. set: function (value) {
  99629. var _this = this;
  99630. if (value === this._capturePhysicsTime) {
  99631. return;
  99632. }
  99633. this._capturePhysicsTime = value;
  99634. if (value) {
  99635. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  99636. BABYLON.Tools.StartPerformanceCounter("Physics");
  99637. _this._physicsTime.beginMonitoring();
  99638. });
  99639. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  99640. BABYLON.Tools.EndPerformanceCounter("Physics");
  99641. _this._physicsTime.endMonitoring();
  99642. });
  99643. }
  99644. else {
  99645. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99646. this._onBeforePhysicsObserver = null;
  99647. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99648. this._onAfterPhysicsObserver = null;
  99649. }
  99650. },
  99651. enumerable: true,
  99652. configurable: true
  99653. });
  99654. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  99655. /**
  99656. * Gets the perf counter used for animations time
  99657. */
  99658. get: function () {
  99659. return this._animationsTime;
  99660. },
  99661. enumerable: true,
  99662. configurable: true
  99663. });
  99664. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  99665. /**
  99666. * Gets the animations time capture status
  99667. */
  99668. get: function () {
  99669. return this._captureAnimationsTime;
  99670. },
  99671. /**
  99672. * Enable or disable the animations time capture
  99673. */
  99674. set: function (value) {
  99675. var _this = this;
  99676. if (value === this._captureAnimationsTime) {
  99677. return;
  99678. }
  99679. this._captureAnimationsTime = value;
  99680. if (value) {
  99681. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  99682. _this._animationsTime.endMonitoring();
  99683. });
  99684. }
  99685. else {
  99686. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99687. this._onAfterAnimationsObserver = null;
  99688. }
  99689. },
  99690. enumerable: true,
  99691. configurable: true
  99692. });
  99693. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  99694. /**
  99695. * Gets the perf counter used for frame time capture
  99696. */
  99697. get: function () {
  99698. return this._frameTime;
  99699. },
  99700. enumerable: true,
  99701. configurable: true
  99702. });
  99703. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  99704. /**
  99705. * Gets the frame time capture status
  99706. */
  99707. get: function () {
  99708. return this._captureFrameTime;
  99709. },
  99710. /**
  99711. * Enable or disable the frame time capture
  99712. */
  99713. set: function (value) {
  99714. this._captureFrameTime = value;
  99715. },
  99716. enumerable: true,
  99717. configurable: true
  99718. });
  99719. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  99720. /**
  99721. * Gets the perf counter used for inter-frames time capture
  99722. */
  99723. get: function () {
  99724. return this._interFrameTime;
  99725. },
  99726. enumerable: true,
  99727. configurable: true
  99728. });
  99729. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  99730. /**
  99731. * Gets the inter-frames time capture status
  99732. */
  99733. get: function () {
  99734. return this._captureInterFrameTime;
  99735. },
  99736. /**
  99737. * Enable or disable the inter-frames time capture
  99738. */
  99739. set: function (value) {
  99740. this._captureInterFrameTime = value;
  99741. },
  99742. enumerable: true,
  99743. configurable: true
  99744. });
  99745. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  99746. /**
  99747. * Gets the perf counter used for render time capture
  99748. */
  99749. get: function () {
  99750. return this._renderTime;
  99751. },
  99752. enumerable: true,
  99753. configurable: true
  99754. });
  99755. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  99756. /**
  99757. * Gets the render time capture status
  99758. */
  99759. get: function () {
  99760. return this._captureRenderTime;
  99761. },
  99762. /**
  99763. * Enable or disable the render time capture
  99764. */
  99765. set: function (value) {
  99766. var _this = this;
  99767. if (value === this._captureRenderTime) {
  99768. return;
  99769. }
  99770. this._captureRenderTime = value;
  99771. if (value) {
  99772. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  99773. _this._renderTime.beginMonitoring();
  99774. BABYLON.Tools.StartPerformanceCounter("Main render");
  99775. });
  99776. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  99777. _this._renderTime.endMonitoring(false);
  99778. BABYLON.Tools.EndPerformanceCounter("Main render");
  99779. });
  99780. }
  99781. else {
  99782. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99783. this._onBeforeDrawPhaseObserver = null;
  99784. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99785. this._onAfterDrawPhaseObserver = null;
  99786. }
  99787. },
  99788. enumerable: true,
  99789. configurable: true
  99790. });
  99791. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  99792. /**
  99793. * Gets the perf counter used for camera render time capture
  99794. */
  99795. get: function () {
  99796. return this._cameraRenderTime;
  99797. },
  99798. enumerable: true,
  99799. configurable: true
  99800. });
  99801. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  99802. /**
  99803. * Gets the camera render time capture status
  99804. */
  99805. get: function () {
  99806. return this._captureCameraRenderTime;
  99807. },
  99808. /**
  99809. * Enable or disable the camera render time capture
  99810. */
  99811. set: function (value) {
  99812. var _this = this;
  99813. if (value === this._captureCameraRenderTime) {
  99814. return;
  99815. }
  99816. this._captureCameraRenderTime = value;
  99817. if (value) {
  99818. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  99819. _this._cameraRenderTime.beginMonitoring();
  99820. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  99821. });
  99822. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  99823. _this._cameraRenderTime.endMonitoring(false);
  99824. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  99825. });
  99826. }
  99827. else {
  99828. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99829. this._onBeforeCameraRenderObserver = null;
  99830. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99831. this._onAfterCameraRenderObserver = null;
  99832. }
  99833. },
  99834. enumerable: true,
  99835. configurable: true
  99836. });
  99837. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  99838. /**
  99839. * Gets the perf counter used for draw calls
  99840. */
  99841. get: function () {
  99842. return this.scene.getEngine()._drawCalls;
  99843. },
  99844. enumerable: true,
  99845. configurable: true
  99846. });
  99847. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  99848. /**
  99849. * Gets the perf counter used for texture collisions
  99850. */
  99851. get: function () {
  99852. return this.scene.getEngine()._textureCollisions;
  99853. },
  99854. enumerable: true,
  99855. configurable: true
  99856. });
  99857. SceneInstrumentation.prototype.dispose = function () {
  99858. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99859. this._onAfterRenderObserver = null;
  99860. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99861. this._onBeforeActiveMeshesEvaluationObserver = null;
  99862. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99863. this._onAfterActiveMeshesEvaluationObserver = null;
  99864. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99865. this._onBeforeRenderTargetsRenderObserver = null;
  99866. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99867. this._onAfterRenderTargetsRenderObserver = null;
  99868. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  99869. this._onBeforeAnimationsObserver = null;
  99870. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99871. this._onBeforeParticlesRenderingObserver = null;
  99872. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99873. this._onAfterParticlesRenderingObserver = null;
  99874. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99875. this._onBeforeSpritesRenderingObserver = null;
  99876. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99877. this._onAfterSpritesRenderingObserver = null;
  99878. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99879. this._onBeforeDrawPhaseObserver = null;
  99880. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99881. this._onAfterDrawPhaseObserver = null;
  99882. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99883. this._onBeforePhysicsObserver = null;
  99884. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99885. this._onAfterPhysicsObserver = null;
  99886. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99887. this._onAfterAnimationsObserver = null;
  99888. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99889. this._onBeforeCameraRenderObserver = null;
  99890. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99891. this._onAfterCameraRenderObserver = null;
  99892. this.scene = null;
  99893. };
  99894. return SceneInstrumentation;
  99895. }());
  99896. BABYLON.SceneInstrumentation = SceneInstrumentation;
  99897. })(BABYLON || (BABYLON = {}));
  99898. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  99899. var BABYLON;
  99900. (function (BABYLON) {
  99901. /**
  99902. * @hidden
  99903. **/
  99904. var _TimeToken = /** @class */ (function () {
  99905. function _TimeToken() {
  99906. this._timeElapsedQueryEnded = false;
  99907. }
  99908. return _TimeToken;
  99909. }());
  99910. BABYLON._TimeToken = _TimeToken;
  99911. })(BABYLON || (BABYLON = {}));
  99912. //# sourceMappingURL=babylon.timeToken.js.map
  99913. var BABYLON;
  99914. (function (BABYLON) {
  99915. /**
  99916. * Background material defines definition.
  99917. * @hidden Mainly internal Use
  99918. */
  99919. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  99920. __extends(BackgroundMaterialDefines, _super);
  99921. /**
  99922. * Constructor of the defines.
  99923. */
  99924. function BackgroundMaterialDefines() {
  99925. var _this = _super.call(this) || this;
  99926. /**
  99927. * True if the diffuse texture is in use.
  99928. */
  99929. _this.DIFFUSE = false;
  99930. /**
  99931. * The direct UV channel to use.
  99932. */
  99933. _this.DIFFUSEDIRECTUV = 0;
  99934. /**
  99935. * True if the diffuse texture is in gamma space.
  99936. */
  99937. _this.GAMMADIFFUSE = false;
  99938. /**
  99939. * True if the diffuse texture has opacity in the alpha channel.
  99940. */
  99941. _this.DIFFUSEHASALPHA = false;
  99942. /**
  99943. * True if you want the material to fade to transparent at grazing angle.
  99944. */
  99945. _this.OPACITYFRESNEL = false;
  99946. /**
  99947. * True if an extra blur needs to be added in the reflection.
  99948. */
  99949. _this.REFLECTIONBLUR = false;
  99950. /**
  99951. * True if you want the material to fade to reflection at grazing angle.
  99952. */
  99953. _this.REFLECTIONFRESNEL = false;
  99954. /**
  99955. * True if you want the material to falloff as far as you move away from the scene center.
  99956. */
  99957. _this.REFLECTIONFALLOFF = false;
  99958. /**
  99959. * False if the current Webgl implementation does not support the texture lod extension.
  99960. */
  99961. _this.TEXTURELODSUPPORT = false;
  99962. /**
  99963. * True to ensure the data are premultiplied.
  99964. */
  99965. _this.PREMULTIPLYALPHA = false;
  99966. /**
  99967. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  99968. */
  99969. _this.USERGBCOLOR = false;
  99970. /**
  99971. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  99972. * stays aligned with the desired configuration.
  99973. */
  99974. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  99975. /**
  99976. * True to add noise in order to reduce the banding effect.
  99977. */
  99978. _this.NOISE = false;
  99979. /**
  99980. * is the reflection texture in BGR color scheme?
  99981. * Mainly used to solve a bug in ios10 video tag
  99982. */
  99983. _this.REFLECTIONBGR = false;
  99984. _this.IMAGEPROCESSING = false;
  99985. _this.VIGNETTE = false;
  99986. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  99987. _this.VIGNETTEBLENDMODEOPAQUE = false;
  99988. _this.TONEMAPPING = false;
  99989. _this.CONTRAST = false;
  99990. _this.COLORCURVES = false;
  99991. _this.COLORGRADING = false;
  99992. _this.COLORGRADING3D = false;
  99993. _this.SAMPLER3DGREENDEPTH = false;
  99994. _this.SAMPLER3DBGRMAP = false;
  99995. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  99996. _this.EXPOSURE = false;
  99997. // Reflection.
  99998. _this.REFLECTION = false;
  99999. _this.REFLECTIONMAP_3D = false;
  100000. _this.REFLECTIONMAP_SPHERICAL = false;
  100001. _this.REFLECTIONMAP_PLANAR = false;
  100002. _this.REFLECTIONMAP_CUBIC = false;
  100003. _this.REFLECTIONMAP_PROJECTION = false;
  100004. _this.REFLECTIONMAP_SKYBOX = false;
  100005. _this.REFLECTIONMAP_EXPLICIT = false;
  100006. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100007. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100008. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100009. _this.INVERTCUBICMAP = false;
  100010. _this.REFLECTIONMAP_OPPOSITEZ = false;
  100011. _this.LODINREFLECTIONALPHA = false;
  100012. _this.GAMMAREFLECTION = false;
  100013. _this.RGBDREFLECTION = false;
  100014. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  100015. // Default BJS.
  100016. _this.MAINUV1 = false;
  100017. _this.MAINUV2 = false;
  100018. _this.UV1 = false;
  100019. _this.UV2 = false;
  100020. _this.CLIPPLANE = false;
  100021. _this.POINTSIZE = false;
  100022. _this.FOG = false;
  100023. _this.NORMAL = false;
  100024. _this.NUM_BONE_INFLUENCERS = 0;
  100025. _this.BonesPerMesh = 0;
  100026. _this.INSTANCES = false;
  100027. _this.SHADOWFLOAT = false;
  100028. _this.rebuild();
  100029. return _this;
  100030. }
  100031. return BackgroundMaterialDefines;
  100032. }(BABYLON.MaterialDefines));
  100033. /**
  100034. * Background material used to create an efficient environement around your scene.
  100035. */
  100036. var BackgroundMaterial = /** @class */ (function (_super) {
  100037. __extends(BackgroundMaterial, _super);
  100038. /**
  100039. * Instantiates a Background Material in the given scene
  100040. * @param name The friendly name of the material
  100041. * @param scene The scene to add the material to
  100042. */
  100043. function BackgroundMaterial(name, scene) {
  100044. var _this = _super.call(this, name, scene) || this;
  100045. /**
  100046. * Key light Color (multiply against the environement texture)
  100047. */
  100048. _this.primaryColor = BABYLON.Color3.White();
  100049. _this._primaryColorShadowLevel = 0;
  100050. _this._primaryColorHighlightLevel = 0;
  100051. /**
  100052. * Reflection Texture used in the material.
  100053. * Should be author in a specific way for the best result (refer to the documentation).
  100054. */
  100055. _this.reflectionTexture = null;
  100056. /**
  100057. * Reflection Texture level of blur.
  100058. *
  100059. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  100060. * texture twice.
  100061. */
  100062. _this.reflectionBlur = 0;
  100063. /**
  100064. * Diffuse Texture used in the material.
  100065. * Should be author in a specific way for the best result (refer to the documentation).
  100066. */
  100067. _this.diffuseTexture = null;
  100068. _this._shadowLights = null;
  100069. /**
  100070. * Specify the list of lights casting shadow on the material.
  100071. * All scene shadow lights will be included if null.
  100072. */
  100073. _this.shadowLights = null;
  100074. /**
  100075. * Helps adjusting the shadow to a softer level if required.
  100076. * 0 means black shadows and 1 means no shadows.
  100077. */
  100078. _this.shadowLevel = 0;
  100079. /**
  100080. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  100081. * It is usually zero but might be interesting to modify according to your setup.
  100082. */
  100083. _this.sceneCenter = BABYLON.Vector3.Zero();
  100084. /**
  100085. * This helps specifying that the material is falling off to the sky box at grazing angle.
  100086. * This helps ensuring a nice transition when the camera goes under the ground.
  100087. */
  100088. _this.opacityFresnel = true;
  100089. /**
  100090. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  100091. * This helps adding a mirror texture on the ground.
  100092. */
  100093. _this.reflectionFresnel = false;
  100094. /**
  100095. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  100096. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  100097. */
  100098. _this.reflectionFalloffDistance = 0.0;
  100099. /**
  100100. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  100101. */
  100102. _this.reflectionAmount = 1.0;
  100103. /**
  100104. * This specifies the weight of the reflection at grazing angle.
  100105. */
  100106. _this.reflectionReflectance0 = 0.05;
  100107. /**
  100108. * This specifies the weight of the reflection at a perpendicular point of view.
  100109. */
  100110. _this.reflectionReflectance90 = 0.5;
  100111. /**
  100112. * Helps to directly use the maps channels instead of their level.
  100113. */
  100114. _this.useRGBColor = true;
  100115. /**
  100116. * This helps reducing the banding effect that could occur on the background.
  100117. */
  100118. _this.enableNoise = false;
  100119. _this._fovMultiplier = 1.0;
  100120. /**
  100121. * Enable the FOV adjustment feature controlled by fovMultiplier.
  100122. */
  100123. _this.useEquirectangularFOV = false;
  100124. _this._maxSimultaneousLights = 4;
  100125. /**
  100126. * Number of Simultaneous lights allowed on the material.
  100127. */
  100128. _this.maxSimultaneousLights = 4;
  100129. /**
  100130. * Keep track of the image processing observer to allow dispose and replace.
  100131. */
  100132. _this._imageProcessingObserver = null;
  100133. /**
  100134. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  100135. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  100136. */
  100137. _this.switchToBGR = false;
  100138. // Temp values kept as cache in the material.
  100139. _this._renderTargets = new BABYLON.SmartArray(16);
  100140. _this._reflectionControls = BABYLON.Vector4.Zero();
  100141. _this._white = BABYLON.Color3.White();
  100142. _this._primaryShadowColor = BABYLON.Color3.Black();
  100143. _this._primaryHighlightColor = BABYLON.Color3.Black();
  100144. // Setup the default processing configuration to the scene.
  100145. _this._attachImageProcessingConfiguration(null);
  100146. _this.getRenderTargetTextures = function () {
  100147. _this._renderTargets.reset();
  100148. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  100149. _this._renderTargets.push(_this._diffuseTexture);
  100150. }
  100151. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  100152. _this._renderTargets.push(_this._reflectionTexture);
  100153. }
  100154. return _this._renderTargets;
  100155. };
  100156. return _this;
  100157. }
  100158. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  100159. /**
  100160. * Experimental Internal Use Only.
  100161. *
  100162. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  100163. * This acts as a helper to set the primary color to a more "human friendly" value.
  100164. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  100165. * output color as close as possible from the chosen value.
  100166. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  100167. * part of lighting setup.)
  100168. */
  100169. get: function () {
  100170. return this.__perceptualColor;
  100171. },
  100172. set: function (value) {
  100173. this.__perceptualColor = value;
  100174. this._computePrimaryColorFromPerceptualColor();
  100175. this._markAllSubMeshesAsLightsDirty();
  100176. },
  100177. enumerable: true,
  100178. configurable: true
  100179. });
  100180. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  100181. /**
  100182. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  100183. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  100184. */
  100185. get: function () {
  100186. return this._primaryColorShadowLevel;
  100187. },
  100188. set: function (value) {
  100189. this._primaryColorShadowLevel = value;
  100190. this._computePrimaryColors();
  100191. this._markAllSubMeshesAsLightsDirty();
  100192. },
  100193. enumerable: true,
  100194. configurable: true
  100195. });
  100196. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  100197. /**
  100198. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  100199. * The primary color is used at the level chosen to define what the white area would look.
  100200. */
  100201. get: function () {
  100202. return this._primaryColorHighlightLevel;
  100203. },
  100204. set: function (value) {
  100205. this._primaryColorHighlightLevel = value;
  100206. this._computePrimaryColors();
  100207. this._markAllSubMeshesAsLightsDirty();
  100208. },
  100209. enumerable: true,
  100210. configurable: true
  100211. });
  100212. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  100213. /**
  100214. * Sets the reflection reflectance fresnel values according to the default standard
  100215. * empirically know to work well :-)
  100216. */
  100217. set: function (value) {
  100218. var reflectionWeight = value;
  100219. if (reflectionWeight < 0.5) {
  100220. reflectionWeight = reflectionWeight * 2.0;
  100221. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  100222. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  100223. }
  100224. else {
  100225. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  100226. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  100227. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  100228. }
  100229. },
  100230. enumerable: true,
  100231. configurable: true
  100232. });
  100233. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  100234. /**
  100235. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100236. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  100237. * Recommended to be keep at 1.0 except for special cases.
  100238. */
  100239. get: function () {
  100240. return this._fovMultiplier;
  100241. },
  100242. set: function (value) {
  100243. if (isNaN(value)) {
  100244. value = 1.0;
  100245. }
  100246. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  100247. },
  100248. enumerable: true,
  100249. configurable: true
  100250. });
  100251. /**
  100252. * Attaches a new image processing configuration to the PBR Material.
  100253. * @param configuration (if null the scene configuration will be use)
  100254. */
  100255. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  100256. var _this = this;
  100257. if (configuration === this._imageProcessingConfiguration) {
  100258. return;
  100259. }
  100260. // Detaches observer.
  100261. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100262. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100263. }
  100264. // Pick the scene configuration if needed.
  100265. if (!configuration) {
  100266. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  100267. }
  100268. else {
  100269. this._imageProcessingConfiguration = configuration;
  100270. }
  100271. // Attaches observer.
  100272. if (this._imageProcessingConfiguration) {
  100273. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  100274. _this._computePrimaryColorFromPerceptualColor();
  100275. _this._markAllSubMeshesAsImageProcessingDirty();
  100276. });
  100277. }
  100278. };
  100279. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  100280. /**
  100281. * Gets the image processing configuration used either in this material.
  100282. */
  100283. get: function () {
  100284. return this._imageProcessingConfiguration;
  100285. },
  100286. /**
  100287. * Sets the Default image processing configuration used either in the this material.
  100288. *
  100289. * If sets to null, the scene one is in use.
  100290. */
  100291. set: function (value) {
  100292. this._attachImageProcessingConfiguration(value);
  100293. // Ensure the effect will be rebuilt.
  100294. this._markAllSubMeshesAsTexturesDirty();
  100295. },
  100296. enumerable: true,
  100297. configurable: true
  100298. });
  100299. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  100300. /**
  100301. * Gets wether the color curves effect is enabled.
  100302. */
  100303. get: function () {
  100304. return this.imageProcessingConfiguration.colorCurvesEnabled;
  100305. },
  100306. /**
  100307. * Sets wether the color curves effect is enabled.
  100308. */
  100309. set: function (value) {
  100310. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  100311. },
  100312. enumerable: true,
  100313. configurable: true
  100314. });
  100315. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  100316. /**
  100317. * Gets wether the color grading effect is enabled.
  100318. */
  100319. get: function () {
  100320. return this.imageProcessingConfiguration.colorGradingEnabled;
  100321. },
  100322. /**
  100323. * Gets wether the color grading effect is enabled.
  100324. */
  100325. set: function (value) {
  100326. this.imageProcessingConfiguration.colorGradingEnabled = value;
  100327. },
  100328. enumerable: true,
  100329. configurable: true
  100330. });
  100331. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  100332. /**
  100333. * Gets wether tonemapping is enabled or not.
  100334. */
  100335. get: function () {
  100336. return this._imageProcessingConfiguration.toneMappingEnabled;
  100337. },
  100338. /**
  100339. * Sets wether tonemapping is enabled or not
  100340. */
  100341. set: function (value) {
  100342. this._imageProcessingConfiguration.toneMappingEnabled = value;
  100343. },
  100344. enumerable: true,
  100345. configurable: true
  100346. });
  100347. ;
  100348. ;
  100349. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  100350. /**
  100351. * The camera exposure used on this material.
  100352. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100353. * This corresponds to a photographic exposure.
  100354. */
  100355. get: function () {
  100356. return this._imageProcessingConfiguration.exposure;
  100357. },
  100358. /**
  100359. * The camera exposure used on this material.
  100360. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100361. * This corresponds to a photographic exposure.
  100362. */
  100363. set: function (value) {
  100364. this._imageProcessingConfiguration.exposure = value;
  100365. },
  100366. enumerable: true,
  100367. configurable: true
  100368. });
  100369. ;
  100370. ;
  100371. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  100372. /**
  100373. * Gets The camera contrast used on this material.
  100374. */
  100375. get: function () {
  100376. return this._imageProcessingConfiguration.contrast;
  100377. },
  100378. /**
  100379. * Sets The camera contrast used on this material.
  100380. */
  100381. set: function (value) {
  100382. this._imageProcessingConfiguration.contrast = value;
  100383. },
  100384. enumerable: true,
  100385. configurable: true
  100386. });
  100387. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  100388. /**
  100389. * Gets the Color Grading 2D Lookup Texture.
  100390. */
  100391. get: function () {
  100392. return this._imageProcessingConfiguration.colorGradingTexture;
  100393. },
  100394. /**
  100395. * Sets the Color Grading 2D Lookup Texture.
  100396. */
  100397. set: function (value) {
  100398. this.imageProcessingConfiguration.colorGradingTexture = value;
  100399. },
  100400. enumerable: true,
  100401. configurable: true
  100402. });
  100403. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  100404. /**
  100405. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100406. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100407. * 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;
  100408. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100409. */
  100410. get: function () {
  100411. return this.imageProcessingConfiguration.colorCurves;
  100412. },
  100413. /**
  100414. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100415. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100416. * 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;
  100417. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100418. */
  100419. set: function (value) {
  100420. this.imageProcessingConfiguration.colorCurves = value;
  100421. },
  100422. enumerable: true,
  100423. configurable: true
  100424. });
  100425. /**
  100426. * The entire material has been created in order to prevent overdraw.
  100427. * @returns false
  100428. */
  100429. BackgroundMaterial.prototype.needAlphaTesting = function () {
  100430. return true;
  100431. };
  100432. /**
  100433. * The entire material has been created in order to prevent overdraw.
  100434. * @returns true if blending is enable
  100435. */
  100436. BackgroundMaterial.prototype.needAlphaBlending = function () {
  100437. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  100438. };
  100439. /**
  100440. * Checks wether the material is ready to be rendered for a given mesh.
  100441. * @param mesh The mesh to render
  100442. * @param subMesh The submesh to check against
  100443. * @param useInstances Specify wether or not the material is used with instances
  100444. * @returns true if all the dependencies are ready (Textures, Effects...)
  100445. */
  100446. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  100447. var _this = this;
  100448. if (useInstances === void 0) { useInstances = false; }
  100449. if (subMesh.effect && this.isFrozen) {
  100450. if (this._wasPreviouslyReady) {
  100451. return true;
  100452. }
  100453. }
  100454. if (!subMesh._materialDefines) {
  100455. subMesh._materialDefines = new BackgroundMaterialDefines();
  100456. }
  100457. var scene = this.getScene();
  100458. var defines = subMesh._materialDefines;
  100459. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  100460. if (defines._renderId === scene.getRenderId()) {
  100461. return true;
  100462. }
  100463. }
  100464. var engine = scene.getEngine();
  100465. // Lights
  100466. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  100467. defines._needNormals = true;
  100468. // Textures
  100469. if (defines._areTexturesDirty) {
  100470. defines._needUVs = false;
  100471. if (scene.texturesEnabled) {
  100472. if (scene.getEngine().getCaps().textureLOD) {
  100473. defines.TEXTURELODSUPPORT = true;
  100474. }
  100475. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100476. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  100477. return false;
  100478. }
  100479. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  100480. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  100481. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  100482. defines.OPACITYFRESNEL = this._opacityFresnel;
  100483. }
  100484. else {
  100485. defines.DIFFUSE = false;
  100486. defines.DIFFUSEHASALPHA = false;
  100487. defines.GAMMADIFFUSE = false;
  100488. defines.OPACITYFRESNEL = false;
  100489. }
  100490. var reflectionTexture = this._reflectionTexture;
  100491. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100492. if (!reflectionTexture.isReadyOrNotBlocking()) {
  100493. return false;
  100494. }
  100495. defines.REFLECTION = true;
  100496. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  100497. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  100498. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  100499. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  100500. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  100501. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  100502. defines.REFLECTIONBGR = this.switchToBGR;
  100503. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  100504. defines.INVERTCUBICMAP = true;
  100505. }
  100506. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  100507. switch (reflectionTexture.coordinatesMode) {
  100508. case BABYLON.Texture.EXPLICIT_MODE:
  100509. defines.REFLECTIONMAP_EXPLICIT = true;
  100510. break;
  100511. case BABYLON.Texture.PLANAR_MODE:
  100512. defines.REFLECTIONMAP_PLANAR = true;
  100513. break;
  100514. case BABYLON.Texture.PROJECTION_MODE:
  100515. defines.REFLECTIONMAP_PROJECTION = true;
  100516. break;
  100517. case BABYLON.Texture.SKYBOX_MODE:
  100518. defines.REFLECTIONMAP_SKYBOX = true;
  100519. break;
  100520. case BABYLON.Texture.SPHERICAL_MODE:
  100521. defines.REFLECTIONMAP_SPHERICAL = true;
  100522. break;
  100523. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  100524. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  100525. break;
  100526. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  100527. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  100528. break;
  100529. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  100530. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  100531. break;
  100532. case BABYLON.Texture.CUBIC_MODE:
  100533. case BABYLON.Texture.INVCUBIC_MODE:
  100534. default:
  100535. defines.REFLECTIONMAP_CUBIC = true;
  100536. break;
  100537. }
  100538. if (this.reflectionFresnel) {
  100539. defines.REFLECTIONFRESNEL = true;
  100540. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  100541. this._reflectionControls.x = this.reflectionAmount;
  100542. this._reflectionControls.y = this.reflectionReflectance0;
  100543. this._reflectionControls.z = this.reflectionReflectance90;
  100544. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  100545. }
  100546. else {
  100547. defines.REFLECTIONFRESNEL = false;
  100548. defines.REFLECTIONFALLOFF = false;
  100549. }
  100550. }
  100551. else {
  100552. defines.REFLECTION = false;
  100553. defines.REFLECTIONFRESNEL = false;
  100554. defines.REFLECTIONFALLOFF = false;
  100555. defines.REFLECTIONBLUR = false;
  100556. defines.REFLECTIONMAP_3D = false;
  100557. defines.REFLECTIONMAP_SPHERICAL = false;
  100558. defines.REFLECTIONMAP_PLANAR = false;
  100559. defines.REFLECTIONMAP_CUBIC = false;
  100560. defines.REFLECTIONMAP_PROJECTION = false;
  100561. defines.REFLECTIONMAP_SKYBOX = false;
  100562. defines.REFLECTIONMAP_EXPLICIT = false;
  100563. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100564. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100565. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100566. defines.INVERTCUBICMAP = false;
  100567. defines.REFLECTIONMAP_OPPOSITEZ = false;
  100568. defines.LODINREFLECTIONALPHA = false;
  100569. defines.GAMMAREFLECTION = false;
  100570. defines.RGBDREFLECTION = false;
  100571. }
  100572. }
  100573. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  100574. defines.USERGBCOLOR = this._useRGBColor;
  100575. defines.NOISE = this._enableNoise;
  100576. }
  100577. if (defines._areLightsDirty) {
  100578. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  100579. }
  100580. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  100581. if (!this._imageProcessingConfiguration.isReady()) {
  100582. return false;
  100583. }
  100584. this._imageProcessingConfiguration.prepareDefines(defines);
  100585. }
  100586. // Misc.
  100587. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  100588. // Values that need to be evaluated on every frame
  100589. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  100590. // Attribs
  100591. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  100592. if (mesh) {
  100593. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100594. mesh.createNormals(true);
  100595. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  100596. }
  100597. }
  100598. }
  100599. // Get correct effect
  100600. if (defines.isDirty) {
  100601. defines.markAsProcessed();
  100602. scene.resetCachedMaterial();
  100603. // Fallbacks
  100604. var fallbacks = new BABYLON.EffectFallbacks();
  100605. if (defines.FOG) {
  100606. fallbacks.addFallback(0, "FOG");
  100607. }
  100608. if (defines.POINTSIZE) {
  100609. fallbacks.addFallback(1, "POINTSIZE");
  100610. }
  100611. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  100612. if (defines.NUM_BONE_INFLUENCERS > 0) {
  100613. fallbacks.addCPUSkinningFallback(0, mesh);
  100614. }
  100615. //Attributes
  100616. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100617. if (defines.NORMAL) {
  100618. attribs.push(BABYLON.VertexBuffer.NormalKind);
  100619. }
  100620. if (defines.UV1) {
  100621. attribs.push(BABYLON.VertexBuffer.UVKind);
  100622. }
  100623. if (defines.UV2) {
  100624. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100625. }
  100626. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  100627. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  100628. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  100629. "vFogInfos", "vFogColor", "pointSize",
  100630. "vClipPlane", "mBones",
  100631. "vPrimaryColor", "vPrimaryColorShadow",
  100632. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  100633. "shadowLevel", "alpha",
  100634. "vBackgroundCenter", "vReflectionControl",
  100635. "vDiffuseInfos", "diffuseMatrix",
  100636. ];
  100637. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  100638. var uniformBuffers = ["Material", "Scene"];
  100639. if (BABYLON.ImageProcessingConfiguration) {
  100640. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  100641. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  100642. }
  100643. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  100644. uniformsNames: uniforms,
  100645. uniformBuffersNames: uniformBuffers,
  100646. samplers: samplers,
  100647. defines: defines,
  100648. maxSimultaneousLights: this._maxSimultaneousLights
  100649. });
  100650. var onCompiled = function (effect) {
  100651. if (_this.onCompiled) {
  100652. _this.onCompiled(effect);
  100653. }
  100654. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  100655. };
  100656. var join = defines.toString();
  100657. subMesh.setEffect(scene.getEngine().createEffect("background", {
  100658. attributes: attribs,
  100659. uniformsNames: uniforms,
  100660. uniformBuffersNames: uniformBuffers,
  100661. samplers: samplers,
  100662. defines: join,
  100663. fallbacks: fallbacks,
  100664. onCompiled: onCompiled,
  100665. onError: this.onError,
  100666. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  100667. }, engine), defines);
  100668. this.buildUniformLayout();
  100669. }
  100670. if (!subMesh.effect || !subMesh.effect.isReady()) {
  100671. return false;
  100672. }
  100673. defines._renderId = scene.getRenderId();
  100674. this._wasPreviouslyReady = true;
  100675. return true;
  100676. };
  100677. /**
  100678. * Compute the primary color according to the chosen perceptual color.
  100679. */
  100680. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  100681. if (!this.__perceptualColor) {
  100682. return;
  100683. }
  100684. this._primaryColor.copyFrom(this.__perceptualColor);
  100685. // Revert gamma space.
  100686. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  100687. // Revert image processing configuration.
  100688. if (this._imageProcessingConfiguration) {
  100689. // Revert Exposure.
  100690. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  100691. }
  100692. this._computePrimaryColors();
  100693. };
  100694. /**
  100695. * Compute the highlights and shadow colors according to their chosen levels.
  100696. */
  100697. BackgroundMaterial.prototype._computePrimaryColors = function () {
  100698. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  100699. return;
  100700. }
  100701. // Find the highlight color based on the configuration.
  100702. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  100703. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  100704. // Find the shadow color based on the configuration.
  100705. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  100706. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  100707. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  100708. };
  100709. /**
  100710. * Build the uniform buffer used in the material.
  100711. */
  100712. BackgroundMaterial.prototype.buildUniformLayout = function () {
  100713. // Order is important !
  100714. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  100715. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  100716. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  100717. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  100718. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  100719. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  100720. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  100721. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  100722. this._uniformBuffer.addUniform("pointSize", 1);
  100723. this._uniformBuffer.addUniform("shadowLevel", 1);
  100724. this._uniformBuffer.addUniform("alpha", 1);
  100725. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  100726. this._uniformBuffer.addUniform("vReflectionControl", 4);
  100727. this._uniformBuffer.create();
  100728. };
  100729. /**
  100730. * Unbind the material.
  100731. */
  100732. BackgroundMaterial.prototype.unbind = function () {
  100733. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  100734. this._uniformBuffer.setTexture("diffuseSampler", null);
  100735. }
  100736. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  100737. this._uniformBuffer.setTexture("reflectionSampler", null);
  100738. }
  100739. _super.prototype.unbind.call(this);
  100740. };
  100741. /**
  100742. * Bind only the world matrix to the material.
  100743. * @param world The world matrix to bind.
  100744. */
  100745. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  100746. this._activeEffect.setMatrix("world", world);
  100747. };
  100748. /**
  100749. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  100750. * @param world The world matrix to bind.
  100751. * @param subMesh The submesh to bind for.
  100752. */
  100753. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  100754. var scene = this.getScene();
  100755. var defines = subMesh._materialDefines;
  100756. if (!defines) {
  100757. return;
  100758. }
  100759. var effect = subMesh.effect;
  100760. if (!effect) {
  100761. return;
  100762. }
  100763. this._activeEffect = effect;
  100764. // Matrices
  100765. this.bindOnlyWorldMatrix(world);
  100766. // Bones
  100767. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  100768. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  100769. if (mustRebind) {
  100770. this._uniformBuffer.bindToEffect(effect, "Material");
  100771. this.bindViewProjection(effect);
  100772. var reflectionTexture = this._reflectionTexture;
  100773. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  100774. // Texture uniforms
  100775. if (scene.texturesEnabled) {
  100776. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100777. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  100778. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  100779. }
  100780. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100781. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  100782. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  100783. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  100784. }
  100785. }
  100786. if (this.shadowLevel > 0) {
  100787. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  100788. }
  100789. this._uniformBuffer.updateFloat("alpha", this.alpha);
  100790. // Point size
  100791. if (this.pointsCloud) {
  100792. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  100793. }
  100794. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  100795. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  100796. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  100797. }
  100798. else {
  100799. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  100800. }
  100801. }
  100802. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  100803. // Textures
  100804. if (scene.texturesEnabled) {
  100805. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100806. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  100807. }
  100808. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100809. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  100810. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100811. }
  100812. else if (!defines.REFLECTIONBLUR) {
  100813. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100814. }
  100815. else {
  100816. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  100817. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  100818. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  100819. }
  100820. if (defines.REFLECTIONFRESNEL) {
  100821. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  100822. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  100823. }
  100824. }
  100825. }
  100826. // Clip plane
  100827. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  100828. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  100829. }
  100830. if (mustRebind || !this.isFrozen) {
  100831. if (scene.lightsEnabled) {
  100832. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  100833. }
  100834. // View
  100835. this.bindView(effect);
  100836. // Fog
  100837. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  100838. // image processing
  100839. if (this._imageProcessingConfiguration) {
  100840. this._imageProcessingConfiguration.bind(this._activeEffect);
  100841. }
  100842. }
  100843. this._uniformBuffer.update();
  100844. this._afterBind(mesh, this._activeEffect);
  100845. };
  100846. /**
  100847. * Dispose the material.
  100848. * @param forceDisposeEffect Force disposal of the associated effect.
  100849. * @param forceDisposeTextures Force disposal of the associated textures.
  100850. */
  100851. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  100852. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  100853. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  100854. if (forceDisposeTextures) {
  100855. if (this.diffuseTexture) {
  100856. this.diffuseTexture.dispose();
  100857. }
  100858. if (this.reflectionTexture) {
  100859. this.reflectionTexture.dispose();
  100860. }
  100861. }
  100862. this._renderTargets.dispose();
  100863. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100864. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100865. }
  100866. _super.prototype.dispose.call(this, forceDisposeEffect);
  100867. };
  100868. /**
  100869. * Clones the material.
  100870. * @param name The cloned name.
  100871. * @returns The cloned material.
  100872. */
  100873. BackgroundMaterial.prototype.clone = function (name) {
  100874. var _this = this;
  100875. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  100876. };
  100877. /**
  100878. * Serializes the current material to its JSON representation.
  100879. * @returns The JSON representation.
  100880. */
  100881. BackgroundMaterial.prototype.serialize = function () {
  100882. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100883. serializationObject.customType = "BABYLON.BackgroundMaterial";
  100884. return serializationObject;
  100885. };
  100886. /**
  100887. * Gets the class name of the material
  100888. * @returns "BackgroundMaterial"
  100889. */
  100890. BackgroundMaterial.prototype.getClassName = function () {
  100891. return "BackgroundMaterial";
  100892. };
  100893. /**
  100894. * Parse a JSON input to create back a background material.
  100895. * @param source The JSON data to parse
  100896. * @param scene The scene to create the parsed material in
  100897. * @param rootUrl The root url of the assets the material depends upon
  100898. * @returns the instantiated BackgroundMaterial.
  100899. */
  100900. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  100901. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  100902. };
  100903. /**
  100904. * Standard reflectance value at parallel view angle.
  100905. */
  100906. BackgroundMaterial.StandardReflectance0 = 0.05;
  100907. /**
  100908. * Standard reflectance value at grazing angle.
  100909. */
  100910. BackgroundMaterial.StandardReflectance90 = 0.5;
  100911. __decorate([
  100912. BABYLON.serializeAsColor3()
  100913. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  100914. __decorate([
  100915. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100916. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  100917. __decorate([
  100918. BABYLON.serializeAsColor3()
  100919. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  100920. __decorate([
  100921. BABYLON.serialize()
  100922. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  100923. __decorate([
  100924. BABYLON.serialize()
  100925. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  100926. __decorate([
  100927. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100928. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  100929. __decorate([
  100930. BABYLON.serializeAsTexture()
  100931. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  100932. __decorate([
  100933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100934. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  100935. __decorate([
  100936. BABYLON.serialize()
  100937. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  100938. __decorate([
  100939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100940. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  100941. __decorate([
  100942. BABYLON.serializeAsTexture()
  100943. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  100944. __decorate([
  100945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100946. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  100947. __decorate([
  100948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100949. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  100950. __decorate([
  100951. BABYLON.serialize()
  100952. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  100953. __decorate([
  100954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100955. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  100956. __decorate([
  100957. BABYLON.serializeAsVector3()
  100958. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  100959. __decorate([
  100960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100961. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  100962. __decorate([
  100963. BABYLON.serialize()
  100964. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  100965. __decorate([
  100966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100967. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  100968. __decorate([
  100969. BABYLON.serialize()
  100970. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  100971. __decorate([
  100972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100973. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  100974. __decorate([
  100975. BABYLON.serialize()
  100976. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  100977. __decorate([
  100978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100979. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  100980. __decorate([
  100981. BABYLON.serialize()
  100982. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  100983. __decorate([
  100984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100985. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  100986. __decorate([
  100987. BABYLON.serialize()
  100988. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  100989. __decorate([
  100990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100991. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  100992. __decorate([
  100993. BABYLON.serialize()
  100994. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  100995. __decorate([
  100996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100997. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  100998. __decorate([
  100999. BABYLON.serialize()
  101000. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  101001. __decorate([
  101002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101003. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  101004. __decorate([
  101005. BABYLON.serialize()
  101006. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  101007. __decorate([
  101008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101009. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  101010. __decorate([
  101011. BABYLON.serialize()
  101012. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  101013. __decorate([
  101014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101015. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  101016. __decorate([
  101017. BABYLON.serializeAsImageProcessingConfiguration()
  101018. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  101019. return BackgroundMaterial;
  101020. }(BABYLON.PushMaterial));
  101021. BABYLON.BackgroundMaterial = BackgroundMaterial;
  101022. })(BABYLON || (BABYLON = {}));
  101023. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  101024. var __assign = (this && this.__assign) || Object.assign || function(t) {
  101025. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101026. s = arguments[i];
  101027. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101028. t[p] = s[p];
  101029. }
  101030. return t;
  101031. };
  101032. var BABYLON;
  101033. (function (BABYLON) {
  101034. /**
  101035. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  101036. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  101037. * It also helps with the default setup of your imageProcessing configuration.
  101038. */
  101039. var EnvironmentHelper = /** @class */ (function () {
  101040. /**
  101041. * constructor
  101042. * @param options
  101043. * @param scene The scene to add the material to
  101044. */
  101045. function EnvironmentHelper(options, scene) {
  101046. var _this = this;
  101047. this._errorHandler = function (message, exception) {
  101048. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  101049. };
  101050. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  101051. this._scene = scene;
  101052. this.onErrorObservable = new BABYLON.Observable();
  101053. this._setupBackground();
  101054. this._setupImageProcessing();
  101055. }
  101056. /**
  101057. * Creates the default options for the helper.
  101058. */
  101059. EnvironmentHelper._getDefaultOptions = function () {
  101060. return {
  101061. createGround: true,
  101062. groundSize: 15,
  101063. groundTexture: this._groundTextureCDNUrl,
  101064. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101065. groundOpacity: 0.9,
  101066. enableGroundShadow: true,
  101067. groundShadowLevel: 0.5,
  101068. enableGroundMirror: false,
  101069. groundMirrorSizeRatio: 0.3,
  101070. groundMirrorBlurKernel: 64,
  101071. groundMirrorAmount: 1,
  101072. groundMirrorFresnelWeight: 1,
  101073. groundMirrorFallOffDistance: 0,
  101074. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  101075. groundYBias: 0.00001,
  101076. createSkybox: true,
  101077. skyboxSize: 20,
  101078. skyboxTexture: this._skyboxTextureCDNUrl,
  101079. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101080. backgroundYRotation: 0,
  101081. sizeAuto: true,
  101082. rootPosition: BABYLON.Vector3.Zero(),
  101083. setupImageProcessing: true,
  101084. environmentTexture: this._environmentTextureCDNUrl,
  101085. cameraExposure: 0.8,
  101086. cameraContrast: 1.2,
  101087. toneMappingEnabled: true,
  101088. };
  101089. };
  101090. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  101091. /**
  101092. * Gets the root mesh created by the helper.
  101093. */
  101094. get: function () {
  101095. return this._rootMesh;
  101096. },
  101097. enumerable: true,
  101098. configurable: true
  101099. });
  101100. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  101101. /**
  101102. * Gets the skybox created by the helper.
  101103. */
  101104. get: function () {
  101105. return this._skybox;
  101106. },
  101107. enumerable: true,
  101108. configurable: true
  101109. });
  101110. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  101111. /**
  101112. * Gets the skybox texture created by the helper.
  101113. */
  101114. get: function () {
  101115. return this._skyboxTexture;
  101116. },
  101117. enumerable: true,
  101118. configurable: true
  101119. });
  101120. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  101121. /**
  101122. * Gets the skybox material created by the helper.
  101123. */
  101124. get: function () {
  101125. return this._skyboxMaterial;
  101126. },
  101127. enumerable: true,
  101128. configurable: true
  101129. });
  101130. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  101131. /**
  101132. * Gets the ground mesh created by the helper.
  101133. */
  101134. get: function () {
  101135. return this._ground;
  101136. },
  101137. enumerable: true,
  101138. configurable: true
  101139. });
  101140. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  101141. /**
  101142. * Gets the ground texture created by the helper.
  101143. */
  101144. get: function () {
  101145. return this._groundTexture;
  101146. },
  101147. enumerable: true,
  101148. configurable: true
  101149. });
  101150. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  101151. /**
  101152. * Gets the ground mirror created by the helper.
  101153. */
  101154. get: function () {
  101155. return this._groundMirror;
  101156. },
  101157. enumerable: true,
  101158. configurable: true
  101159. });
  101160. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  101161. /**
  101162. * Gets the ground mirror render list to helps pushing the meshes
  101163. * you wish in the ground reflection.
  101164. */
  101165. get: function () {
  101166. if (this._groundMirror) {
  101167. return this._groundMirror.renderList;
  101168. }
  101169. return null;
  101170. },
  101171. enumerable: true,
  101172. configurable: true
  101173. });
  101174. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  101175. /**
  101176. * Gets the ground material created by the helper.
  101177. */
  101178. get: function () {
  101179. return this._groundMaterial;
  101180. },
  101181. enumerable: true,
  101182. configurable: true
  101183. });
  101184. /**
  101185. * Updates the background according to the new options
  101186. * @param options
  101187. */
  101188. EnvironmentHelper.prototype.updateOptions = function (options) {
  101189. var newOptions = __assign({}, this._options, options);
  101190. if (this._ground && !newOptions.createGround) {
  101191. this._ground.dispose();
  101192. this._ground = null;
  101193. }
  101194. if (this._groundMaterial && !newOptions.createGround) {
  101195. this._groundMaterial.dispose();
  101196. this._groundMaterial = null;
  101197. }
  101198. if (this._groundTexture) {
  101199. if (this._options.groundTexture != newOptions.groundTexture) {
  101200. this._groundTexture.dispose();
  101201. this._groundTexture = null;
  101202. }
  101203. }
  101204. if (this._skybox && !newOptions.createSkybox) {
  101205. this._skybox.dispose();
  101206. this._skybox = null;
  101207. }
  101208. if (this._skyboxMaterial && !newOptions.createSkybox) {
  101209. this._skyboxMaterial.dispose();
  101210. this._skyboxMaterial = null;
  101211. }
  101212. if (this._skyboxTexture) {
  101213. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  101214. this._skyboxTexture.dispose();
  101215. this._skyboxTexture = null;
  101216. }
  101217. }
  101218. if (this._groundMirror && !newOptions.enableGroundMirror) {
  101219. this._groundMirror.dispose();
  101220. this._groundMirror = null;
  101221. }
  101222. if (this._scene.environmentTexture) {
  101223. if (this._options.environmentTexture != newOptions.environmentTexture) {
  101224. this._scene.environmentTexture.dispose();
  101225. }
  101226. }
  101227. this._options = newOptions;
  101228. this._setupBackground();
  101229. this._setupImageProcessing();
  101230. };
  101231. /**
  101232. * Sets the primary color of all the available elements.
  101233. * @param color the main color to affect to the ground and the background
  101234. */
  101235. EnvironmentHelper.prototype.setMainColor = function (color) {
  101236. if (this.groundMaterial) {
  101237. this.groundMaterial.primaryColor = color;
  101238. }
  101239. if (this.skyboxMaterial) {
  101240. this.skyboxMaterial.primaryColor = color;
  101241. }
  101242. if (this.groundMirror) {
  101243. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  101244. }
  101245. };
  101246. /**
  101247. * Setup the image processing according to the specified options.
  101248. */
  101249. EnvironmentHelper.prototype._setupImageProcessing = function () {
  101250. if (this._options.setupImageProcessing) {
  101251. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  101252. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  101253. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  101254. this._setupEnvironmentTexture();
  101255. }
  101256. };
  101257. /**
  101258. * Setup the environment texture according to the specified options.
  101259. */
  101260. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  101261. if (this._scene.environmentTexture) {
  101262. return;
  101263. }
  101264. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  101265. this._scene.environmentTexture = this._options.environmentTexture;
  101266. return;
  101267. }
  101268. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  101269. this._scene.environmentTexture = environmentTexture;
  101270. };
  101271. /**
  101272. * Setup the background according to the specified options.
  101273. */
  101274. EnvironmentHelper.prototype._setupBackground = function () {
  101275. if (!this._rootMesh) {
  101276. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  101277. }
  101278. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  101279. var sceneSize = this._getSceneSize();
  101280. if (this._options.createGround) {
  101281. this._setupGround(sceneSize);
  101282. this._setupGroundMaterial();
  101283. this._setupGroundDiffuseTexture();
  101284. if (this._options.enableGroundMirror) {
  101285. this._setupGroundMirrorTexture(sceneSize);
  101286. }
  101287. this._setupMirrorInGroundMaterial();
  101288. }
  101289. if (this._options.createSkybox) {
  101290. this._setupSkybox(sceneSize);
  101291. this._setupSkyboxMaterial();
  101292. this._setupSkyboxReflectionTexture();
  101293. }
  101294. this._rootMesh.position.x = sceneSize.rootPosition.x;
  101295. this._rootMesh.position.z = sceneSize.rootPosition.z;
  101296. this._rootMesh.position.y = sceneSize.rootPosition.y;
  101297. };
  101298. /**
  101299. * Get the scene sizes according to the setup.
  101300. */
  101301. EnvironmentHelper.prototype._getSceneSize = function () {
  101302. var _this = this;
  101303. var groundSize = this._options.groundSize;
  101304. var skyboxSize = this._options.skyboxSize;
  101305. var rootPosition = this._options.rootPosition;
  101306. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  101307. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101308. }
  101309. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  101310. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  101311. });
  101312. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  101313. if (this._options.sizeAuto) {
  101314. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  101315. this._scene.activeCamera.upperRadiusLimit) {
  101316. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  101317. skyboxSize = groundSize;
  101318. }
  101319. var sceneDiagonalLenght = sceneDiagonal.length();
  101320. if (sceneDiagonalLenght > groundSize) {
  101321. groundSize = sceneDiagonalLenght * 2;
  101322. skyboxSize = groundSize;
  101323. }
  101324. // 10 % bigger.
  101325. groundSize *= 1.1;
  101326. skyboxSize *= 1.5;
  101327. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  101328. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  101329. }
  101330. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101331. };
  101332. /**
  101333. * Setup the ground according to the specified options.
  101334. */
  101335. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  101336. var _this = this;
  101337. if (!this._ground || this._ground.isDisposed()) {
  101338. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  101339. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  101340. this._ground.parent = this._rootMesh;
  101341. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  101342. }
  101343. this._ground.receiveShadows = this._options.enableGroundShadow;
  101344. };
  101345. /**
  101346. * Setup the ground material according to the specified options.
  101347. */
  101348. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  101349. if (!this._groundMaterial) {
  101350. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  101351. }
  101352. this._groundMaterial.alpha = this._options.groundOpacity;
  101353. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  101354. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  101355. this._groundMaterial.primaryColor = this._options.groundColor;
  101356. this._groundMaterial.useRGBColor = false;
  101357. this._groundMaterial.enableNoise = true;
  101358. if (this._ground) {
  101359. this._ground.material = this._groundMaterial;
  101360. }
  101361. };
  101362. /**
  101363. * Setup the ground diffuse texture according to the specified options.
  101364. */
  101365. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  101366. if (!this._groundMaterial) {
  101367. return;
  101368. }
  101369. if (this._groundTexture) {
  101370. return;
  101371. }
  101372. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  101373. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  101374. return;
  101375. }
  101376. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101377. diffuseTexture.gammaSpace = false;
  101378. diffuseTexture.hasAlpha = true;
  101379. this._groundMaterial.diffuseTexture = diffuseTexture;
  101380. };
  101381. /**
  101382. * Setup the ground mirror texture according to the specified options.
  101383. */
  101384. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  101385. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101386. if (!this._groundMirror) {
  101387. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  101388. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  101389. this._groundMirror.anisotropicFilteringLevel = 1;
  101390. this._groundMirror.wrapU = wrapping;
  101391. this._groundMirror.wrapV = wrapping;
  101392. this._groundMirror.gammaSpace = false;
  101393. if (this._groundMirror.renderList) {
  101394. for (var i = 0; i < this._scene.meshes.length; i++) {
  101395. var mesh = this._scene.meshes[i];
  101396. if (mesh !== this._ground &&
  101397. mesh !== this._skybox &&
  101398. mesh !== this._rootMesh) {
  101399. this._groundMirror.renderList.push(mesh);
  101400. }
  101401. }
  101402. }
  101403. }
  101404. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  101405. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  101406. };
  101407. /**
  101408. * Setup the ground to receive the mirror texture.
  101409. */
  101410. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  101411. if (this._groundMaterial) {
  101412. this._groundMaterial.reflectionTexture = this._groundMirror;
  101413. this._groundMaterial.reflectionFresnel = true;
  101414. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  101415. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  101416. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  101417. }
  101418. };
  101419. /**
  101420. * Setup the skybox according to the specified options.
  101421. */
  101422. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  101423. var _this = this;
  101424. if (!this._skybox || this._skybox.isDisposed()) {
  101425. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  101426. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  101427. }
  101428. this._skybox.parent = this._rootMesh;
  101429. };
  101430. /**
  101431. * Setup the skybox material according to the specified options.
  101432. */
  101433. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  101434. if (!this._skybox) {
  101435. return;
  101436. }
  101437. if (!this._skyboxMaterial) {
  101438. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  101439. }
  101440. this._skyboxMaterial.useRGBColor = false;
  101441. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  101442. this._skyboxMaterial.enableNoise = true;
  101443. this._skybox.material = this._skyboxMaterial;
  101444. };
  101445. /**
  101446. * Setup the skybox reflection texture according to the specified options.
  101447. */
  101448. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  101449. if (!this._skyboxMaterial) {
  101450. return;
  101451. }
  101452. if (this._skyboxTexture) {
  101453. return;
  101454. }
  101455. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  101456. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  101457. return;
  101458. }
  101459. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101460. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  101461. this._skyboxTexture.gammaSpace = false;
  101462. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  101463. };
  101464. /**
  101465. * Dispose all the elements created by the Helper.
  101466. */
  101467. EnvironmentHelper.prototype.dispose = function () {
  101468. if (this._groundMaterial) {
  101469. this._groundMaterial.dispose(true, true);
  101470. }
  101471. if (this._skyboxMaterial) {
  101472. this._skyboxMaterial.dispose(true, true);
  101473. }
  101474. this._rootMesh.dispose(false);
  101475. };
  101476. /**
  101477. * Default ground texture URL.
  101478. */
  101479. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  101480. /**
  101481. * Default skybox texture URL.
  101482. */
  101483. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  101484. /**
  101485. * Default environment texture URL.
  101486. */
  101487. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  101488. return EnvironmentHelper;
  101489. }());
  101490. BABYLON.EnvironmentHelper = EnvironmentHelper;
  101491. })(BABYLON || (BABYLON = {}));
  101492. //# sourceMappingURL=babylon.environmentHelper.js.map
  101493. var BABYLON;
  101494. (function (BABYLON) {
  101495. /**
  101496. * This class is made for on one-liner static method to help creating particle systems.
  101497. */
  101498. var ParticleHelper = /** @class */ (function () {
  101499. function ParticleHelper() {
  101500. }
  101501. /**
  101502. * This is the main static method (one-liner) of this helper to create different particle systems.
  101503. * @param type This string represents the type to the particle system to create
  101504. * @param emitter The object where the particle system will start to emit from.
  101505. * @param scene The scene where the particle system should live.
  101506. * @param gpu If the system will use gpu.
  101507. * @returns the ParticleSystem created.
  101508. */
  101509. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  101510. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  101511. if (gpu === void 0) { gpu = false; }
  101512. return new Promise(function (resolve, reject) {
  101513. if (!scene) {
  101514. scene = BABYLON.Engine.LastCreatedScene;
  101515. ;
  101516. }
  101517. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  101518. return reject("Particle system with GPU is not supported.");
  101519. }
  101520. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  101521. var newData = JSON.parse(data.toString());
  101522. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  101523. }, undefined, undefined, undefined, function (req, exception) {
  101524. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  101525. });
  101526. });
  101527. };
  101528. /**
  101529. * Static function used to create a new particle system from a IParticleSystemData
  101530. * @param data defines the source data
  101531. * @param scene defines the hosting scene
  101532. * @param emitter defines the particle emitter
  101533. * @returns a new ParticleSystem based on referenced data
  101534. */
  101535. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  101536. // Create a particle system
  101537. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  101538. // Where the particles come from
  101539. system.emitter = emitter; // the starting object, the emitter
  101540. ParticleHelper.UpdateSystem(system, data, scene);
  101541. return system;
  101542. };
  101543. /**
  101544. * Static function used to update a particle system from a IParticleSystemData
  101545. * @param system defines the particle system to update
  101546. * @param data defines the source data
  101547. * @param scene defines the hosting scene
  101548. */
  101549. ParticleHelper.UpdateSystem = function (system, data, scene) {
  101550. // Texture of each particle
  101551. if (data.textureFile) {
  101552. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  101553. }
  101554. // Colors of all particles
  101555. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  101556. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  101557. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  101558. // Size of each particle (random between...
  101559. system.minSize = data.minSize;
  101560. system.maxSize = data.maxSize;
  101561. system.minScaleX = data.minScaleX;
  101562. system.maxScaleX = data.maxScaleX;
  101563. system.minScaleY = data.minScaleY;
  101564. system.maxScaleY = data.maxScaleY;
  101565. // Life time of each particle (random between...
  101566. system.minLifeTime = data.minLifeTime;
  101567. system.maxLifeTime = data.maxLifeTime;
  101568. // Emission rate
  101569. system.emitRate = data.emitRate;
  101570. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101571. system.blendMode = data.blendMode;
  101572. // Set the gravity of all particles
  101573. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  101574. // Angular speed, in radians
  101575. system.minAngularSpeed = data.minAngularSpeed;
  101576. system.maxAngularSpeed = data.maxAngularSpeed;
  101577. // Speed
  101578. system.minEmitPower = data.minEmitPower;
  101579. system.maxEmitPower = data.maxEmitPower;
  101580. system.updateSpeed = data.updateSpeed;
  101581. switch (data.emitterType) {
  101582. case "box":
  101583. if (!data.direction1 || !data.direction2) {
  101584. throw new Error("Directions are missing in this particle system.");
  101585. }
  101586. if (!data.minEmitBox || !data.maxEmitBox) {
  101587. throw new Error("EmitBox is missing in this particle system.");
  101588. }
  101589. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  101590. break;
  101591. case "sphere":
  101592. system.createSphereEmitter(data.radius);
  101593. break;
  101594. case "directed_sphere":
  101595. if (!data.direction1 || !data.direction2) {
  101596. throw new Error("Directions are missing in this particle system.");
  101597. }
  101598. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  101599. break;
  101600. case "cone":
  101601. system.createConeEmitter(data.radius, data.angle);
  101602. break;
  101603. default:
  101604. break;
  101605. }
  101606. };
  101607. /**
  101608. * Static function used to export a particle system to a IParticleSystemData variable.
  101609. * Please note that texture file name is not exported and must be added manually
  101610. * @param system defines the particle system to export
  101611. */
  101612. ParticleHelper.ExportSystem = function (system) {
  101613. var outData = {};
  101614. // Colors of all particles
  101615. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  101616. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  101617. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  101618. // Size of each particle (random between...
  101619. outData.minSize = system.minSize;
  101620. outData.maxSize = system.maxSize;
  101621. outData.minScaleX = system.minScaleX;
  101622. outData.maxScaleX = system.maxScaleX;
  101623. outData.minScaleY = system.minScaleY;
  101624. outData.maxScaleY = system.maxScaleY;
  101625. // Life time of each particle (random between...
  101626. outData.minLifeTime = system.minLifeTime;
  101627. outData.maxLifeTime = system.maxLifeTime;
  101628. // Emission rate
  101629. outData.emitRate = system.emitRate;
  101630. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101631. outData.blendMode = system.blendMode;
  101632. // Set the gravity of all particles
  101633. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  101634. // Angular speed, in radians
  101635. outData.minAngularSpeed = system.minAngularSpeed;
  101636. outData.maxAngularSpeed = system.maxAngularSpeed;
  101637. // Speed
  101638. outData.minEmitPower = system.minEmitPower;
  101639. outData.maxEmitPower = system.maxEmitPower;
  101640. outData.updateSpeed = system.updateSpeed;
  101641. switch (system.particleEmitterType.getClassName()) {
  101642. case "BoxEmitter":
  101643. outData.emitterType = "box";
  101644. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  101645. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  101646. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  101647. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  101648. break;
  101649. case "SphereParticleEmitter":
  101650. outData.emitterType = "sphere";
  101651. outData.radius = system.particleEmitterType.radius;
  101652. break;
  101653. case "SphereDirectedParticleEmitter":
  101654. outData.emitterType = "directed_sphere";
  101655. var sphereDirectedParticleEmitter = system.particleEmitterType;
  101656. outData.radius = sphereDirectedParticleEmitter.radius;
  101657. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  101658. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  101659. break;
  101660. case "ConeEmitter":
  101661. outData.emitterType = "cone";
  101662. outData.radius = system.particleEmitterType.radius;
  101663. outData.angle = system.particleEmitterType.angle;
  101664. break;
  101665. default:
  101666. break;
  101667. }
  101668. return outData;
  101669. };
  101670. /**
  101671. * Base Assets URL.
  101672. */
  101673. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  101674. return ParticleHelper;
  101675. }());
  101676. BABYLON.ParticleHelper = ParticleHelper;
  101677. })(BABYLON || (BABYLON = {}));
  101678. //# sourceMappingURL=babylon.particleHelper.js.map
  101679. var BABYLON;
  101680. (function (BABYLON) {
  101681. /**
  101682. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  101683. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  101684. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  101685. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101686. */
  101687. var VideoDome = /** @class */ (function (_super) {
  101688. __extends(VideoDome, _super);
  101689. /**
  101690. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  101691. * @param name Element's name, child elements will append suffixes for their own names.
  101692. * @param urlsOrVideo defines the url(s) or the video element to use
  101693. * @param options An object containing optional or exposed sub element properties
  101694. */
  101695. function VideoDome(name, urlsOrVideo, options, scene) {
  101696. var _this = _super.call(this, name, scene) || this;
  101697. _this._useDirectMapping = false;
  101698. // set defaults and manage values
  101699. name = name || "videoDome";
  101700. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101701. options.clickToPlay = Boolean(options.clickToPlay);
  101702. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  101703. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  101704. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101705. if (options.useDirectMapping === undefined) {
  101706. _this._useDirectMapping = true;
  101707. }
  101708. else {
  101709. _this._useDirectMapping = options.useDirectMapping;
  101710. }
  101711. // create
  101712. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  101713. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101714. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  101715. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101716. // configure material
  101717. material.useEquirectangularFOV = true;
  101718. material.fovMultiplier = 1.0;
  101719. material.opacityFresnel = false;
  101720. if (_this._useDirectMapping) {
  101721. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101722. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101723. material.diffuseTexture = texture;
  101724. }
  101725. else {
  101726. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101727. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101728. material.reflectionTexture = texture;
  101729. }
  101730. // configure mesh
  101731. _this._mesh.material = material;
  101732. _this._mesh.parent = _this;
  101733. // optional configuration
  101734. if (options.clickToPlay) {
  101735. scene.onPointerUp = function () {
  101736. _this._videoTexture.video.play();
  101737. };
  101738. }
  101739. return _this;
  101740. }
  101741. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  101742. /**
  101743. * Gets the video texture being displayed on the sphere
  101744. */
  101745. get: function () {
  101746. return this._videoTexture;
  101747. },
  101748. enumerable: true,
  101749. configurable: true
  101750. });
  101751. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  101752. /**
  101753. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101754. * Also see the options.resolution property.
  101755. */
  101756. get: function () {
  101757. return this._material.fovMultiplier;
  101758. },
  101759. set: function (value) {
  101760. this._material.fovMultiplier = value;
  101761. },
  101762. enumerable: true,
  101763. configurable: true
  101764. });
  101765. /**
  101766. * Releases resources associated with this node.
  101767. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101768. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101769. */
  101770. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101771. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101772. this._videoTexture.dispose();
  101773. this._mesh.dispose();
  101774. this._material.dispose();
  101775. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101776. };
  101777. return VideoDome;
  101778. }(BABYLON.Node));
  101779. BABYLON.VideoDome = VideoDome;
  101780. })(BABYLON || (BABYLON = {}));
  101781. //# sourceMappingURL=babylon.videoDome.js.map
  101782. var BABYLON;
  101783. (function (BABYLON) {
  101784. /**
  101785. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  101786. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  101787. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  101788. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101789. */
  101790. var PhotoDome = /** @class */ (function (_super) {
  101791. __extends(PhotoDome, _super);
  101792. /**
  101793. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  101794. * @param name Element's name, child elements will append suffixes for their own names.
  101795. * @param urlsOfPhoto define the url of the photo to display
  101796. * @param options An object containing optional or exposed sub element properties
  101797. */
  101798. function PhotoDome(name, urlOfPhoto, options, scene) {
  101799. var _this = _super.call(this, name, scene) || this;
  101800. _this._useDirectMapping = false;
  101801. // set defaults and manage values
  101802. name = name || "photoDome";
  101803. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101804. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101805. if (options.useDirectMapping === undefined) {
  101806. _this._useDirectMapping = true;
  101807. }
  101808. else {
  101809. _this._useDirectMapping = options.useDirectMapping;
  101810. }
  101811. // create
  101812. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101813. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101814. // configure material
  101815. material.opacityFresnel = false;
  101816. material.useEquirectangularFOV = true;
  101817. material.fovMultiplier = 1.0;
  101818. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  101819. // configure mesh
  101820. _this._mesh.material = material;
  101821. _this._mesh.parent = _this;
  101822. return _this;
  101823. }
  101824. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  101825. /**
  101826. * Gets or sets the texture being displayed on the sphere
  101827. */
  101828. get: function () {
  101829. return this._photoTexture;
  101830. },
  101831. set: function (value) {
  101832. if (this._photoTexture === value) {
  101833. return;
  101834. }
  101835. this._photoTexture = value;
  101836. if (this._useDirectMapping) {
  101837. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101838. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101839. this._material.diffuseTexture = this._photoTexture;
  101840. }
  101841. else {
  101842. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101843. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101844. this._material.reflectionTexture = this._photoTexture;
  101845. }
  101846. },
  101847. enumerable: true,
  101848. configurable: true
  101849. });
  101850. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  101851. /**
  101852. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101853. * Also see the options.resolution property.
  101854. */
  101855. get: function () {
  101856. return this._material.fovMultiplier;
  101857. },
  101858. set: function (value) {
  101859. this._material.fovMultiplier = value;
  101860. },
  101861. enumerable: true,
  101862. configurable: true
  101863. });
  101864. /**
  101865. * Releases resources associated with this node.
  101866. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101867. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101868. */
  101869. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101870. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101871. this._photoTexture.dispose();
  101872. this._mesh.dispose();
  101873. this._material.dispose();
  101874. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101875. };
  101876. return PhotoDome;
  101877. }(BABYLON.Node));
  101878. BABYLON.PhotoDome = PhotoDome;
  101879. })(BABYLON || (BABYLON = {}));
  101880. //# sourceMappingURL=babylon.photoDome.js.map
  101881. 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;\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\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n#ifdef BILLBOARD \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.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \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 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;\nvec3 worldPos=position+alignedCorner; \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;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\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\nvoid main() {\nvUV=uv;\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*size.yz*size.x;\n#ifdef BILLBOARD\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\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;\n\nvec4 viewPosition=view*vec4(position+alignedCorner,1.0); \ngl_Position=projection*viewPosition;\n#endif\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 float radius;\nuniform float coneAngle;\nuniform float 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\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifdef SIZEGRADIENTS\nout vec3 outInitialSize;\n#endif\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\nin vec3 initialSize;\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;\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\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifdef SIZEGRADIENTS\noutInitialSize=outSize;\n#endif \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\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;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(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(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutInitialSize=initialSize;\noutSize=initialSize*texture(sizeGradientSampler,vec2(age/life,0)).r;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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"};
  101882. 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};"};
  101883. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  101884. globalObject["BABYLON"] = BABYLON;
  101885. //backwards compatibility
  101886. if(typeof earcut !== 'undefined') {
  101887. globalObject["Earcut"] = {
  101888. earcut: earcut
  101889. };
  101890. }
  101891. return BABYLON;
  101892. });
  101893. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)))
  101894. /***/ }),
  101895. /* 1 */
  101896. /***/ (function(module, exports, __webpack_require__) {
  101897. "use strict";
  101898. Object.defineProperty(exports, "__esModule", { value: true });
  101899. var deepmerge = __webpack_require__(21);
  101900. var expDm = deepmerge['default'];
  101901. exports.deepmerge = expDm;
  101902. /**
  101903. * Is the provided string a URL?
  101904. *
  101905. * @param urlToCheck the url to inspect
  101906. */
  101907. function isUrl(urlToCheck) {
  101908. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  101909. return true;
  101910. }
  101911. return false;
  101912. }
  101913. exports.isUrl = isUrl;
  101914. /**
  101915. * Convert a string from kebab-case to camelCase
  101916. * @param s string to convert
  101917. */
  101918. function kebabToCamel(s) {
  101919. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  101920. }
  101921. exports.kebabToCamel = kebabToCamel;
  101922. //https://gist.github.com/youssman/745578062609e8acac9f
  101923. /**
  101924. * Convert a string from camelCase to kebab-case
  101925. * @param str string to convert
  101926. */
  101927. function camelToKebab(str) {
  101928. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  101929. }
  101930. exports.camelToKebab = camelToKebab;
  101931. /**
  101932. * This will extend an object with configuration values.
  101933. * What it practically does it take the keys from the configuration and set them on the object.
  101934. * I the configuration is a tree, it will traverse into the tree.
  101935. * @param object the object to extend
  101936. * @param config the configuration object that will extend the object
  101937. */
  101938. function extendClassWithConfig(object, config) {
  101939. if (!config)
  101940. return;
  101941. Object.keys(config).forEach(function (key) {
  101942. if (key in object && typeof object[key] !== 'function') {
  101943. // if (typeof object[key] === 'function') return;
  101944. // if it is an object, iterate internally until reaching basic types
  101945. if (typeof object[key] === 'object') {
  101946. extendClassWithConfig(object[key], config[key]);
  101947. }
  101948. else {
  101949. if (config[key] !== undefined) {
  101950. object[key] = config[key];
  101951. }
  101952. }
  101953. }
  101954. });
  101955. }
  101956. exports.extendClassWithConfig = extendClassWithConfig;
  101957. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQVMsQ0FBQyxTQUFTLENBQUMsQ0FBQztBQUNmLDBCQUFTO0FBRTNCOzs7O0dBSUc7QUFDSCxlQUFzQixVQUFrQjtJQUNwQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsS0FBSyxDQUFDLEtBQUssQ0FBQyxFQUFFO1FBQ3hJLE9BQU8sSUFBSSxDQUFDO0tBQ2Y7SUFDRCxPQUFPLEtBQUssQ0FBQztBQUNqQixDQUFDO0FBTEQsc0JBS0M7QUFFRDs7O0dBR0c7QUFDSCxzQkFBNkIsQ0FBQztJQUMxQixPQUFPLENBQUMsQ0FBQyxPQUFPLENBQUMsU0FBUyxFQUFFLFVBQVUsQ0FBQyxJQUFJLE9BQU8sQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLFdBQVcsRUFB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DTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  101958. /***/ }),
  101959. /* 2 */
  101960. /***/ (function(module, exports, __webpack_require__) {
  101961. "use strict";
  101962. function __export(m) {
  101963. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  101964. }
  101965. Object.defineProperty(exports, "__esModule", { value: true });
  101966. __export(__webpack_require__(31));
  101967. __export(__webpack_require__(33));
  101968. __export(__webpack_require__(39));
  101969. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  101970. /***/ }),
  101971. /* 3 */
  101972. /***/ (function(module, exports, __webpack_require__) {
  101973. "use strict";
  101974. Object.defineProperty(exports, "__esModule", { value: true });
  101975. var babylonjs_1 = __webpack_require__(0);
  101976. var _1 = __webpack_require__(1);
  101977. /**
  101978. * This is a simple HTML mapper.
  101979. * This mapper parses a single HTML element and returns the configuration from its attributes.
  101980. * it parses numbers and boolean values to the corresponding variable types.
  101981. * The following HTML element:
  101982. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  101983. *
  101984. * {
  101985. * test: 1, //a number!
  101986. * randomFlag: boolean, //camelCase and boolean
  101987. * a: {
  101988. * string: {
  101989. * object: "test" //dot-separated object levels
  101990. * }
  101991. * }
  101992. * }
  101993. */
  101994. var HTMLMapper = /** @class */ (function () {
  101995. function HTMLMapper() {
  101996. }
  101997. /**
  101998. * Map a specific element and get configuration from it
  101999. * @param element the HTML element to analyze.
  102000. */
  102001. HTMLMapper.prototype.map = function (element) {
  102002. var config = {};
  102003. var _loop_1 = function (attrIdx) {
  102004. var attr = element.attributes.item(attrIdx);
  102005. if (!attr) {
  102006. return "continue";
  102007. }
  102008. // map "object.property" to the right configuration place.
  102009. var split = attr.nodeName.split('.');
  102010. split.reduce(function (currentConfig, key, idx) {
  102011. //convert html-style to json-style
  102012. var camelKey = _1.kebabToCamel(key);
  102013. if (idx === split.length - 1) {
  102014. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  102015. if (val === "true") {
  102016. val = true;
  102017. }
  102018. else if (val === "false") {
  102019. val = false;
  102020. }
  102021. else {
  102022. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  102023. if (isnum) {
  102024. var number = parseFloat(val);
  102025. if (!isNaN(number)) {
  102026. val = number;
  102027. }
  102028. }
  102029. }
  102030. currentConfig[camelKey] = val;
  102031. }
  102032. else {
  102033. currentConfig[camelKey] = currentConfig[camelKey] || {};
  102034. }
  102035. return currentConfig[camelKey];
  102036. }, config);
  102037. };
  102038. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  102039. _loop_1(attrIdx);
  102040. }
  102041. return config;
  102042. };
  102043. return HTMLMapper;
  102044. }());
  102045. /**
  102046. * A simple string-to-JSON mapper.
  102047. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  102048. */
  102049. var JSONMapper = /** @class */ (function () {
  102050. function JSONMapper() {
  102051. }
  102052. JSONMapper.prototype.map = function (rawSource) {
  102053. return JSON.parse(rawSource);
  102054. };
  102055. return JSONMapper;
  102056. }());
  102057. /**
  102058. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  102059. * DOM elements and attributes.
  102060. */
  102061. var DOMMapper = /** @class */ (function () {
  102062. function DOMMapper() {
  102063. }
  102064. /**
  102065. * The mapping function that will convert HTML data to a viewer configuration object
  102066. * @param baseElement the baseElement from which to start traversing
  102067. * @returns a ViewerCOnfiguration object from the provided HTML Element
  102068. */
  102069. DOMMapper.prototype.map = function (baseElement) {
  102070. var htmlMapper = new HTMLMapper();
  102071. var config = htmlMapper.map(baseElement);
  102072. var traverseChildren = function (element, partConfig) {
  102073. var children = element.children;
  102074. if (children.length) {
  102075. for (var i = 0; i < children.length; ++i) {
  102076. var item = children.item(i);
  102077. // use the HTML Mapper to read configuration from a single element
  102078. var configMapped = htmlMapper.map(item);
  102079. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  102080. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  102081. partConfig[key] = [];
  102082. }
  102083. else {
  102084. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  102085. partConfig.push(configMapped);
  102086. }
  102087. else if (partConfig[key]) {
  102088. //exists already! probably an array
  102089. element.setAttribute('array', 'true');
  102090. var oldItem = partConfig[key];
  102091. partConfig = [oldItem, configMapped];
  102092. }
  102093. else {
  102094. partConfig[key] = configMapped;
  102095. }
  102096. }
  102097. traverseChildren(item, partConfig[key] || configMapped);
  102098. }
  102099. }
  102100. return partConfig;
  102101. };
  102102. traverseChildren(baseElement, config);
  102103. return config;
  102104. };
  102105. return DOMMapper;
  102106. }());
  102107. /**
  102108. * The MapperManager manages the different implemented mappers.
  102109. * It allows the user to register new mappers as well and use them to parse their own configuration data
  102110. */
  102111. var MapperManager = /** @class */ (function () {
  102112. function MapperManager() {
  102113. this._mappers = {
  102114. "html": new HTMLMapper(),
  102115. "json": new JSONMapper(),
  102116. "dom": new DOMMapper()
  102117. };
  102118. }
  102119. /**
  102120. * Get a specific configuration mapper.
  102121. *
  102122. * @param type the name of the mapper to load
  102123. */
  102124. MapperManager.prototype.getMapper = function (type) {
  102125. if (!this._mappers[type]) {
  102126. babylonjs_1.Tools.Error("No mapper defined for " + type);
  102127. }
  102128. return this._mappers[type];
  102129. };
  102130. /**
  102131. * Use this functio to register your own configuration mapper.
  102132. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  102133. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  102134. * @param mapper The implemented mapper
  102135. */
  102136. MapperManager.prototype.registerMapper = function (type, mapper) {
  102137. this._mappers[type] = mapper;
  102138. };
  102139. /**
  102140. * Dispose the mapper manager and all of its mappers.
  102141. */
  102142. MapperManager.prototype.dispose = function () {
  102143. this._mappers = {};
  102144. };
  102145. /**
  102146. * The default mapper is the JSON mapper.
  102147. */
  102148. MapperManager.DefaultMapper = 'json';
  102149. return MapperManager;
  102150. }());
  102151. exports.MapperManager = MapperManager;
  102152. /**
  102153. * mapperManager is a singleton of the type MapperManager.
  102154. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  102155. * or indirectly with using BabylonViewer.disposeAll()
  102156. */
  102157. exports.mapperManager = new MapperManager();
  102158. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBa0M7QUFHbEMsK0JBQTBDO0FBUzFDOzs7Ozs7Ozs7Ozs7Ozs7O0dBZ0JHO0FBQ0g7SUFBQTtJQTRDQSxDQUFDO0lBMUNHOzs7T0FHRztJQUNILHdCQUFHLEdBQUgsVUFBSSxPQUFvQjtRQUVwQixJQUFJLE1BQU0sR0FBRyxFQUFFLENBQUM7Z0NBQ1AsT0FBTztZQUNaLElBQUksSUFBSSxHQUFHLE9BQU8sQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDO1lBQzVDLElBQUksQ0FBQyxJQUFJLEVBQUU7O2FBRVY7WUFDRCwwREFBMEQ7WUFDMUQsSUFBSSxLQUFLLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckMsS0FBSyxDQUFDLE1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QUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0=
  102159. /***/ }),
  102160. /* 4 */
  102161. /***/ (function(module, exports, __webpack_require__) {
  102162. "use strict";
  102163. Object.defineProperty(exports, "__esModule", { value: true });
  102164. var babylonjs_1 = __webpack_require__(0);
  102165. var ViewerGlobals = /** @class */ (function () {
  102166. function ViewerGlobals() {
  102167. this.disableInit = false;
  102168. this.disableWebGL2Support = false;
  102169. }
  102170. Object.defineProperty(ViewerGlobals.prototype, "version", {
  102171. get: function () {
  102172. return babylonjs_1.Engine.Version;
  102173. },
  102174. enumerable: true,
  102175. configurable: true
  102176. });
  102177. return ViewerGlobals;
  102178. }());
  102179. exports.ViewerGlobals = ViewerGlobals;
  102180. exports.viewerGlobals = new ViewerGlobals();
  102181. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  102182. /***/ }),
  102183. /* 5 */
  102184. /***/ (function(module, exports, __webpack_require__) {
  102185. "use strict";
  102186. Object.defineProperty(exports, "__esModule", { value: true });
  102187. var babylonjs_1 = __webpack_require__(0);
  102188. var modelAnimation_1 = __webpack_require__(23);
  102189. var _1 = __webpack_require__(1);
  102190. /**
  102191. * The current state of the model
  102192. */
  102193. var ModelState;
  102194. (function (ModelState) {
  102195. ModelState[ModelState["INIT"] = 0] = "INIT";
  102196. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  102197. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  102198. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  102199. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  102200. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  102201. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  102202. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  102203. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  102204. /**
  102205. * The viewer model is a container for all assets representing a sngle loaded model.
  102206. */
  102207. var ViewerModel = /** @class */ (function () {
  102208. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  102209. var _this = this;
  102210. this._observablesManager = _observablesManager;
  102211. this._configurationContainer = _configurationContainer;
  102212. /**
  102213. * the list of meshes that are a part of this model
  102214. */
  102215. this._meshes = [];
  102216. /**
  102217. * ParticleSystems connected to this model
  102218. */
  102219. this.particleSystems = [];
  102220. /**
  102221. * Skeletons defined in this model
  102222. */
  102223. this.skeletons = [];
  102224. this._loaderDone = false;
  102225. this._animatables = [];
  102226. this._frameRate = 60;
  102227. this._shadowsRenderedAfterLoad = false;
  102228. this.onLoadedObservable = new babylonjs_1.Observable();
  102229. this.onLoadErrorObservable = new babylonjs_1.Observable();
  102230. this.onLoadProgressObservable = new babylonjs_1.Observable();
  102231. this.onCompleteObservable = new babylonjs_1.Observable();
  102232. this.onAfterConfigure = new babylonjs_1.Observable();
  102233. this.state = ModelState.INIT;
  102234. var scene = this._configurationContainer && this._configurationContainer.scene;
  102235. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", scene);
  102236. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", scene);
  102237. this._pivotMesh.parent = this.rootMesh;
  102238. // rotate 180, gltf fun
  102239. this._pivotMesh.rotation.y += Math.PI;
  102240. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102241. this._animations = [];
  102242. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  102243. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  102244. if (this._observablesManager) {
  102245. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  102246. }
  102247. if (this._modelConfiguration.entryAnimation) {
  102248. this.rootMesh.setEnabled(false);
  102249. }
  102250. this.onLoadedObservable.add(function () {
  102251. _this.updateConfiguration(_this._modelConfiguration);
  102252. if (_this._observablesManager) {
  102253. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  102254. }
  102255. _this._initAnimations();
  102256. });
  102257. this.onCompleteObservable.add(function () {
  102258. _this.state = ModelState.COMPLETE;
  102259. });
  102260. }
  102261. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  102262. get: function () {
  102263. return this._shadowsRenderedAfterLoad;
  102264. },
  102265. set: function (rendered) {
  102266. if (!rendered) {
  102267. throw new Error("can only be enabled");
  102268. }
  102269. else {
  102270. this._shadowsRenderedAfterLoad = rendered;
  102271. }
  102272. },
  102273. enumerable: true,
  102274. configurable: true
  102275. });
  102276. ViewerModel.prototype.getViewerId = function () {
  102277. return this._configurationContainer && this._configurationContainer.viewerId;
  102278. };
  102279. Object.defineProperty(ViewerModel.prototype, "enabled", {
  102280. /**
  102281. * Is this model enabled?
  102282. */
  102283. get: function () {
  102284. return this.rootMesh.isEnabled();
  102285. },
  102286. /**
  102287. * Set whether this model is enabled or not.
  102288. */
  102289. set: function (enable) {
  102290. this.rootMesh.setEnabled(enable);
  102291. },
  102292. enumerable: true,
  102293. configurable: true
  102294. });
  102295. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  102296. set: function (done) {
  102297. this._loaderDone = done;
  102298. this._checkCompleteState();
  102299. },
  102300. enumerable: true,
  102301. configurable: true
  102302. });
  102303. ViewerModel.prototype._checkCompleteState = function () {
  102304. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  102305. this._modelComplete();
  102306. }
  102307. };
  102308. /**
  102309. * Add a mesh to this model.
  102310. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  102311. *
  102312. * @param mesh the new mesh to add
  102313. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  102314. */
  102315. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  102316. if (!mesh.parent) {
  102317. mesh.parent = this._pivotMesh;
  102318. }
  102319. mesh.receiveShadows = !!this.configuration.receiveShadows;
  102320. this._meshes.push(mesh);
  102321. if (triggerLoaded) {
  102322. return this.onLoadedObservable.notifyObserversWithPromise(this);
  102323. }
  102324. };
  102325. Object.defineProperty(ViewerModel.prototype, "meshes", {
  102326. /**
  102327. * get the list of meshes (excluding the root mesh)
  102328. */
  102329. get: function () {
  102330. return this._meshes;
  102331. },
  102332. enumerable: true,
  102333. configurable: true
  102334. });
  102335. Object.defineProperty(ViewerModel.prototype, "configuration", {
  102336. /**
  102337. * Get the model's configuration
  102338. */
  102339. get: function () {
  102340. return this._modelConfiguration;
  102341. },
  102342. /**
  102343. * (Re-)set the model's entire configuration
  102344. * @param newConfiguration the new configuration to replace the new one
  102345. */
  102346. set: function (newConfiguration) {
  102347. this._modelConfiguration = newConfiguration;
  102348. this._configureModel();
  102349. },
  102350. enumerable: true,
  102351. configurable: true
  102352. });
  102353. /**
  102354. * Update the current configuration with new values.
  102355. * Configuration will not be overwritten, but merged with the new configuration.
  102356. * Priority is to the new configuration
  102357. * @param newConfiguration the configuration to be merged into the current configuration;
  102358. */
  102359. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  102360. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  102361. this._configureModel();
  102362. };
  102363. ViewerModel.prototype._initAnimations = function () {
  102364. var _this = this;
  102365. // check if this is not a gltf loader and init the animations
  102366. if (this.skeletons.length) {
  102367. this.skeletons.forEach(function (skeleton, idx) {
  102368. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._configurationContainer && _this._configurationContainer.scene);
  102369. var add = false;
  102370. skeleton.getAnimatables().forEach(function (a) {
  102371. if (a.animations[0]) {
  102372. ag.addTargetedAnimation(a.animations[0], a);
  102373. add = true;
  102374. }
  102375. });
  102376. if (add) {
  102377. _this.addAnimationGroup(ag);
  102378. }
  102379. });
  102380. }
  102381. var completeCallback = function () {
  102382. };
  102383. if (this._modelConfiguration.animation) {
  102384. if (this._modelConfiguration.animation.playOnce) {
  102385. this._animations.forEach(function (a) {
  102386. a.playMode = 0 /* ONCE */;
  102387. });
  102388. }
  102389. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  102390. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  102391. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  102392. completeCallback = function () {
  102393. _this.playAnimation(animationName_1);
  102394. };
  102395. }
  102396. }
  102397. this._enterScene(completeCallback);
  102398. };
  102399. /**
  102400. * Animates the model from the current position to the default position
  102401. * @param completeCallback A function to call when the animation has completed
  102402. */
  102403. ViewerModel.prototype._enterScene = function (completeCallback) {
  102404. var _this = this;
  102405. var scene = this.rootMesh.getScene();
  102406. var previousValue = scene.animationPropertiesOverride.enableBlending;
  102407. var callback = function () {
  102408. _this.state = ModelState.ENTRYDONE;
  102409. scene.animationPropertiesOverride.enableBlending = previousValue;
  102410. _this._checkCompleteState();
  102411. if (completeCallback)
  102412. completeCallback();
  102413. };
  102414. if (!this._entryAnimation) {
  102415. callback();
  102416. return;
  102417. }
  102418. this.rootMesh.setEnabled(true);
  102419. // disable blending for the sake of the entry animation;
  102420. scene.animationPropertiesOverride.enableBlending = false;
  102421. this._applyAnimation(this._entryAnimation, true, callback);
  102422. };
  102423. /**
  102424. * Animates the model from the current position to the exit-screen position
  102425. * @param completeCallback A function to call when the animation has completed
  102426. */
  102427. ViewerModel.prototype._exitScene = function (completeCallback) {
  102428. if (!this._exitAnimation) {
  102429. completeCallback();
  102430. return;
  102431. }
  102432. this._applyAnimation(this._exitAnimation, false, completeCallback);
  102433. };
  102434. ViewerModel.prototype._modelComplete = function () {
  102435. var _this = this;
  102436. //reapply material defines to be sure:
  102437. var meshes = this._pivotMesh.getChildMeshes(false);
  102438. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  102439. _this._applyModelMaterialConfiguration(mesh.material);
  102440. });
  102441. this.state = ModelState.COMPLETE;
  102442. this.onCompleteObservable.notifyObservers(this);
  102443. };
  102444. /**
  102445. * Add a new animation group to this model.
  102446. * @param animationGroup the new animation group to be added
  102447. */
  102448. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  102449. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  102450. };
  102451. /**
  102452. * Get the ModelAnimation array
  102453. */
  102454. ViewerModel.prototype.getAnimations = function () {
  102455. return this._animations;
  102456. };
  102457. /**
  102458. * Get the animations' names. Using the names you can play a specific animation.
  102459. */
  102460. ViewerModel.prototype.getAnimationNames = function () {
  102461. return this._animations.map(function (a) { return a.name; });
  102462. };
  102463. /**
  102464. * Get an animation by the provided name. Used mainly when playing n animation.
  102465. * @param name the name of the animation to find
  102466. */
  102467. ViewerModel.prototype._getAnimationByName = function (name) {
  102468. // can't use .find, noe available on IE
  102469. var filtered = this._animations.filter(function (a) { return a.name === name; });
  102470. // what the next line means - if two animations have the same name, they will not be returned!
  102471. if (filtered.length === 1) {
  102472. return filtered[0];
  102473. }
  102474. else {
  102475. return null;
  102476. }
  102477. };
  102478. /**
  102479. * Choose an initialized animation using its name and start playing it
  102480. * @param name the name of the animation to play
  102481. * @returns The model aniamtion to be played.
  102482. */
  102483. ViewerModel.prototype.playAnimation = function (name) {
  102484. var animation = this.setCurrentAnimationByName(name);
  102485. if (animation) {
  102486. animation.start();
  102487. }
  102488. return animation;
  102489. };
  102490. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  102491. var animation = this._getAnimationByName(name);
  102492. if (animation) {
  102493. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  102494. this.currentAnimation.stop();
  102495. }
  102496. this.currentAnimation = animation;
  102497. return animation;
  102498. }
  102499. else {
  102500. throw new Error("animation not found - " + name);
  102501. }
  102502. };
  102503. ViewerModel.prototype._configureModel = function () {
  102504. var _this = this;
  102505. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  102506. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  102507. var updateMeshesWithNoParent = function (variable, value, param) {
  102508. meshesWithNoParent.forEach(function (mesh) {
  102509. if (param) {
  102510. mesh[variable][param] = value;
  102511. }
  102512. else {
  102513. mesh[variable] = value;
  102514. }
  102515. });
  102516. };
  102517. var updateXYZ = function (variable, configValues) {
  102518. if (configValues.x !== undefined) {
  102519. updateMeshesWithNoParent(variable, configValues.x, 'x');
  102520. }
  102521. if (configValues.y !== undefined) {
  102522. updateMeshesWithNoParent(variable, configValues.y, 'y');
  102523. }
  102524. if (configValues.z !== undefined) {
  102525. updateMeshesWithNoParent(variable, configValues.z, 'z');
  102526. }
  102527. if (configValues.w !== undefined) {
  102528. updateMeshesWithNoParent(variable, configValues.w, 'w');
  102529. }
  102530. };
  102531. if (this._modelConfiguration.normalize) {
  102532. var center = false;
  102533. var unitSize = false;
  102534. var parentIndex = void 0;
  102535. if (this._modelConfiguration.normalize === true) {
  102536. center = true;
  102537. unitSize = true;
  102538. }
  102539. else {
  102540. center = !!this._modelConfiguration.normalize.center;
  102541. unitSize = !!this._modelConfiguration.normalize.unitSize;
  102542. parentIndex = this._modelConfiguration.normalize.parentIndex;
  102543. }
  102544. var meshesToNormalize = [];
  102545. if (parentIndex !== undefined) {
  102546. meshesToNormalize.push(this._meshes[parentIndex]);
  102547. }
  102548. else {
  102549. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  102550. }
  102551. if (unitSize) {
  102552. meshesToNormalize.forEach(function (mesh) {
  102553. mesh.normalizeToUnitCube(true);
  102554. mesh.computeWorldMatrix(true);
  102555. });
  102556. }
  102557. if (center) {
  102558. meshesToNormalize.forEach(function (mesh) {
  102559. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  102560. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  102561. var halfSizeVec = sizeVec.scale(0.5);
  102562. var center = boundingInfo.min.add(halfSizeVec);
  102563. mesh.position = center.scale(-1);
  102564. mesh.position.y += halfSizeVec.y;
  102565. // Recompute Info.
  102566. mesh.computeWorldMatrix(true);
  102567. });
  102568. }
  102569. }
  102570. else {
  102571. // if centered, should be done here
  102572. }
  102573. // position?
  102574. if (this._modelConfiguration.position) {
  102575. updateXYZ('position', this._modelConfiguration.position);
  102576. }
  102577. if (this._modelConfiguration.rotation) {
  102578. //quaternion?
  102579. if (this._modelConfiguration.rotation.w) {
  102580. meshesWithNoParent.forEach(function (mesh) {
  102581. if (!mesh.rotationQuaternion) {
  102582. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  102583. }
  102584. });
  102585. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  102586. }
  102587. else {
  102588. updateXYZ('rotation', this._modelConfiguration.rotation);
  102589. }
  102590. }
  102591. if (this._modelConfiguration.rotationOffsetAxis) {
  102592. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  102593. meshesWithNoParent.forEach(function (m) {
  102594. if (_this._modelConfiguration.rotationOffsetAngle) {
  102595. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  102596. }
  102597. });
  102598. }
  102599. if (this._modelConfiguration.scaling) {
  102600. updateXYZ('scaling', this._modelConfiguration.scaling);
  102601. }
  102602. if (this._modelConfiguration.castShadow) {
  102603. this._meshes.forEach(function (mesh) {
  102604. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  102605. });
  102606. }
  102607. var meshes = this._pivotMesh.getChildMeshes(false);
  102608. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  102609. _this._applyModelMaterialConfiguration(mesh.material);
  102610. });
  102611. if (this._modelConfiguration.entryAnimation) {
  102612. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  102613. }
  102614. if (this._modelConfiguration.exitAnimation) {
  102615. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  102616. }
  102617. this.onAfterConfigure.notifyObservers(this);
  102618. };
  102619. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  102620. var anim = {
  102621. time: 0.5
  102622. };
  102623. if (animConfig.scaling) {
  102624. anim.scaling = babylonjs_1.Vector3.Zero();
  102625. }
  102626. if (animConfig.easingFunction !== undefined) {
  102627. anim.easingFunction = animConfig.easingFunction;
  102628. }
  102629. if (animConfig.easingMode !== undefined) {
  102630. anim.easingMode = animConfig.easingMode;
  102631. }
  102632. _1.extendClassWithConfig(anim, animConfig);
  102633. return anim;
  102634. };
  102635. /**
  102636. * Apply a material configuration to a material
  102637. * @param material Material to apply configuration to
  102638. */
  102639. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  102640. if (!this._modelConfiguration.material)
  102641. return;
  102642. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  102643. if (material instanceof babylonjs_1.PBRMaterial) {
  102644. if (this._modelConfiguration.material.directIntensity !== undefined) {
  102645. material.directIntensity = this._modelConfiguration.material.directIntensity;
  102646. }
  102647. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  102648. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  102649. }
  102650. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  102651. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  102652. }
  102653. if (this._modelConfiguration.material.directEnabled !== undefined) {
  102654. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  102655. }
  102656. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  102657. material.reflectionColor = this._configurationContainer.reflectionColor;
  102658. }
  102659. }
  102660. else if (material instanceof babylonjs_1.MultiMaterial) {
  102661. for (var i = 0; i < material.subMaterials.length; i++) {
  102662. var subMaterial = material.subMaterials[i];
  102663. if (subMaterial) {
  102664. this._applyModelMaterialConfiguration(subMaterial);
  102665. }
  102666. }
  102667. }
  102668. };
  102669. /**
  102670. * Start entry/exit animation given an animation configuration
  102671. * @param animationConfiguration Entry/Exit animation configuration
  102672. * @param isEntry Pass true if the animation is an entry animation
  102673. * @param completeCallback Callback to execute when the animation completes
  102674. */
  102675. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  102676. var animations = [];
  102677. //scale
  102678. if (animationConfiguration.scaling) {
  102679. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  102680. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  102681. if (!scaleStart.equals(scaleEnd)) {
  102682. this.rootMesh.scaling = scaleStart;
  102683. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  102684. animations.push(this._scaleTransition);
  102685. }
  102686. }
  102687. //Start the animation(s)
  102688. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  102689. completeCallback(); });
  102690. };
  102691. /**
  102692. * Begin @animations with the specified @easingFunction
  102693. * @param animations The BABYLON Animations to begin
  102694. * @param duration of transition, in seconds
  102695. * @param easingFunction An easing function to apply
  102696. * @param easingMode A easing mode to apply to the easingFunction
  102697. * @param onAnimationEnd Call back trigger at the end of the animation.
  102698. */
  102699. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  102700. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  102701. if (easingFunction) {
  102702. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  102703. var animation = animations_1[_i];
  102704. easingFunction.setEasingMode(easingMode);
  102705. animation.setEasingFunction(easingFunction);
  102706. }
  102707. }
  102708. //Stop any current animations before starting the new one - merging not yet supported.
  102709. this.stopAllAnimations();
  102710. this.rootMesh.animations = animations;
  102711. if (this.rootMesh.getScene().beginAnimation) {
  102712. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  102713. if (onAnimationEnd) {
  102714. onAnimationEnd();
  102715. }
  102716. });
  102717. this._animatables.push(animatable);
  102718. }
  102719. };
  102720. /**
  102721. * Sets key values on an Animation from first to last frame.
  102722. * @param animation The Babylon animation object to set keys on
  102723. * @param startValue The value of the first key
  102724. * @param endValue The value of the last key
  102725. * @param duration The duration of the animation, used to determine the end frame
  102726. */
  102727. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  102728. animation.setKeys([
  102729. {
  102730. frame: 0,
  102731. value: startValue
  102732. },
  102733. {
  102734. frame: this._frameRate * duration,
  102735. value: endValue
  102736. }
  102737. ]);
  102738. };
  102739. /**
  102740. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  102741. * @param easingFunctionID The enum of the easing funtion to create
  102742. * @return The newly created Babylon easing function object
  102743. */
  102744. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  102745. var easingFunction;
  102746. switch (easingFunctionID) {
  102747. case 1 /* CircleEase */:
  102748. easingFunction = new babylonjs_1.CircleEase();
  102749. break;
  102750. case 2 /* BackEase */:
  102751. easingFunction = new babylonjs_1.BackEase(0.3);
  102752. break;
  102753. case 3 /* BounceEase */:
  102754. easingFunction = new babylonjs_1.BounceEase();
  102755. break;
  102756. case 4 /* CubicEase */:
  102757. easingFunction = new babylonjs_1.CubicEase();
  102758. break;
  102759. case 5 /* ElasticEase */:
  102760. easingFunction = new babylonjs_1.ElasticEase();
  102761. break;
  102762. case 6 /* ExponentialEase */:
  102763. easingFunction = new babylonjs_1.ExponentialEase();
  102764. break;
  102765. case 7 /* PowerEase */:
  102766. easingFunction = new babylonjs_1.PowerEase();
  102767. break;
  102768. case 8 /* QuadraticEase */:
  102769. easingFunction = new babylonjs_1.QuadraticEase();
  102770. break;
  102771. case 9 /* QuarticEase */:
  102772. easingFunction = new babylonjs_1.QuarticEase();
  102773. break;
  102774. case 10 /* QuinticEase */:
  102775. easingFunction = new babylonjs_1.QuinticEase();
  102776. break;
  102777. case 11 /* SineEase */:
  102778. easingFunction = new babylonjs_1.SineEase();
  102779. break;
  102780. default:
  102781. babylonjs_1.Tools.Log("No ease function found");
  102782. break;
  102783. }
  102784. return easingFunction;
  102785. };
  102786. /**
  102787. * Stops and removes all animations that have been applied to the model
  102788. */
  102789. ViewerModel.prototype.stopAllAnimations = function () {
  102790. if (this.rootMesh) {
  102791. this.rootMesh.animations = [];
  102792. }
  102793. if (this.currentAnimation) {
  102794. this.currentAnimation.stop();
  102795. }
  102796. while (this._animatables.length) {
  102797. this._animatables[0].onAnimationEnd = null;
  102798. this._animatables[0].stop();
  102799. this._animatables.shift();
  102800. }
  102801. };
  102802. /**
  102803. * Will remove this model from the viewer (but NOT dispose it).
  102804. */
  102805. ViewerModel.prototype.remove = function () {
  102806. this.stopAllAnimations();
  102807. // hide it
  102808. this.rootMesh.isVisible = false;
  102809. if (this._observablesManager) {
  102810. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  102811. }
  102812. };
  102813. /**
  102814. * Dispose this model, including all of its associated assets.
  102815. */
  102816. ViewerModel.prototype.dispose = function () {
  102817. this.remove();
  102818. this.onAfterConfigure.clear();
  102819. this.onLoadedObservable.clear();
  102820. this.onLoadErrorObservable.clear();
  102821. this.onLoadProgressObservable.clear();
  102822. if (this.loader && this.loader.name === "gltf") {
  102823. this.loader.dispose();
  102824. }
  102825. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  102826. this.particleSystems.length = 0;
  102827. this.skeletons.forEach(function (s) { return s.dispose(); });
  102828. this.skeletons.length = 0;
  102829. this._animations.forEach(function (ag) { return ag.dispose(); });
  102830. this._animations.length = 0;
  102831. this.rootMesh.dispose(false, true);
  102832. };
  102833. return ViewerModel;
  102834. }());
  102835. exports.ViewerModel = ViewerModel;
  102836. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTW9kZWwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvdmlld2VyTW9kZWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBc2Q7QUFJdGQsbURBQXdKO0FBRXhKLCtCQUE4RDtBQUs5RDs7R0FFRztBQUNILElBQVksVUFTWDtBQVRELFdBQVksVUFBVTtJQUNsQiwyQ0FBSSxDQUFBO0lBQ0osaURBQU8sQ0FBQTtJQUNQLCtDQUFNLENBQUE7SUFDTiw2Q0FBSyxDQUFBO0lBQ0wscURBQVMsQ0FBQTtJQUNULG1EQUFRLENBQUE7SUFDUixtREFBUSxDQUFBO0lBQ1IsNkNBQUssQ0FBQTtBQUNULENBQUMsRUFUVyxVQUFVLEdBQVYsa0JBQVUsS0FBVixrQkFBVSxRQVNyQjtBQUVEOztHQUVHO0FBQ0g7SUErRUkscUJBQW9CLG1CQUF1QyxFQUFFLGtCQUF1QyxFQUFVLHVCQUFnRDtRQUE5SixpQkFzQ0M7UUF0Q21CLHdCQUFtQixHQUFuQixtQkFBbUIsQ0FBb0I7UUFBbUQsNEJBQ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LENBQUMsT0FBTyxFQUFFLEVBQVosQ0FBWSxDQUFDLENBQUM7UUFDakQsSUFBSSxDQUFDLGVBQWUsQ0FBQyxNQUFNLEdBQUcsQ0FBQyxDQUFDO1FBQ2hDLElBQUksQ0FBQyxTQUFTLENBQUMsT0FBTyxDQUFDLFVBQUEsQ0FBQyxJQUFJLE9BQUEsQ0FBQyxDQUFDLE9BQU8sRUFBRSxFQUFYLENBQVcsQ0FBQyxDQUFDO1FBQ3pDLElBQUksQ0FBQyxTQUFTLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztRQUMxQixJQUFJLENBQUMsV0FBVyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEVBQUUsSUFBSSxPQUFBLEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBWixDQUFZLENBQUMsQ0FBQztRQUM3QyxJQUFJLENBQUMsV0FBVyxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUM7UUFDNUIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFsdUJELElBa3VCQztBQWx1Qlksa0NBQVcifQ==
  102837. /***/ }),
  102838. /* 6 */
  102839. /***/ (function(module, exports, __webpack_require__) {
  102840. "use strict";
  102841. Object.defineProperty(exports, "__esModule", { value: true });
  102842. var babylonjs_1 = __webpack_require__(0);
  102843. /**
  102844. * Receives Telemetry events and raises events to the API
  102845. */
  102846. var TelemetryManager = /** @class */ (function () {
  102847. function TelemetryManager() {
  102848. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  102849. this._event = this._eventEnabled;
  102850. }
  102851. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  102852. /**
  102853. * Receives a telemetry event
  102854. * @param event The name of the Telemetry event
  102855. * @param details An additional value, or an object containing a list of property/value pairs
  102856. */
  102857. get: function () {
  102858. return this._event;
  102859. },
  102860. enumerable: true,
  102861. configurable: true
  102862. });
  102863. /**
  102864. * Log a Telemetry event for errors raised on the WebGL context.
  102865. * @param engine The Babylon engine with the WebGL context.
  102866. */
  102867. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  102868. if (!engine) {
  102869. return;
  102870. }
  102871. var logErrors = true;
  102872. while (logErrors) {
  102873. var gl = engine._gl;
  102874. if (gl && gl.getError) {
  102875. var error = gl.getError();
  102876. if (error === gl.NO_ERROR) {
  102877. logErrors = false;
  102878. }
  102879. else {
  102880. this.broadcast("WebGL Error", viewerId, { error: error });
  102881. }
  102882. }
  102883. else {
  102884. logErrors = false;
  102885. }
  102886. }
  102887. };
  102888. Object.defineProperty(TelemetryManager.prototype, "enable", {
  102889. /**
  102890. * Enable or disable telemetry events
  102891. * @param enabled Boolan, true if events are enabled
  102892. */
  102893. set: function (enabled) {
  102894. if (enabled) {
  102895. this._event = this._eventEnabled;
  102896. }
  102897. else {
  102898. this._event = this._eventDisabled;
  102899. }
  102900. },
  102901. enumerable: true,
  102902. configurable: true
  102903. });
  102904. /**
  102905. * Called on event when disabled, typically do nothing here
  102906. */
  102907. TelemetryManager.prototype._eventDisabled = function () {
  102908. // nothing to do
  102909. };
  102910. /**
  102911. * Called on event when enabled
  102912. * @param event - The name of the Telemetry event
  102913. * @param details An additional value, or an object containing a list of property/value pairs
  102914. */
  102915. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  102916. var telemetryData = {
  102917. viewerId: viewerId,
  102918. event: event,
  102919. session: this.session,
  102920. date: new Date(),
  102921. now: window.performance ? window.performance.now() : Date.now(),
  102922. detail: null
  102923. };
  102924. if (typeof details === "object") {
  102925. for (var attr in details) {
  102926. if (details.hasOwnProperty(attr)) {
  102927. telemetryData[attr] = details[attr];
  102928. }
  102929. }
  102930. }
  102931. else if (details) {
  102932. telemetryData.detail = details;
  102933. }
  102934. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  102935. };
  102936. Object.defineProperty(TelemetryManager.prototype, "session", {
  102937. /**
  102938. * Returns the current session ID or creates one if it doesn't exixt
  102939. * @return The current session ID
  102940. */
  102941. get: function () {
  102942. if (!this._currentSessionId) {
  102943. //String + Timestamp + Random Integer
  102944. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  102945. }
  102946. return this._currentSessionId;
  102947. },
  102948. enumerable: true,
  102949. configurable: true
  102950. });
  102951. /**
  102952. * Disposes the telemetry manager
  102953. */
  102954. TelemetryManager.prototype.dispose = function () {
  102955. this.onEventBroadcastedObservable.clear();
  102956. delete this.onEventBroadcastedObservable;
  102957. };
  102958. return TelemetryManager;
  102959. }());
  102960. exports.TelemetryManager = TelemetryManager;
  102961. exports.telemetryManager = new TelemetryManager();
  102962. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9tYW5hZ2Vycy90ZWxlbWV0cnlNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQStDO0FBYy9DOztHQUVHO0FBQ0g7SUFBQTtRQUVXLGlDQUE0QixHQUE4QixJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUkxRSxXQUFNLEdBQThELElBQUksQ0FBQyxhQUFhLENBQUM7SUFzR25HLENBQUM7SUEvRkcsc0JBQVcsdUNBQVM7UUFMcEI7Ozs7V0FJRzthQUNIO1lBQ0ksT0FBTyxJQUFJLENBQUMsTUFBTSxDQUFDO1FBQ3ZCLENBQUM7OztPQUFBO0lBRUQ7OztPQUdHO0lBQ0ksMkNBQWdCLEdBQXZCLFVBQXdCLE1BQWMsRUFBRSxRQUFpQjtRQUNyRCxJQUFJLENBQUMsTUFBTSxFQUFFO1lBQ1QsT0FBTztTQUNWO1FBQ0QsSUFBSSxTQUFTLEdBQUcsSUFBSSxDQUFD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DSSxJQUFJLENBQUMsNEJBQTRCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDMUMsT0FBTyxJQUFJLENBQUMsNEJBQTRCLENBQUM7SUFDN0MsQ0FBQztJQUNMLHVCQUFDO0FBQUQsQ0FBQyxBQTVHRCxJQTRHQztBQTVHWSw0Q0FBZ0I7QUE4R2hCLFFBQUEsZ0JBQWdCLEdBQUcsSUFBSSxnQkFBZ0IsRUFBRSxDQUFDIn0=
  102963. /***/ }),
  102964. /* 7 */
  102965. /***/ (function(module, exports, __webpack_require__) {
  102966. "use strict";
  102967. Object.defineProperty(exports, "__esModule", { value: true });
  102968. var babylonjs_1 = __webpack_require__(0);
  102969. /**
  102970. * The viewer manager is the container for all viewers currently registered on this page.
  102971. * It is possible to have more than one viewer on a single page.
  102972. */
  102973. var ViewerManager = /** @class */ (function () {
  102974. function ViewerManager() {
  102975. this._viewers = {};
  102976. this.onViewerAddedObservable = new babylonjs_1.Observable();
  102977. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  102978. }
  102979. /**
  102980. * Adding a new viewer to the viewer manager and start tracking it.
  102981. * @param viewer the viewer to add
  102982. */
  102983. ViewerManager.prototype.addViewer = function (viewer) {
  102984. this._viewers[viewer.getBaseId()] = viewer;
  102985. this._onViewerAdded(viewer);
  102986. };
  102987. /**
  102988. * remove a viewer from the viewer manager
  102989. * @param viewer the viewer to remove
  102990. */
  102991. ViewerManager.prototype.removeViewer = function (viewer) {
  102992. var id = viewer.getBaseId();
  102993. delete this._viewers[id];
  102994. this.onViewerRemovedObservable.notifyObservers(id);
  102995. };
  102996. /**
  102997. * 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)
  102998. * @param id the id of the HTMl element (or the viewer's, if none provided)
  102999. */
  103000. ViewerManager.prototype.getViewerById = function (id) {
  103001. return this._viewers[id];
  103002. };
  103003. /**
  103004. * Get a viewer using a container element
  103005. * @param element the HTML element to search viewers associated with
  103006. */
  103007. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  103008. for (var id in this._viewers) {
  103009. if (this._viewers[id].containerElement === element) {
  103010. return this.getViewerById(id);
  103011. }
  103012. }
  103013. };
  103014. /**
  103015. * Get a promise that will fullfil when this viewer was initialized.
  103016. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  103017. * you will get the viewer after everything was already configured.
  103018. * @param id the viewer id to find
  103019. */
  103020. ViewerManager.prototype.getViewerPromiseById = function (id) {
  103021. var _this = this;
  103022. return new Promise(function (resolve, reject) {
  103023. var localViewer = _this.getViewerById(id);
  103024. if (localViewer) {
  103025. return resolve(localViewer);
  103026. }
  103027. var viewerFunction = function (viewer) {
  103028. if (viewer.getBaseId() === id) {
  103029. resolve(viewer);
  103030. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  103031. }
  103032. };
  103033. _this.onViewerAddedObservable.add(viewerFunction);
  103034. });
  103035. };
  103036. ViewerManager.prototype._onViewerAdded = function (viewer) {
  103037. this.onViewerAdded && this.onViewerAdded(viewer);
  103038. this.onViewerAddedObservable.notifyObservers(viewer);
  103039. };
  103040. /**
  103041. * dispose the manager and all of its associated viewers
  103042. */
  103043. ViewerManager.prototype.dispose = function () {
  103044. delete this._onViewerAdded;
  103045. for (var id in this._viewers) {
  103046. this._viewers[id].dispose();
  103047. }
  103048. this.onViewerAddedObservable.clear();
  103049. this.onViewerRemovedObservable.clear();
  103050. };
  103051. return ViewerManager;
  103052. }());
  103053. exports.ViewerManager = ViewerManager;
  103054. exports.viewerManager = new ViewerManager();
  103055. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJL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FJLENBQUMsUUFBUSxDQUFDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sRUFBRSxDQUFDO1NBQy9CO1FBRUQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3JDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  103056. /***/ }),
  103057. /* 8 */
  103058. /***/ (function(module, exports, __webpack_require__) {
  103059. "use strict";
  103060. var __extends = (this && this.__extends) || (function () {
  103061. var extendStatics = Object.setPrototypeOf ||
  103062. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  103063. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  103064. return function (d, b) {
  103065. extendStatics(d, b);
  103066. function __() { this.constructor = d; }
  103067. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  103068. };
  103069. })();
  103070. Object.defineProperty(exports, "__esModule", { value: true });
  103071. var viewer_1 = __webpack_require__(9);
  103072. var babylonjs_1 = __webpack_require__(0);
  103073. /**
  103074. * The Default viewer is the default implementation of the AbstractViewer.
  103075. * It uses the templating system to render a new canvas and controls.
  103076. */
  103077. var DefaultViewer = /** @class */ (function (_super) {
  103078. __extends(DefaultViewer, _super);
  103079. /**
  103080. * Create a new default viewer
  103081. * @param containerElement the element in which the templates will be rendered
  103082. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  103083. */
  103084. function DefaultViewer(containerElement, initialConfiguration) {
  103085. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  103086. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  103087. _this.containerElement = containerElement;
  103088. _this._handlePointerDown = function (event) {
  103089. var pointerDown = event.event;
  103090. if (pointerDown.button !== 0)
  103091. return;
  103092. var element = event.event.target;
  103093. if (!element) {
  103094. return;
  103095. }
  103096. var parentClasses = element.parentElement.classList;
  103097. var elementClasses = element.classList;
  103098. var elementName = "";
  103099. 0;
  103100. for (var i = 0; i < elementClasses.length; ++i) {
  103101. var className = elementClasses[i];
  103102. if (className.indexOf("-button") !== -1 || className.indexOf("-wrapper") !== -1) {
  103103. elementName = className;
  103104. break;
  103105. }
  103106. }
  103107. switch (elementName) {
  103108. case "speed-button":
  103109. case "types-button":
  103110. if (parentClasses.contains("open")) {
  103111. parentClasses.remove("open");
  103112. }
  103113. else {
  103114. parentClasses.add("open");
  103115. }
  103116. break;
  103117. case "play-pause-button":
  103118. _this._togglePlayPause();
  103119. break;
  103120. case "label-option-button":
  103121. var label = element.dataset["value"];
  103122. if (label) {
  103123. _this._updateAnimationType(label);
  103124. }
  103125. break;
  103126. case "speed-option-button":
  103127. if (!_this._currentAnimation) {
  103128. return;
  103129. }
  103130. var speed = element.dataset["value"];
  103131. if (speed)
  103132. _this._updateAnimationSpeed(speed);
  103133. break;
  103134. case "progress-wrapper":
  103135. _this._resumePlay = !_this._isAnimationPaused;
  103136. if (_this._resumePlay) {
  103137. _this._togglePlayPause(true);
  103138. }
  103139. break;
  103140. case "fullscreen-button":
  103141. _this.toggleFullscreen();
  103142. break;
  103143. case "hd-button":
  103144. _this.toggleHD();
  103145. break;
  103146. default:
  103147. return;
  103148. }
  103149. };
  103150. /**
  103151. * Plays or Pauses animation
  103152. */
  103153. _this._togglePlayPause = function (noUiUpdate) {
  103154. if (!_this._currentAnimation) {
  103155. return;
  103156. }
  103157. if (_this._isAnimationPaused) {
  103158. _this._currentAnimation.restart();
  103159. }
  103160. else {
  103161. _this._currentAnimation.pause();
  103162. }
  103163. _this._isAnimationPaused = !_this._isAnimationPaused;
  103164. if (noUiUpdate)
  103165. return;
  103166. var navbar = _this.templateManager.getTemplate('navBar');
  103167. if (!navbar)
  103168. return;
  103169. navbar.updateParams({
  103170. paused: _this._isAnimationPaused,
  103171. });
  103172. };
  103173. /**
  103174. * Control progress bar position based on animation current frame
  103175. */
  103176. _this._updateProgressBar = function () {
  103177. var navbar = _this.templateManager.getTemplate('navBar');
  103178. if (!navbar)
  103179. return;
  103180. var progressSlider = navbar.parent.querySelector("input.progress-wrapper");
  103181. if (progressSlider && _this._currentAnimation) {
  103182. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  103183. var currentValue = progressSlider.valueAsNumber;
  103184. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  103185. progressSlider.value = '' + progress;
  103186. }
  103187. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  103188. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  103189. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  103190. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  103191. }
  103192. }
  103193. else {
  103194. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  103195. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  103196. _this._oldIdleRotationValue = 0;
  103197. }
  103198. }
  103199. }
  103200. };
  103201. /**
  103202. * Update Current Animation Speed
  103203. */
  103204. _this._updateAnimationSpeed = function (speed, paramsObject) {
  103205. var navbar = _this.templateManager.getTemplate('navBar');
  103206. if (!navbar)
  103207. return;
  103208. if (speed && _this._currentAnimation) {
  103209. _this._currentAnimation.speedRatio = parseFloat(speed);
  103210. if (!_this._isAnimationPaused) {
  103211. _this._currentAnimation.restart();
  103212. }
  103213. if (paramsObject) {
  103214. paramsObject.selectedSpeed = speed + "x";
  103215. }
  103216. else {
  103217. navbar.updateParams({
  103218. selectedSpeed: speed + "x",
  103219. });
  103220. }
  103221. }
  103222. };
  103223. /**
  103224. * Update Current Animation Type
  103225. */
  103226. _this._updateAnimationType = function (label, paramsObject) {
  103227. var navbar = _this.templateManager.getTemplate('navBar');
  103228. if (!navbar)
  103229. return;
  103230. if (label) {
  103231. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  103232. }
  103233. if (paramsObject) {
  103234. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  103235. paramsObject.selectedAnimationName = label;
  103236. }
  103237. else {
  103238. navbar.updateParams({
  103239. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  103240. selectedAnimationName: label
  103241. });
  103242. }
  103243. _this._updateAnimationSpeed("1.0", paramsObject);
  103244. };
  103245. /**
  103246. * Toggle fullscreen of the entire viewer
  103247. */
  103248. _this.toggleFullscreen = function () {
  103249. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  103250. var viewerElement = viewerTemplate && viewerTemplate.parent;
  103251. if (viewerElement) {
  103252. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  103253. if (!fullscreenElement) {
  103254. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  103255. requestFullScreen.call(viewerElement);
  103256. }
  103257. else {
  103258. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  103259. exitFullscreen.call(document);
  103260. }
  103261. }
  103262. };
  103263. _this._onModelLoaded = function (model) {
  103264. _this._configureTemplate(model);
  103265. // with a short timeout, making sure everything is there already.
  103266. var hideLoadingDelay = 20;
  103267. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  103268. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  103269. }
  103270. setTimeout(function () {
  103271. _this.sceneManager.scene.executeWhenReady(function () {
  103272. _this.hideLoadingScreen();
  103273. });
  103274. }, hideLoadingDelay);
  103275. return;
  103276. };
  103277. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  103278. _this.onModelRemovedObservable.add(function () {
  103279. _this._configureTemplate();
  103280. });
  103281. _this.onEngineInitObservable.add(function () {
  103282. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  103283. _this._configureLights(data.newConfiguration, data.model);
  103284. });
  103285. });
  103286. return _this;
  103287. }
  103288. /**
  103289. * This will be executed when the templates initialize.
  103290. */
  103291. DefaultViewer.prototype._onTemplatesLoaded = function () {
  103292. var _this = this;
  103293. this.showLoadingScreen();
  103294. // navbar
  103295. this._initNavbar();
  103296. // close overlay button
  103297. var template = this.templateManager.getTemplate('overlay');
  103298. if (template) {
  103299. var closeButton = template.parent.querySelector('.close-button');
  103300. if (closeButton) {
  103301. closeButton.addEventListener('pointerdown', function () {
  103302. _this.hideOverlayScreen();
  103303. });
  103304. }
  103305. }
  103306. if (this.configuration.templates && this.configuration.templates.viewer) {
  103307. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  103308. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  103309. }, function () {
  103310. }, function () {
  103311. }, function () {
  103312. }, function () {
  103313. }, function (file) {
  103314. _this.loadModel(file);
  103315. }, function () {
  103316. });
  103317. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  103318. }
  103319. }
  103320. return _super.prototype._onTemplatesLoaded.call(this);
  103321. };
  103322. DefaultViewer.prototype._dropped = function (evt) {
  103323. };
  103324. DefaultViewer.prototype._initNavbar = function () {
  103325. var _this = this;
  103326. var navbar = this.templateManager.getTemplate('navBar');
  103327. if (navbar) {
  103328. this.onFrameRenderedObservable.add(this._updateProgressBar);
  103329. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  103330. // an example how to trigger the help button. publiclly available
  103331. this.templateManager.eventManager.registerCallback("navBar", function () {
  103332. // do your thing
  103333. }, "pointerdown", ".help-button");
  103334. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  103335. var evt = event.event;
  103336. var element = (evt.target);
  103337. if (!_this._currentAnimation)
  103338. return;
  103339. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  103340. if (isNaN(gotoFrame))
  103341. return;
  103342. _this._currentAnimation.goToFrame(gotoFrame);
  103343. }, "input");
  103344. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  103345. if (_this._resumePlay) {
  103346. _this._togglePlayPause(true);
  103347. }
  103348. _this._resumePlay = false;
  103349. }, "pointerup", ".progress-wrapper");
  103350. if (window.devicePixelRatio === 1 && navbar.configuration.params && !navbar.configuration.params.hideHdButton) {
  103351. navbar.updateParams({
  103352. hideHdButton: true
  103353. });
  103354. }
  103355. }
  103356. };
  103357. DefaultViewer.prototype.toggleHD = function () {
  103358. _super.prototype.toggleHD.call(this);
  103359. // update UI element
  103360. var navbar = this.templateManager.getTemplate('navBar');
  103361. if (!navbar)
  103362. return;
  103363. if (navbar.configuration.params) {
  103364. navbar.configuration.params.hdEnabled = this._hdToggled;
  103365. }
  103366. var span = navbar.parent.querySelector("button.hd-button span");
  103367. if (span) {
  103368. span.classList.remove(this._hdToggled ? "hd-icon" : "sd-icon");
  103369. span.classList.add(!this._hdToggled ? "hd-icon" : "sd-icon");
  103370. }
  103371. };
  103372. /**
  103373. * Preparing the container element to present the viewer
  103374. */
  103375. DefaultViewer.prototype._prepareContainerElement = function () {
  103376. this.containerElement.style.position = 'relative';
  103377. this.containerElement.style.height = '100%';
  103378. this.containerElement.style.display = 'flex';
  103379. };
  103380. /**
  103381. * This function will configure the templates and update them after a model was loaded
  103382. * It is mainly responsible to changing the title and subtitle etc'.
  103383. * @param model the model to be used to configure the templates by
  103384. */
  103385. DefaultViewer.prototype._configureTemplate = function (model) {
  103386. var navbar = this.templateManager.getTemplate('navBar');
  103387. if (!navbar)
  103388. return;
  103389. var newParams = navbar.configuration.params || {};
  103390. if (!model) {
  103391. newParams.animations = null;
  103392. }
  103393. else {
  103394. var animationNames = model.getAnimationNames();
  103395. newParams.animations = animationNames;
  103396. if (animationNames.length) {
  103397. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  103398. this._animationList = animationNames;
  103399. newParams.paused = this._isAnimationPaused;
  103400. var animationIndex = 0;
  103401. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  103402. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  103403. if (animationIndex === -1) {
  103404. animationIndex = 0;
  103405. }
  103406. }
  103407. this._updateAnimationType(animationNames[animationIndex], newParams);
  103408. }
  103409. else {
  103410. newParams.animations = null;
  103411. }
  103412. if (model.configuration.thumbnail) {
  103413. newParams.logoImage = model.configuration.thumbnail;
  103414. }
  103415. }
  103416. navbar.updateParams(newParams, false);
  103417. };
  103418. /**
  103419. * This will load a new model to the default viewer
  103420. * overriding the AbstractViewer's loadModel.
  103421. * The scene will automatically be cleared of the old models, if exist.
  103422. * @param model the configuration object (or URL) to load.
  103423. */
  103424. DefaultViewer.prototype.loadModel = function (model) {
  103425. var _this = this;
  103426. if (!model) {
  103427. model = this.configuration.model;
  103428. }
  103429. this.showLoadingScreen();
  103430. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  103431. console.log(error);
  103432. _this.hideLoadingScreen();
  103433. _this.showOverlayScreen('error');
  103434. return Promise.reject(error);
  103435. });
  103436. };
  103437. /**
  103438. * Show the overlay and the defined sub-screen.
  103439. * Mainly used for help and errors
  103440. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  103441. */
  103442. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  103443. var _this = this;
  103444. var template = this.templateManager.getTemplate('overlay');
  103445. if (!template)
  103446. return Promise.resolve('Overlay template not found');
  103447. return template.show((function (template) {
  103448. var canvasRect = _this.containerElement.getBoundingClientRect();
  103449. template.parent.style.display = 'flex';
  103450. template.parent.style.width = canvasRect.width + "px";
  103451. template.parent.style.height = canvasRect.height + "px";
  103452. template.parent.style.opacity = "1";
  103453. var subTemplate = _this.templateManager.getTemplate(subScreen);
  103454. if (!subTemplate) {
  103455. return Promise.reject(subScreen + ' template not found');
  103456. }
  103457. return subTemplate.show((function (template) {
  103458. template.parent.style.display = 'flex';
  103459. return Promise.resolve(template);
  103460. }));
  103461. }));
  103462. };
  103463. /**
  103464. * Hide the overlay screen.
  103465. */
  103466. DefaultViewer.prototype.hideOverlayScreen = function () {
  103467. var template = this.templateManager.getTemplate('overlay');
  103468. if (!template)
  103469. return Promise.resolve('Overlay template not found');
  103470. return template.hide((function (template) {
  103471. template.parent.style.opacity = "0";
  103472. var onTransitionEnd = function () {
  103473. template.parent.removeEventListener("transitionend", onTransitionEnd);
  103474. template.parent.style.display = 'none';
  103475. };
  103476. template.parent.addEventListener("transitionend", onTransitionEnd);
  103477. var overlays = template.parent.querySelectorAll('.overlay');
  103478. if (overlays) {
  103479. for (var i = 0; i < overlays.length; ++i) {
  103480. var htmlElement = overlays.item(i);
  103481. htmlElement.style.display = 'none';
  103482. }
  103483. }
  103484. return Promise.resolve(template);
  103485. }));
  103486. };
  103487. /**
  103488. * show the viewer (in case it was hidden)
  103489. *
  103490. * @param visibilityFunction an optional function to execute in order to show the container
  103491. */
  103492. DefaultViewer.prototype.show = function (visibilityFunction) {
  103493. var template = this.templateManager.getTemplate('main');
  103494. //not possible, but yet:
  103495. if (!template)
  103496. return Promise.reject('Main template not found');
  103497. return template.show(visibilityFunction);
  103498. };
  103499. /**
  103500. * hide the viewer (in case it is visible)
  103501. *
  103502. * @param visibilityFunction an optional function to execute in order to hide the container
  103503. */
  103504. DefaultViewer.prototype.hide = function (visibilityFunction) {
  103505. var template = this.templateManager.getTemplate('main');
  103506. //not possible, but yet:
  103507. if (!template)
  103508. return Promise.reject('Main template not found');
  103509. return template.hide(visibilityFunction);
  103510. };
  103511. /**
  103512. * Show the loading screen.
  103513. * The loading screen can be configured using the configuration object
  103514. */
  103515. DefaultViewer.prototype.showLoadingScreen = function () {
  103516. var _this = this;
  103517. var template = this.templateManager.getTemplate('loadingScreen');
  103518. if (!template)
  103519. return Promise.resolve('Loading Screen template not found');
  103520. return template.show((function (template) {
  103521. var canvasRect = _this.containerElement.getBoundingClientRect();
  103522. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  103523. template.parent.style.display = 'flex';
  103524. template.parent.style.width = canvasRect.width + "px";
  103525. template.parent.style.height = canvasRect.height + "px";
  103526. template.parent.style.opacity = "1";
  103527. // from the configuration!!!
  103528. var color = "black";
  103529. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  103530. color = (_this.configuration.templates.loadingScreen.params &&
  103531. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  103532. }
  103533. template.parent.style.backgroundColor = color;
  103534. return Promise.resolve(template);
  103535. }));
  103536. };
  103537. /**
  103538. * Hide the loading screen
  103539. */
  103540. DefaultViewer.prototype.hideLoadingScreen = function () {
  103541. var template = this.templateManager.getTemplate('loadingScreen');
  103542. if (!template)
  103543. return Promise.resolve('Loading Screen template not found');
  103544. return template.hide((function (template) {
  103545. template.parent.style.opacity = "0";
  103546. var onTransitionEnd = function () {
  103547. template.parent.removeEventListener("transitionend", onTransitionEnd);
  103548. template.parent.style.display = 'none';
  103549. };
  103550. template.parent.addEventListener("transitionend", onTransitionEnd);
  103551. return Promise.resolve(template);
  103552. }));
  103553. };
  103554. DefaultViewer.prototype.dispose = function () {
  103555. this.templateManager.dispose();
  103556. _super.prototype.dispose.call(this);
  103557. };
  103558. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  103559. var _this = this;
  103560. _super.prototype._onConfigurationLoaded.call(this, configuration);
  103561. // initialize the templates
  103562. var templateConfiguration = this.configuration.templates || {};
  103563. this.templateManager.initTemplate(templateConfiguration);
  103564. // when done, execute onTemplatesLoaded()
  103565. this.templateManager.onAllLoaded.add(function () {
  103566. var canvas = _this.templateManager.getCanvas();
  103567. if (canvas) {
  103568. _this._canvas = canvas;
  103569. }
  103570. _this._onTemplateLoaded();
  103571. });
  103572. };
  103573. /**
  103574. * An extension of the light configuration of the abstract viewer.
  103575. * @param lightsConfiguration the light configuration to use
  103576. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  103577. */
  103578. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  103579. var _this = this;
  103580. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  103581. // labs feature - flashlight
  103582. if (this.configuration.lab && this.configuration.lab.flashlight) {
  103583. var pointerPosition = babylonjs_1.Vector3.Zero();
  103584. var lightTarget_1;
  103585. var angle = 0.5;
  103586. var exponent = Math.PI / 2;
  103587. if (typeof this.configuration.lab.flashlight === "object") {
  103588. exponent = this.configuration.lab.flashlight.exponent || exponent;
  103589. angle = this.configuration.lab.flashlight.angle || angle;
  103590. }
  103591. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  103592. if (typeof this.configuration.lab.flashlight === "object") {
  103593. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  103594. if (this.configuration.lab.flashlight.diffuse) {
  103595. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  103596. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  103597. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  103598. }
  103599. if (this.configuration.lab.flashlight.specular) {
  103600. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  103601. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  103602. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  103603. }
  103604. }
  103605. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  103606. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  103607. if (eventData.type === 4 && eventData.pickInfo) {
  103608. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  103609. }
  103610. else {
  103611. lightTarget_1 = undefined;
  103612. }
  103613. });
  103614. var updateFlashlightFunction = function () {
  103615. if (_this.sceneManager.camera && flashlight) {
  103616. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  103617. if (lightTarget_1) {
  103618. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  103619. }
  103620. }
  103621. };
  103622. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  103623. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  103624. }
  103625. };
  103626. return DefaultViewer;
  103627. }(viewer_1.AbstractViewer));
  103628. exports.DefaultViewer = DefaultViewer;
  103629. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdFZpZXdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvZGVmYXVsdFZpZXdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFJQSxtQ0FBMEM7QUFDMUMsdUNBQXNZO0FBTXRZOzs7R0FHRztBQUNIO0lBQW1DLGlDQUFjO0lBSTdDOzs7O09BSUc7SUFDSCx1QkFBbUIsZ0JBQTZCLEVBQUUsb0JBQWtFO1FBQWxFLHFDQUFBLEVBQUEseUJBQThDLE9BQU8sRUFBRSxTQUFTLEVBQUU7UUFBcEgsWUFDSSxrQkFBTSxnQkFBZ0IsRUFBRSxvQkFBb0IsQ0FBQyxTQVloRDtRQWJrQixzQkFBZ0IsR0FBaEIsZ0JBQWdCLENBQWE7UUFrR3hDLHdCQUFrQixHQUFHLFVBQUMsS0FBb0I7WUFFOUMsSUFBSSxXQUFXLEdBQWlCLEtBQUssQ0FBQyxLQUFLLENBQUM7WUFDNUMsSUFBSSxXQUFXLENBQUMsTUFBTSxLQUFLLENBQUM7Z0JBQUUsT0FBTztZQUNyQyxJQUFJLE9BQU8sR0FBaUIsS0FBSyxDQUFDLEtBQUssQ0FBQyxNQUFPLENBQUM7WUFFaEQsSUFBSSxDQUFDLE9BQU8sRUFBRTtnQkFDVixPQUFPO2FBQ1Y7WUFFRC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0FBQyxHQUFHLENBQUMsVUFBQyxTQUFTLEVBQUUsVUFBVTtnQkFDbEUsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLENBQUMsSUFBSSxTQUFTLENBQUMsUUFBUSxFQUFFO29CQUM1QyxhQUFXLEdBQUcsQ0FBQyxTQUFTLENBQUMsUUFBUSxDQUFDLFdBQVcsQ0FBQyxDQUFDO2lCQUNsRDtxQkFBTTtvQkFDSCxhQUFXLEdBQUcsU0FBUyxDQUFDO2lCQUMzQjtZQUNMLENBQUMsQ0FBQyxDQUFDO1lBQ0gsSUFBSSx3QkFBd0IsR0FBRztnQkFDM0IsSUFBSSxLQUFJLENBQUMsWUFBWSxDQUFDLE1BQU0sSUFBSSxVQUFVLEVBQUU7b0JBQ3hDLFVBQVUsQ0FBQyxRQUFRLENBQUMsUUFBUSxDQUFDLEtBQUksQ0FBQyxZQUFZLENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxDQUFDO29CQUNoRSxJQUFJLGFBQVcsRUFBRTt3QkFDYixhQUFXLENBQUMsYUFBYSxDQUFDLFVBQVUsQ0FBQyxRQUFRLEVBQUUsVUFBVSxDQUFDLFNBQVMsQ0FBQyxDQUFDO3FCQUN4RTtpQkFDSjtZQUNMLENBQUMsQ0FBQTtZQUNELElBQUksQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLG9CQUFvQixDQUFDLHdCQUF3QixDQUFDLENBQUM7WUFDdkUsSUFBSSxDQUFDLGtDQUFrQyxDQUFDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxDQUFDO1NBQzFFO0lBQ0wsQ0FBQztJQUNMLG9CQUFDO0FBQUQsQ0FBQyxBQXJsQkQsQ0FBbUMsdUJBQWMsR0FxbEJoRDtBQXJsQlksc0NBQWEifQ==
  103630. /***/ }),
  103631. /* 9 */
  103632. /***/ (function(module, exports, __webpack_require__) {
  103633. "use strict";
  103634. Object.defineProperty(exports, "__esModule", { value: true });
  103635. var viewerManager_1 = __webpack_require__(7);
  103636. var sceneManager_1 = __webpack_require__(22);
  103637. var loader_1 = __webpack_require__(28);
  103638. var babylonjs_1 = __webpack_require__(0);
  103639. var modelLoader_1 = __webpack_require__(13);
  103640. var globals_1 = __webpack_require__(4);
  103641. var telemetryManager_1 = __webpack_require__(6);
  103642. var _1 = __webpack_require__(1);
  103643. var observablesManager_1 = __webpack_require__(59);
  103644. var configurationContainer_1 = __webpack_require__(60);
  103645. var templateManager_1 = __webpack_require__(61);
  103646. /**
  103647. * The AbstractViewr is the center of Babylon's viewer.
  103648. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  103649. */
  103650. var AbstractViewer = /** @class */ (function () {
  103651. function AbstractViewer(containerElement, initialConfiguration) {
  103652. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  103653. var _this = this;
  103654. this.containerElement = containerElement;
  103655. /**
  103656. * A flag that controls whether or not the render loop should be executed
  103657. */
  103658. this.runRenderLoop = true;
  103659. /**
  103660. * is this viewer disposed?
  103661. */
  103662. this._isDisposed = false;
  103663. this._hdToggled = false;
  103664. /**
  103665. * The resize function that will be registered with the window object
  103666. */
  103667. this._resize = function () {
  103668. // Only resize if Canvas is in the DOM
  103669. if (!_this.isCanvasInDOM()) {
  103670. return;
  103671. }
  103672. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  103673. return;
  103674. }
  103675. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  103676. return;
  103677. }
  103678. _this.engine.resize();
  103679. };
  103680. /**
  103681. * render loop that will be executed by the engine
  103682. */
  103683. this._render = function (force) {
  103684. if (force === void 0) { force = false; }
  103685. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  103686. if (_this.runRenderLoop || force) {
  103687. _this.engine.performanceMonitor.enable();
  103688. _this.sceneManager.scene.render();
  103689. _this.onFrameRenderedObservable.notifyObservers(_this);
  103690. }
  103691. else {
  103692. _this.engine.performanceMonitor.disable();
  103693. // update camera instead of rendering
  103694. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  103695. }
  103696. }
  103697. };
  103698. // if exists, use the container id. otherwise, generate a random string.
  103699. if (containerElement.id) {
  103700. this.baseId = containerElement.id;
  103701. }
  103702. else {
  103703. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  103704. }
  103705. this._registeredOnBeforeRenderFunctions = [];
  103706. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  103707. // add this viewer to the viewer manager
  103708. viewerManager_1.viewerManager.addViewer(this);
  103709. this.observablesManager = new observablesManager_1.ObservablesManager();
  103710. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  103711. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  103712. // extend the configuration
  103713. this._configurationLoader = new loader_1.ConfigurationLoader();
  103714. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  103715. _this._onConfigurationLoaded(configuration);
  103716. });
  103717. this.onSceneInitObservable.add(function () {
  103718. _this.updateConfiguration();
  103719. });
  103720. this.onInitDoneObservable.add(function () {
  103721. _this._isInit = true;
  103722. _this.engine.runRenderLoop(_this._render);
  103723. });
  103724. this._prepareContainerElement();
  103725. }
  103726. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  103727. // observables
  103728. /**
  103729. * Will notify when the scene was initialized
  103730. */
  103731. get: function () {
  103732. return this.observablesManager.onSceneInitObservable;
  103733. },
  103734. enumerable: true,
  103735. configurable: true
  103736. });
  103737. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  103738. /**
  103739. * will notify when the engine was initialized
  103740. */
  103741. get: function () {
  103742. return this.observablesManager.onEngineInitObservable;
  103743. },
  103744. enumerable: true,
  103745. configurable: true
  103746. });
  103747. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  103748. /**
  103749. * Will notify when a new model was added to the scene.
  103750. * Note that added does not neccessarily mean loaded!
  103751. */
  103752. get: function () {
  103753. return this.observablesManager.onModelAddedObservable;
  103754. },
  103755. enumerable: true,
  103756. configurable: true
  103757. });
  103758. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  103759. /**
  103760. * will notify after every model load
  103761. */
  103762. get: function () {
  103763. return this.observablesManager.onModelLoadedObservable;
  103764. },
  103765. enumerable: true,
  103766. configurable: true
  103767. });
  103768. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  103769. /**
  103770. * will notify when any model notify of progress
  103771. */
  103772. get: function () {
  103773. return this.observablesManager.onModelLoadProgressObservable;
  103774. },
  103775. enumerable: true,
  103776. configurable: true
  103777. });
  103778. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  103779. /**
  103780. * will notify when any model load failed.
  103781. */
  103782. get: function () {
  103783. return this.observablesManager.onModelLoadErrorObservable;
  103784. },
  103785. enumerable: true,
  103786. configurable: true
  103787. });
  103788. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  103789. /**
  103790. * Will notify when a model was removed from the scene;
  103791. */
  103792. get: function () {
  103793. return this.observablesManager.onModelRemovedObservable;
  103794. },
  103795. enumerable: true,
  103796. configurable: true
  103797. });
  103798. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  103799. /**
  103800. * will notify when a new loader was initialized.
  103801. * Used mainly to know when a model starts loading.
  103802. */
  103803. get: function () {
  103804. return this.observablesManager.onLoaderInitObservable;
  103805. },
  103806. enumerable: true,
  103807. configurable: true
  103808. });
  103809. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  103810. /**
  103811. * Observers registered here will be executed when the entire load process has finished.
  103812. */
  103813. get: function () {
  103814. return this.observablesManager.onViewerInitDoneObservable;
  103815. },
  103816. enumerable: true,
  103817. configurable: true
  103818. });
  103819. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  103820. /**
  103821. * Functions added to this observable will be executed on each frame rendered.
  103822. */
  103823. get: function () {
  103824. return this.observablesManager.onFrameRenderedObservable;
  103825. },
  103826. enumerable: true,
  103827. configurable: true
  103828. });
  103829. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  103830. /**
  103831. * The (single) canvas of this viewer
  103832. */
  103833. get: function () {
  103834. return this._canvas;
  103835. },
  103836. enumerable: true,
  103837. configurable: true
  103838. });
  103839. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  103840. get: function () {
  103841. return this._configurationContainer;
  103842. },
  103843. enumerable: true,
  103844. configurable: true
  103845. });
  103846. /**
  103847. * get the baseId of this viewer
  103848. */
  103849. AbstractViewer.prototype.getBaseId = function () {
  103850. return this.baseId;
  103851. };
  103852. /**
  103853. * Do we have a canvas to render on, and is it a part of the scene
  103854. */
  103855. AbstractViewer.prototype.isCanvasInDOM = function () {
  103856. return !!this._canvas && !!this._canvas.parentElement;
  103857. };
  103858. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  103859. /**
  103860. * Is the engine currently set to rende even when the page is in background
  103861. */
  103862. get: function () {
  103863. return this.engine && this.engine.renderEvenInBackground;
  103864. },
  103865. /**
  103866. * Set the viewer's background rendering flag.
  103867. */
  103868. set: function (value) {
  103869. if (this.engine) {
  103870. this.engine.renderEvenInBackground = value;
  103871. }
  103872. },
  103873. enumerable: true,
  103874. configurable: true
  103875. });
  103876. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  103877. /**
  103878. * Get the configuration object. This is a reference only.
  103879. * The configuration can ONLY be updated using the updateConfiguration function.
  103880. * changing this object will have no direct effect on the scene.
  103881. */
  103882. get: function () {
  103883. return this._configurationContainer.configuration;
  103884. },
  103885. enumerable: true,
  103886. configurable: true
  103887. });
  103888. /**
  103889. * force resizing the engine.
  103890. */
  103891. AbstractViewer.prototype.forceResize = function () {
  103892. this._resize();
  103893. };
  103894. AbstractViewer.prototype.toggleHD = function () {
  103895. this._hdToggled = !this._hdToggled;
  103896. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  103897. this.engine.setHardwareScalingLevel(scale);
  103898. };
  103899. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  103900. var _this = this;
  103901. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  103902. if (this.configuration.observers) {
  103903. this._configureObservers(this.configuration.observers);
  103904. }
  103905. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  103906. if (this.configuration.loaderPlugins) {
  103907. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  103908. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  103909. _this.modelLoader.addPlugin(name);
  103910. }
  103911. }));
  103912. }
  103913. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  103914. };
  103915. /**
  103916. * Force a single render loop execution.
  103917. */
  103918. AbstractViewer.prototype.forceRender = function () {
  103919. this._render(true);
  103920. };
  103921. /**
  103922. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  103923. * @param callback optional callback that will be triggered when screenshot is done.
  103924. * @param width Optional screenshot width (default to 512).
  103925. * @param height Optional screenshot height (default to 512).
  103926. * @returns a promise with the screenshot data
  103927. */
  103928. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  103929. var _this = this;
  103930. if (width === void 0) { width = 0; }
  103931. if (height === void 0) { height = 0; }
  103932. width = width || this.canvas.clientWidth;
  103933. height = height || this.canvas.clientHeight;
  103934. // Create the screenshot
  103935. return new Promise(function (resolve, reject) {
  103936. try {
  103937. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  103938. if (callback) {
  103939. callback(data);
  103940. }
  103941. resolve(data);
  103942. });
  103943. }
  103944. catch (e) {
  103945. reject(e);
  103946. }
  103947. });
  103948. };
  103949. /**
  103950. * Update the current viewer configuration with new values.
  103951. * Only provided information will be updated, old configuration values will be kept.
  103952. * If this.configuration was manually changed, you can trigger this function with no parameters,
  103953. * and the entire configuration will be updated.
  103954. * @param newConfiguration the partial configuration to update
  103955. *
  103956. */
  103957. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  103958. var _this = this;
  103959. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  103960. // update this.configuration with the new data
  103961. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  103962. this.sceneManager.updateConfiguration(newConfiguration);
  103963. // observers in configuration
  103964. if (newConfiguration.observers) {
  103965. this._configureObservers(newConfiguration.observers);
  103966. }
  103967. if (newConfiguration.loaderPlugins) {
  103968. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  103969. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  103970. _this.modelLoader.addPlugin(name);
  103971. }
  103972. }));
  103973. }
  103974. };
  103975. /**
  103976. * this is used to register native functions using the configuration object.
  103977. * This will configure the observers.
  103978. * @param observersConfiguration observers configuration
  103979. */
  103980. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  103981. if (observersConfiguration.onEngineInit) {
  103982. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  103983. }
  103984. else {
  103985. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  103986. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  103987. }
  103988. }
  103989. if (observersConfiguration.onSceneInit) {
  103990. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  103991. }
  103992. else {
  103993. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  103994. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  103995. }
  103996. }
  103997. if (observersConfiguration.onModelLoaded) {
  103998. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  103999. }
  104000. else {
  104001. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  104002. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  104003. }
  104004. }
  104005. };
  104006. /**
  104007. * Dispoe the entire viewer including the scene and the engine
  104008. */
  104009. AbstractViewer.prototype.dispose = function () {
  104010. if (this._isDisposed) {
  104011. return;
  104012. }
  104013. window.removeEventListener('resize', this._resize);
  104014. if (this.sceneManager) {
  104015. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  104016. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  104017. }
  104018. this.sceneManager.dispose();
  104019. }
  104020. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  104021. this.observablesManager.dispose();
  104022. this.modelLoader.dispose();
  104023. if (this.engine) {
  104024. this.engine.dispose();
  104025. }
  104026. viewerManager_1.viewerManager.removeViewer(this);
  104027. this._isDisposed = true;
  104028. };
  104029. /**
  104030. * This function will execute when the HTML templates finished initializing.
  104031. * It should initialize the engine and continue execution.
  104032. *
  104033. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  104034. */
  104035. AbstractViewer.prototype._onTemplatesLoaded = function () {
  104036. return Promise.resolve(this);
  104037. };
  104038. /**
  104039. * This will force the creation of an engine and a scene.
  104040. * It will also load a model if preconfigured.
  104041. * But first - it will load the extendible onTemplateLoaded()!
  104042. */
  104043. AbstractViewer.prototype._onTemplateLoaded = function () {
  104044. var _this = this;
  104045. // check if viewer was disposed right after created
  104046. if (this._isDisposed) {
  104047. return Promise.reject("viewer was disposed");
  104048. }
  104049. return this._onTemplatesLoaded().then(function () {
  104050. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  104051. return _this._initEngine().then(function (engine) {
  104052. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  104053. }).then(function () {
  104054. _this._initTelemetryEvents();
  104055. if (autoLoad) {
  104056. return _this.loadModel(_this.configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  104057. }
  104058. else {
  104059. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  104060. }
  104061. }).then(function () {
  104062. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  104063. }).catch(function (e) {
  104064. babylonjs_1.Tools.Warn(e.toString());
  104065. return _this;
  104066. });
  104067. });
  104068. };
  104069. /**
  104070. * Initialize the engine. Retruns a promise in case async calls are needed.
  104071. *
  104072. * @protected
  104073. * @returns {Promise<Engine>}
  104074. * @memberof Viewer
  104075. */
  104076. AbstractViewer.prototype._initEngine = function () {
  104077. // init custom shaders
  104078. this._injectCustomShaders();
  104079. //let canvasElement = this.templateManager.getCanvas();
  104080. if (!this.canvas) {
  104081. return Promise.reject('Canvas element not found!');
  104082. }
  104083. var config = this.configuration.engine || {};
  104084. // TDO enable further configuration
  104085. // check for webgl2 support, force-disable if needed.
  104086. if (globals_1.viewerGlobals.disableWebGL2Support) {
  104087. config.engineOptions = config.engineOptions || {};
  104088. config.engineOptions.disableWebGL2Support = true;
  104089. }
  104090. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  104091. // Disable manifest checking
  104092. babylonjs_1.Database.IDBStorageEnabled = false;
  104093. if (!config.disableResize) {
  104094. window.addEventListener('resize', this._resize);
  104095. }
  104096. if (this.configuration.engine) {
  104097. if (this.configuration.engine.adaptiveQuality) {
  104098. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  104099. this.engine.setHardwareScalingLevel(scale);
  104100. }
  104101. if (this.configuration.engine.hdEnabled) {
  104102. this.toggleHD();
  104103. }
  104104. }
  104105. // create a new template manager for this viewer
  104106. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  104107. return Promise.resolve(this.engine);
  104108. };
  104109. /**
  104110. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  104111. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  104112. *
  104113. * @param modelConfig model configuration to use when loading the model.
  104114. * @param clearScene should the scene be cleared before loading this model
  104115. * @returns a ViewerModel object that is not yet fully loaded.
  104116. */
  104117. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  104118. var _this = this;
  104119. if (clearScene === void 0) { clearScene = true; }
  104120. var configuration;
  104121. if (typeof modelConfig === 'string') {
  104122. configuration = {
  104123. url: modelConfig
  104124. };
  104125. }
  104126. else if (modelConfig instanceof File) {
  104127. configuration = {
  104128. file: modelConfig,
  104129. root: "file:"
  104130. };
  104131. }
  104132. else {
  104133. configuration = modelConfig;
  104134. }
  104135. if (!configuration.url && !configuration.file) {
  104136. throw new Error("no model provided");
  104137. }
  104138. if (clearScene) {
  104139. this.sceneManager.clearScene(true, false);
  104140. }
  104141. //merge the configuration for future models:
  104142. if (this.configuration.model && typeof this.configuration.model === 'object') {
  104143. var globalConfig = _1.deepmerge({}, this.configuration.model);
  104144. configuration = _1.deepmerge(globalConfig, configuration);
  104145. if (modelConfig instanceof File) {
  104146. configuration.file = modelConfig;
  104147. }
  104148. }
  104149. else {
  104150. this.configuration.model = configuration;
  104151. }
  104152. this._isLoading = true;
  104153. var model = this.modelLoader.load(configuration);
  104154. this.lastUsedLoader = model.loader;
  104155. model.onLoadErrorObservable.add(function (errorObject) {
  104156. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  104157. });
  104158. model.onLoadProgressObservable.add(function (progressEvent) {
  104159. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104160. });
  104161. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  104162. model.onLoadedObservable.add(function () {
  104163. _this._isLoading = false;
  104164. });
  104165. return model;
  104166. };
  104167. /**
  104168. * load a model using the provided configuration.
  104169. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  104170. * If you want to attach to the observables of the model, use initModle instead.
  104171. *
  104172. * @param modelConfig the model configuration or URL to load.
  104173. * @param clearScene Should the scene be cleared before loading the model
  104174. * @returns a Promise the fulfills when the model finished loading successfully.
  104175. */
  104176. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  104177. var _this = this;
  104178. if (clearScene === void 0) { clearScene = true; }
  104179. if (this._isLoading) {
  104180. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  104181. return Promise.reject("another model is curently being loaded.");
  104182. }
  104183. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  104184. if (!scene)
  104185. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  104186. return scene;
  104187. }).then(function () {
  104188. var model = _this.initModel(modelConfig, clearScene);
  104189. return new Promise(function (resolve, reject) {
  104190. // at this point, configuration.model is an object, not a string
  104191. model.onLoadedObservable.add(function () {
  104192. resolve(model);
  104193. });
  104194. model.onLoadErrorObservable.add(function (error) {
  104195. reject(error);
  104196. });
  104197. });
  104198. });
  104199. };
  104200. AbstractViewer.prototype._initTelemetryEvents = function () {
  104201. var _this = this;
  104202. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  104203. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  104204. userAgent: navigator.userAgent,
  104205. platform: navigator.platform
  104206. });
  104207. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  104208. var trackFPS = function () {
  104209. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  104210. };
  104211. trackFPS();
  104212. // Track the FPS again after 60 seconds
  104213. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  104214. };
  104215. /**
  104216. * Injects all the spectre shader in the babylon shader store
  104217. */
  104218. AbstractViewer.prototype._injectCustomShaders = function () {
  104219. var customShaders = this.configuration.customShaders;
  104220. // Inject all the spectre shader in the babylon shader store.
  104221. if (!customShaders) {
  104222. return;
  104223. }
  104224. if (customShaders.shaders) {
  104225. Object.keys(customShaders.shaders).forEach(function (key) {
  104226. // typescript considers a callback "unsafe", so... '!'
  104227. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  104228. });
  104229. }
  104230. if (customShaders.includes) {
  104231. Object.keys(customShaders.includes).forEach(function (key) {
  104232. // typescript considers a callback "unsafe", so... '!'
  104233. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  104234. });
  104235. }
  104236. };
  104237. return AbstractViewer;
  104238. }());
  104239. exports.AbstractViewer = AbstractViewer;
  104240. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5RCx1Q0FBbWdCO0FBS25nQixxREFBb0Q7QUFFcEQsb0RBQXlEO0FBRXpELGlFQUFnRTtBQUNoRSwrQkFBdUM7QUFDdkMscUVBQW9FO0FBQ3BFLGtGQUFpRjtBQUNqRixpRUFBZ0U7QUFFaEU7OztHQUdHO0FBQ0g7SUFnSkksd0JBQW1CLGdCQUE2QixFQUFFLG9CQUE4QztRQUE5QyxxQ0FBQSxFQUFBLHlCQUE4QztRQUFoRyxpQkFzQ0M7UUF0Q2tCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQXJIaEQ7O1dBRUc7UUFDSSxrQkFBYSxHQUFZLElBQUksQ0FBQztRQXdGckM7O1dBRUc7UUFDTyxnQkFBVyxHQUFZLEtBQUssQ0FBQztRQTZHN0IsZUFBVSxHQUFZLEtBQUssQ0FBQztRQVV0Qzs7V0FFRztRQUNPLFlBQU8sR0FBRztZQUNoQixzQ0FBc0M7WUFDdEMsSUFBSSxDQUFDLEtBQUksQ0FBQyxhQUFhLEVBQUUsRUFBRTtnQkFDdkIsT0FBTzthQUNWO1lBRUQsSUFBSSxLQUFJLENBQUMsTUFBTSxDQUFDLFdBQVcsSUFBSSxDQUFDLElBQUksS0FBSSxDQUFDLE1BQU0sQ0FBQyxZQUFZLElBQUksQ0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xDQUFDO1lBQzVELENBQUMsQ0FBQyxDQUFDO1NBQ047UUFDRCxJQUFJLGFBQWEsQ0FBQyxRQUFRLEVBQUU7WUFDeEIsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsUUFBUSxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsR0FBRztnQkFDM0Msc0RBQXNEO2dCQUN0RCxrQkFBTSxDQUFDLG9CQUFvQixDQUFDLEdBQUcsQ0FBQyxHQUFHLGFBQWMsQ0FBQyxRQUFTLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckUsQ0FBQyxDQUFDLENBQUM7U0FDTjtJQUNMLENBQUM7SUFDTCxxQkFBQztBQUFELENBQUMsQUE3b0JELElBNm9CQztBQTdvQnFCLHdDQUFjIn0=
  104241. /***/ }),
  104242. /* 10 */
  104243. /***/ (function(module, exports, __webpack_require__) {
  104244. "use strict";
  104245. function __export(m) {
  104246. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  104247. }
  104248. Object.defineProperty(exports, "__esModule", { value: true });
  104249. __export(__webpack_require__(11));
  104250. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  104251. /***/ }),
  104252. /* 11 */
  104253. /***/ (function(module, exports, __webpack_require__) {
  104254. "use strict";
  104255. Object.defineProperty(exports, "__esModule", { value: true });
  104256. function getConfigurationKey(key, configObject) {
  104257. var splits = key.split('.');
  104258. if (splits.length === 0 || !configObject)
  104259. return;
  104260. else if (splits.length === 1) {
  104261. if (configObject[key] !== undefined) {
  104262. return configObject[key];
  104263. }
  104264. }
  104265. else {
  104266. var firstKey = splits.shift();
  104267. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  104268. }
  104269. }
  104270. exports.getConfigurationKey = getConfigurationKey;
  104271. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  104272. /***/ }),
  104273. /* 12 */
  104274. /***/ (function(module, exports, __webpack_require__) {
  104275. "use strict";
  104276. Object.defineProperty(exports, "__esModule", { value: true });
  104277. var babylonjs_1 = __webpack_require__(0);
  104278. /**
  104279. * A minimal WebGL cubemap descriptor
  104280. */
  104281. var TextureCube = /** @class */ (function () {
  104282. /**
  104283. * constructor
  104284. * @param internalFormat WebGL pixel format for the texture on the GPU
  104285. * @param type WebGL pixel type of the supplied data and texture on the GPU
  104286. * @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
  104287. */
  104288. function TextureCube(internalFormat, type, source) {
  104289. if (source === void 0) { source = []; }
  104290. this.internalFormat = internalFormat;
  104291. this.type = type;
  104292. this.source = source;
  104293. }
  104294. Object.defineProperty(TextureCube.prototype, "Width", {
  104295. /**
  104296. * Returns the width of a face of the texture or 0 if not available
  104297. */
  104298. get: function () {
  104299. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  104300. },
  104301. enumerable: true,
  104302. configurable: true
  104303. });
  104304. Object.defineProperty(TextureCube.prototype, "Height", {
  104305. /**
  104306. * Returns the height of a face of the texture or 0 if not available
  104307. */
  104308. get: function () {
  104309. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  104310. },
  104311. enumerable: true,
  104312. configurable: true
  104313. });
  104314. return TextureCube;
  104315. }());
  104316. exports.TextureCube = TextureCube;
  104317. /**
  104318. * A static class providing methods to aid working with Bablyon textures.
  104319. */
  104320. var TextureUtils = /** @class */ (function () {
  104321. function TextureUtils() {
  104322. }
  104323. /**
  104324. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  104325. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  104326. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  104327. * @param scene A Babylon Scene instance
  104328. * @param textureCube A Spectre TextureCube object
  104329. * @param parameters WebGL texture sampling parameters
  104330. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  104331. * @param environment Specifies that the texture will be used as an environment
  104332. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  104333. * @return Babylon cube texture
  104334. */
  104335. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  104336. if (environment === void 0) { environment = false; }
  104337. if (singleLod === void 0) { singleLod = false; }
  104338. if (!textureCube)
  104339. throw new Error("no texture cube provided");
  104340. var parameters;
  104341. if (environment) {
  104342. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  104343. }
  104344. else {
  104345. parameters = {
  104346. magFilter: 9728 /* NEAREST */,
  104347. minFilter: 9728 /* NEAREST */,
  104348. wrapS: 33071 /* CLAMP_TO_EDGE */,
  104349. wrapT: 33071 /* CLAMP_TO_EDGE */
  104350. };
  104351. }
  104352. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  104353. var babylonTexture = textureCube[key];
  104354. if (!babylonTexture) {
  104355. //initialize babylon texture
  104356. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  104357. if (environment) {
  104358. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  104359. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  104360. }
  104361. babylonTexture.gammaSpace = false;
  104362. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  104363. var glTexture_1 = internalTexture_1._webGLTexture;
  104364. //babylon properties
  104365. internalTexture_1.isCube = true;
  104366. internalTexture_1.generateMipMaps = false;
  104367. babylonTexture._texture = internalTexture_1;
  104368. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  104369. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  104370. var texturesUploaded_1 = 0;
  104371. var textureComplete = function () {
  104372. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  104373. };
  104374. var uploadFace = function (i, level, face) {
  104375. if (!glTexture_1)
  104376. return;
  104377. if (i === 0 && level === 0) {
  104378. internalTexture_1.width = face.width;
  104379. internalTexture_1.height = face.height;
  104380. }
  104381. var gl = (scene.getEngine())._gl;
  104382. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  104383. scene.getEngine()._unpackFlipY(false);
  104384. if (face instanceof HTMLElement || face instanceof ImageData) {
  104385. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  104386. }
  104387. else {
  104388. var textureData = face;
  104389. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  104390. }
  104391. texturesUploaded_1++;
  104392. if (textureComplete()) {
  104393. //generate mipmaps
  104394. if (automaticMipmaps) {
  104395. var w = face.width;
  104396. var h = face.height;
  104397. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  104398. if (isPot) {
  104399. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  104400. }
  104401. }
  104402. // Upload Separate lods in case there is no support for texture lod.
  104403. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  104404. var mipSlices = 3;
  104405. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  104406. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  104407. var lod = textureCube[lodKey];
  104408. //initialize lod texture if it doesn't already exist
  104409. if (lod == null && textureCube.Width) {
  104410. //compute LOD from even spacing in smoothness (matching shader calculation)
  104411. var smoothness = i_1 / (mipSlices - 1);
  104412. var roughness = 1 - smoothness;
  104413. var kMinimumVariance = 0.0005;
  104414. var alphaG = roughness * roughness + kMinimumVariance;
  104415. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  104416. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  104417. var maxLODIndex = textureCube.source.length - 1;
  104418. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  104419. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  104420. if (i_1 === 0) {
  104421. internalTexture_1._lodTextureLow = lod;
  104422. }
  104423. else if (i_1 === 1) {
  104424. internalTexture_1._lodTextureMid = lod;
  104425. }
  104426. else {
  104427. internalTexture_1._lodTextureHigh = lod;
  104428. }
  104429. textureCube[lodKey] = lod;
  104430. }
  104431. }
  104432. }
  104433. internalTexture_1.isReady = true;
  104434. }
  104435. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  104436. scene.getEngine().resetTextureCache();
  104437. };
  104438. var _loop_1 = function (i) {
  104439. var faces = textureCube.source[i];
  104440. var _loop_2 = function (j) {
  104441. var face = faces[j];
  104442. if (face instanceof HTMLImageElement && !face.complete) {
  104443. face.addEventListener('load', function () {
  104444. uploadFace(j, i, face);
  104445. }, false);
  104446. }
  104447. else {
  104448. uploadFace(j, i, face);
  104449. }
  104450. };
  104451. for (var j = 0; j < faces.length; j++) {
  104452. _loop_2(j);
  104453. }
  104454. };
  104455. for (var i = 0; i <= maxMipLevel_1; i++) {
  104456. _loop_1(i);
  104457. }
  104458. scene.getEngine().resetTextureCache();
  104459. babylonTexture.isReady = function () {
  104460. return textureComplete();
  104461. };
  104462. textureCube[key] = babylonTexture;
  104463. }
  104464. return babylonTexture;
  104465. };
  104466. /**
  104467. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  104468. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  104469. * @param parameters Spectre SamplingParameters to apply
  104470. */
  104471. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  104472. var scene = babylonTexture.getScene();
  104473. if (!scene)
  104474. return;
  104475. var gl = (scene.getEngine())._gl;
  104476. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  104477. var internalTexture = babylonTexture._texture;
  104478. if (!internalTexture)
  104479. return;
  104480. var glTexture = internalTexture._webGLTexture;
  104481. gl.bindTexture(target, glTexture);
  104482. if (parameters.magFilter != null)
  104483. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  104484. if (parameters.minFilter != null)
  104485. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  104486. if (parameters.wrapS != null)
  104487. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  104488. if (parameters.wrapT != null)
  104489. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  104490. //set babylon wrap modes from sampling parameter
  104491. switch (parameters.wrapS) {
  104492. case 10497 /* REPEAT */:
  104493. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  104494. break;
  104495. case 33071 /* CLAMP_TO_EDGE */:
  104496. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104497. break;
  104498. case 33648 /* MIRRORED_REPEAT */:
  104499. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  104500. break;
  104501. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104502. }
  104503. switch (parameters.wrapT) {
  104504. case 10497 /* REPEAT */:
  104505. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  104506. break;
  104507. case 33071 /* CLAMP_TO_EDGE */:
  104508. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104509. break;
  104510. case 33648 /* MIRRORED_REPEAT */:
  104511. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  104512. break;
  104513. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104514. }
  104515. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  104516. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  104517. if (anisotropicExt) {
  104518. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  104519. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  104520. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  104521. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  104522. }
  104523. }
  104524. gl.bindTexture(target, null);
  104525. scene.getEngine().resetTextureCache();
  104526. };
  104527. /**
  104528. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  104529. */
  104530. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  104531. /**
  104532. * Controls anisotropic filtering for deserialized textures.
  104533. */
  104534. TextureUtils.MaxAnisotropy = 4;
  104535. TextureUtils._EnvironmentSampling = {
  104536. magFilter: 9729 /* LINEAR */,
  104537. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  104538. wrapS: 33071 /* CLAMP_TO_EDGE */,
  104539. wrapT: 33071 /* CLAMP_TO_EDGE */,
  104540. maxAnisotropy: 1
  104541. };
  104542. TextureUtils._EnvironmentSingleMipSampling = {
  104543. magFilter: 9729 /* LINEAR */,
  104544. minFilter: 9729 /* LINEAR */,
  104545. wrapS: 33071 /* CLAMP_TO_EDGE */,
  104546. wrapT: 33071 /* CLAMP_TO_EDGE */,
  104547. maxAnisotropy: 1
  104548. };
  104549. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  104550. /**
  104551. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  104552. */
  104553. TextureUtils.EnvironmentLODScale = 0.8;
  104554. /**
  104555. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  104556. */
  104557. TextureUtils.EnvironmentLODOffset = 1.0;
  104558. return TextureUtils;
  104559. }());
  104560. exports.TextureUtils = TextureUtils;
  104561. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV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ztDQUFBLEFBMVBELElBMFBDO0FBMVBZLG9DQUFZIn0=
  104562. /***/ }),
  104563. /* 13 */
  104564. /***/ (function(module, exports, __webpack_require__) {
  104565. "use strict";
  104566. Object.defineProperty(exports, "__esModule", { value: true });
  104567. var babylonjs_1 = __webpack_require__(0);
  104568. var babylonjs_loaders_1 = __webpack_require__(14);
  104569. var viewerModel_1 = __webpack_require__(5);
  104570. var _1 = __webpack_require__(54);
  104571. /**
  104572. * An instance of the class is in charge of loading the model correctly.
  104573. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  104574. *
  104575. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  104576. */
  104577. var ModelLoader = /** @class */ (function () {
  104578. /**
  104579. * Create a new Model loader
  104580. * @param _viewer the viewer using this model loader
  104581. */
  104582. function ModelLoader(_observablesManager, _configurationContainer) {
  104583. this._observablesManager = _observablesManager;
  104584. this._configurationContainer = _configurationContainer;
  104585. this._disposed = false;
  104586. this._loaders = [];
  104587. this._loadId = 0;
  104588. this._plugins = [];
  104589. }
  104590. /**
  104591. * Adds a new plugin to the loader process.
  104592. *
  104593. * @param plugin the plugin name or the plugin itself
  104594. */
  104595. ModelLoader.prototype.addPlugin = function (plugin) {
  104596. var actualPlugin = {};
  104597. if (typeof plugin === 'string') {
  104598. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  104599. if (loadedPlugin) {
  104600. actualPlugin = loadedPlugin;
  104601. }
  104602. }
  104603. else {
  104604. actualPlugin = plugin;
  104605. }
  104606. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  104607. this._plugins.push(actualPlugin);
  104608. }
  104609. };
  104610. /**
  104611. * Load a model using predefined configuration
  104612. * @param modelConfiguration the modelConfiguration to use to load the model
  104613. */
  104614. ModelLoader.prototype.load = function (modelConfiguration) {
  104615. var _this = this;
  104616. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration, this._configurationContainer);
  104617. model.loadId = this._loadId++;
  104618. if (!modelConfiguration.url) {
  104619. model.state = viewerModel_1.ModelState.ERROR;
  104620. babylonjs_1.Tools.Error("No URL provided");
  104621. return model;
  104622. }
  104623. var base;
  104624. var filename;
  104625. if (modelConfiguration.file) {
  104626. base = "file:";
  104627. filename = modelConfiguration.file;
  104628. }
  104629. else {
  104630. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  104631. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  104632. }
  104633. var plugin = modelConfiguration.loader;
  104634. var scene = model.rootMesh.getScene();
  104635. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  104636. meshes.forEach(function (mesh) {
  104637. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104638. model.addMesh(mesh);
  104639. });
  104640. model.particleSystems = particleSystems;
  104641. model.skeletons = skeletons;
  104642. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  104643. var animationGroup = animationGroups_1[_i];
  104644. model.addAnimationGroup(animationGroup);
  104645. }
  104646. _this._checkAndRun("onLoaded", model);
  104647. scene.executeWhenReady(function () {
  104648. model.onLoadedObservable.notifyObservers(model);
  104649. });
  104650. }, function (progressEvent) {
  104651. _this._checkAndRun("onProgress", progressEvent);
  104652. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104653. }, function (scene, m, exception) {
  104654. model.state = viewerModel_1.ModelState.ERROR;
  104655. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  104656. _this._checkAndRun("onError", m, exception);
  104657. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104658. }, plugin);
  104659. if (model.loader.name === "gltf") {
  104660. var gltfLoader_1 = model.loader;
  104661. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  104662. gltfLoader_1.compileMaterials = true;
  104663. if (!modelConfiguration.file) {
  104664. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  104665. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  104666. };
  104667. }
  104668. // if ground is set to "mirror":
  104669. if (this._configurationContainer
  104670. && this._configurationContainer.configuration
  104671. && this._configurationContainer.configuration.ground
  104672. && typeof this._configurationContainer.configuration.ground === 'object'
  104673. && this._configurationContainer.configuration.ground.mirror) {
  104674. gltfLoader_1.useClipPlane = true;
  104675. }
  104676. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  104677. gltfLoader_1[functionName].add(function (payload) {
  104678. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  104679. });
  104680. });
  104681. gltfLoader_1.onParsedObservable.add(function (data) {
  104682. if (data && data.json && data.json['asset']) {
  104683. model.loadInfo = data.json['asset'];
  104684. }
  104685. });
  104686. gltfLoader_1.onCompleteObservable.add(function () {
  104687. model.loaderDone = true;
  104688. });
  104689. }
  104690. else {
  104691. model.loaderDone = true;
  104692. }
  104693. this._checkAndRun("onInit", model.loader, model);
  104694. this._loaders.push(model.loader);
  104695. return model;
  104696. };
  104697. ModelLoader.prototype.cancelLoad = function (model) {
  104698. var loader = model.loader || this._loaders[model.loadId];
  104699. // ATM only available in the GLTF Loader
  104700. if (loader && loader.name === "gltf") {
  104701. var gltfLoader = loader;
  104702. gltfLoader.dispose();
  104703. model.state = viewerModel_1.ModelState.CANCELED;
  104704. }
  104705. else {
  104706. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  104707. }
  104708. };
  104709. /**
  104710. * dispose the model loader.
  104711. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  104712. */
  104713. ModelLoader.prototype.dispose = function () {
  104714. this._loaders.forEach(function (loader) {
  104715. if (loader.name === "gltf") {
  104716. loader.dispose();
  104717. }
  104718. });
  104719. this._loaders.length = 0;
  104720. this._disposed = true;
  104721. };
  104722. ModelLoader.prototype._checkAndRun = function (functionName) {
  104723. var _this = this;
  104724. var payload = [];
  104725. for (var _i = 1; _i < arguments.length; _i++) {
  104726. payload[_i - 1] = arguments[_i];
  104727. }
  104728. if (this._disposed)
  104729. return;
  104730. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  104731. try {
  104732. plugin[functionName].apply(_this, payload);
  104733. }
  104734. catch (e) { }
  104735. });
  104736. };
  104737. return ModelLoader;
  104738. }());
  104739. exports.ModelLoader = ModelLoader;
  104740. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbG9hZGVyL21vZGVsTG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQWtHO0FBQ2xHLHVEQUFpRjtBQUVqRixvREFBK0Q7QUFDL0QsK0JBQWtFO0FBSWxFOzs7OztHQUtHO0FBQ0g7SUFTSTs7O09BR0c7SUFDSCxxQkFBb0IsbUJBQXVDLEVBQVUsdUJBQWdEO1FBQWpHLHdCQUFtQixHQUFuQixtQkFBbUIsQ0FBb0I7UUFBVSw0QkFBdUIsR0FBdkIsdUJBQXVCLENBQXlCO1FBVjdHLGNBQVMsR0FBRyxLQUFLLENBQUM7UUFXdEIsSUFBSSxDQUFDLFFBQVEsR0FBRyxFQUFFLENBQUM7UUFDbkIsSUFBSSxDQUFDLE9BQU8sR0FBRyxDQUFDLENBQUM7UUFDakIsSUFBSSxDQUFDLFFBQVEsR0FBRyxFQUFFLENBQUM7SUFDdkIsQ0FBQztJQUVEOzs7O09BSUc7SUFDSSwrQkFBUyxHQUFoQixVQUFpQixNQUE4QjtRQUMzQyxJQUFJLFlBQVksR0FBa0IsRUFBRSxDQUFDO1FBQ3JDLElBQUksT0FBTyxNQUFNLEtBQUssUUFBUSxFQUFFO1lBQzVCL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QyxDQUFDLENBQUE7SUFDTixDQUFDO0lBQ0wsa0JBQUM7QUFBRCxDQUFDLEFBaExELElBZ0xDO0FBaExZLGtDQUFXIn0=
  104741. /***/ }),
  104742. /* 14 */
  104743. /***/ (function(module, exports, __webpack_require__) {
  104744. (function universalModuleDefinition(root, factory) {
  104745. var amdDependencies = [];
  104746. var BABYLON = root.BABYLON || this.BABYLON;
  104747. if(true) {
  104748. BABYLON = BABYLON || __webpack_require__(0);
  104749. module.exports = factory(BABYLON);
  104750. } else if(typeof define === 'function' && define.amd) {
  104751. amdDependencies.push("babylonjs");
  104752. define("babylonjs-loaders", amdDependencies, factory);
  104753. } else if(typeof exports === 'object') {
  104754. BABYLON = BABYLON || require("babylonjs");
  104755. exports["babylonjs-loaders"] = factory(BABYLON);
  104756. } else {
  104757. root["BABYLON"] = factory(BABYLON);
  104758. }
  104759. })(this, function(BABYLON) {
  104760. BABYLON = BABYLON || this.BABYLON;
  104761. 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};
  104762. 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)}}();
  104763. var BABYLON;
  104764. (function (BABYLON) {
  104765. var STLFileLoader = /** @class */ (function () {
  104766. function STLFileLoader() {
  104767. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  104768. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  104769. 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;
  104770. 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;
  104771. this.name = "stl";
  104772. // force data to come in as an ArrayBuffer
  104773. // we'll convert to string if it looks like it's an ASCII .stl
  104774. this.extensions = {
  104775. ".stl": { isBinary: true },
  104776. };
  104777. }
  104778. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104779. var matches;
  104780. if (typeof data !== "string") {
  104781. if (this.isBinary(data)) {
  104782. // binary .stl
  104783. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  104784. this.parseBinary(babylonMesh, data);
  104785. if (meshes) {
  104786. meshes.push(babylonMesh);
  104787. }
  104788. return true;
  104789. }
  104790. // ASCII .stl
  104791. // convert to string
  104792. var array_buffer = new Uint8Array(data);
  104793. var str = '';
  104794. for (var i = 0; i < data.byteLength; i++) {
  104795. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  104796. }
  104797. data = str;
  104798. }
  104799. //if arrived here, data is a string, containing the STLA data.
  104800. while (matches = this.solidPattern.exec(data)) {
  104801. var meshName = matches[1];
  104802. var meshNameFromEnd = matches[3];
  104803. if (meshName != meshNameFromEnd) {
  104804. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  104805. return false;
  104806. }
  104807. // check meshesNames
  104808. if (meshesNames && meshName) {
  104809. if (meshesNames instanceof Array) {
  104810. if (!meshesNames.indexOf(meshName)) {
  104811. continue;
  104812. }
  104813. }
  104814. else {
  104815. if (meshName !== meshesNames) {
  104816. continue;
  104817. }
  104818. }
  104819. }
  104820. // stl mesh name can be empty as well
  104821. meshName = meshName || "stlmesh";
  104822. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  104823. this.parseASCII(babylonMesh, matches[2]);
  104824. if (meshes) {
  104825. meshes.push(babylonMesh);
  104826. }
  104827. }
  104828. return true;
  104829. };
  104830. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  104831. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  104832. if (result) {
  104833. scene.createDefaultCameraOrLight();
  104834. }
  104835. return result;
  104836. };
  104837. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104838. var container = new BABYLON.AssetContainer(scene);
  104839. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104840. container.removeAllFromScene();
  104841. return container;
  104842. };
  104843. STLFileLoader.prototype.isBinary = function (data) {
  104844. // check if file size is correct for binary stl
  104845. var faceSize, nFaces, reader;
  104846. reader = new DataView(data);
  104847. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  104848. nFaces = reader.getUint32(80, true);
  104849. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104850. return true;
  104851. }
  104852. // check characters higher than ASCII to confirm binary
  104853. var fileLength = reader.byteLength;
  104854. for (var index = 0; index < fileLength; index++) {
  104855. if (reader.getUint8(index) > 127) {
  104856. return true;
  104857. }
  104858. }
  104859. return false;
  104860. };
  104861. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  104862. var reader = new DataView(data);
  104863. var faces = reader.getUint32(80, true);
  104864. var dataOffset = 84;
  104865. var faceLength = 12 * 4 + 2;
  104866. var offset = 0;
  104867. var positions = new Float32Array(faces * 3 * 3);
  104868. var normals = new Float32Array(faces * 3 * 3);
  104869. var indices = new Uint32Array(faces * 3);
  104870. var indicesCount = 0;
  104871. for (var face = 0; face < faces; face++) {
  104872. var start = dataOffset + face * faceLength;
  104873. var normalX = reader.getFloat32(start, true);
  104874. var normalY = reader.getFloat32(start + 4, true);
  104875. var normalZ = reader.getFloat32(start + 8, true);
  104876. for (var i = 1; i <= 3; i++) {
  104877. var vertexstart = start + i * 12;
  104878. // ordering is intentional to match ascii import
  104879. positions[offset] = reader.getFloat32(vertexstart, true);
  104880. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  104881. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  104882. normals[offset] = normalX;
  104883. normals[offset + 2] = normalY;
  104884. normals[offset + 1] = normalZ;
  104885. offset += 3;
  104886. }
  104887. indices[indicesCount] = indicesCount++;
  104888. indices[indicesCount] = indicesCount++;
  104889. indices[indicesCount] = indicesCount++;
  104890. }
  104891. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104892. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104893. mesh.setIndices(indices);
  104894. mesh.computeWorldMatrix(true);
  104895. };
  104896. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  104897. var positions = [];
  104898. var normals = [];
  104899. var indices = [];
  104900. var indicesCount = 0;
  104901. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  104902. var matches;
  104903. while (matches = this.facetsPattern.exec(solidData)) {
  104904. var facet = matches[1];
  104905. //one normal per face
  104906. var normalMatches = this.normalPattern.exec(facet);
  104907. this.normalPattern.lastIndex = 0;
  104908. if (!normalMatches) {
  104909. continue;
  104910. }
  104911. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  104912. var vertexMatch;
  104913. while (vertexMatch = this.vertexPattern.exec(facet)) {
  104914. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  104915. normals.push(normal[0], normal[1], normal[2]);
  104916. }
  104917. indices.push(indicesCount++, indicesCount++, indicesCount++);
  104918. this.vertexPattern.lastIndex = 0;
  104919. }
  104920. this.facetsPattern.lastIndex = 0;
  104921. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104922. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104923. mesh.setIndices(indices);
  104924. mesh.computeWorldMatrix(true);
  104925. };
  104926. return STLFileLoader;
  104927. }());
  104928. BABYLON.STLFileLoader = STLFileLoader;
  104929. if (BABYLON.SceneLoader) {
  104930. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  104931. }
  104932. })(BABYLON || (BABYLON = {}));
  104933. //# sourceMappingURL=babylon.stlFileLoader.js.map
  104934. var BABYLON;
  104935. (function (BABYLON) {
  104936. /**
  104937. * Class reading and parsing the MTL file bundled with the obj file.
  104938. */
  104939. var MTLFileLoader = /** @class */ (function () {
  104940. function MTLFileLoader() {
  104941. // All material loaded from the mtl will be set here
  104942. this.materials = [];
  104943. }
  104944. /**
  104945. * This function will read the mtl file and create each material described inside
  104946. * This function could be improve by adding :
  104947. * -some component missing (Ni, Tf...)
  104948. * -including the specific options available
  104949. *
  104950. * @param scene
  104951. * @param data
  104952. * @param rootUrl
  104953. */
  104954. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  104955. if (data instanceof ArrayBuffer) {
  104956. return;
  104957. }
  104958. //Split the lines from the file
  104959. var lines = data.split('\n');
  104960. //Space char
  104961. var delimiter_pattern = /\s+/;
  104962. //Array with RGB colors
  104963. var color;
  104964. //New material
  104965. var material = null;
  104966. //Look at each line
  104967. for (var i = 0; i < lines.length; i++) {
  104968. var line = lines[i].trim();
  104969. // Blank line or comment
  104970. if (line.length === 0 || line.charAt(0) === '#') {
  104971. continue;
  104972. }
  104973. //Get the first parameter (keyword)
  104974. var pos = line.indexOf(' ');
  104975. var key = (pos >= 0) ? line.substring(0, pos) : line;
  104976. key = key.toLowerCase();
  104977. //Get the data following the key
  104978. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  104979. //This mtl keyword will create the new material
  104980. if (key === "newmtl") {
  104981. //Check if it is the first material.
  104982. // Materials specifications are described after this keyword.
  104983. if (material) {
  104984. //Add the previous material in the material array.
  104985. this.materials.push(material);
  104986. }
  104987. //Create a new material.
  104988. // value is the name of the material read in the mtl file
  104989. material = new BABYLON.StandardMaterial(value, scene);
  104990. }
  104991. else if (key === "kd" && material) {
  104992. // Diffuse color (color under white light) using RGB values
  104993. //value = "r g b"
  104994. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104995. //color = [r,g,b]
  104996. //Set tghe color into the material
  104997. material.diffuseColor = BABYLON.Color3.FromArray(color);
  104998. }
  104999. else if (key === "ka" && material) {
  105000. // Ambient color (color under shadow) using RGB values
  105001. //value = "r g b"
  105002. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105003. //color = [r,g,b]
  105004. //Set tghe color into the material
  105005. material.ambientColor = BABYLON.Color3.FromArray(color);
  105006. }
  105007. else if (key === "ks" && material) {
  105008. // Specular color (color when light is reflected from shiny surface) using RGB values
  105009. //value = "r g b"
  105010. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105011. //color = [r,g,b]
  105012. //Set the color into the material
  105013. material.specularColor = BABYLON.Color3.FromArray(color);
  105014. }
  105015. else if (key === "ke" && material) {
  105016. // Emissive color using RGB values
  105017. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105018. material.emissiveColor = BABYLON.Color3.FromArray(color);
  105019. }
  105020. else if (key === "ns" && material) {
  105021. //value = "Integer"
  105022. material.specularPower = parseFloat(value);
  105023. }
  105024. else if (key === "d" && material) {
  105025. //d is dissolve for current material. It mean alpha for BABYLON
  105026. material.alpha = parseFloat(value);
  105027. //Texture
  105028. //This part can be improved by adding the possible options of texture
  105029. }
  105030. else if (key === "map_ka" && material) {
  105031. // ambient texture map with a loaded image
  105032. //We must first get the folder of the image
  105033. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105034. }
  105035. else if (key === "map_kd" && material) {
  105036. // Diffuse texture map with a loaded image
  105037. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105038. }
  105039. else if (key === "map_ks" && material) {
  105040. // Specular texture map with a loaded image
  105041. //We must first get the folder of the image
  105042. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105043. }
  105044. else if (key === "map_ns") {
  105045. //Specular
  105046. //Specular highlight component
  105047. //We must first get the folder of the image
  105048. //
  105049. //Not supported by BABYLON
  105050. //
  105051. // continue;
  105052. }
  105053. else if (key === "map_bump" && material) {
  105054. //The bump texture
  105055. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105056. }
  105057. else if (key === "map_d" && material) {
  105058. // The dissolve of the material
  105059. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105060. //Options for illumination
  105061. }
  105062. else if (key === "illum") {
  105063. //Illumination
  105064. if (value === "0") {
  105065. //That mean Kd == Kd
  105066. }
  105067. else if (value === "1") {
  105068. //Color on and Ambient on
  105069. }
  105070. else if (value === "2") {
  105071. //Highlight on
  105072. }
  105073. else if (value === "3") {
  105074. //Reflection on and Ray trace on
  105075. }
  105076. else if (value === "4") {
  105077. //Transparency: Glass on, Reflection: Ray trace on
  105078. }
  105079. else if (value === "5") {
  105080. //Reflection: Fresnel on and Ray trace on
  105081. }
  105082. else if (value === "6") {
  105083. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  105084. }
  105085. else if (value === "7") {
  105086. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  105087. }
  105088. else if (value === "8") {
  105089. //Reflection on and Ray trace off
  105090. }
  105091. else if (value === "9") {
  105092. //Transparency: Glass on, Reflection: Ray trace off
  105093. }
  105094. else if (value === "10") {
  105095. //Casts shadows onto invisible surfaces
  105096. }
  105097. }
  105098. else {
  105099. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  105100. }
  105101. }
  105102. //At the end of the file, add the last material
  105103. if (material) {
  105104. this.materials.push(material);
  105105. }
  105106. };
  105107. /**
  105108. * Gets the texture for the material.
  105109. *
  105110. * If the material is imported from input file,
  105111. * We sanitize the url to ensure it takes the textre from aside the material.
  105112. *
  105113. * @param rootUrl The root url to load from
  105114. * @param value The value stored in the mtl
  105115. * @return The Texture
  105116. */
  105117. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  105118. if (!value) {
  105119. return null;
  105120. }
  105121. var url = rootUrl;
  105122. // Load from input file.
  105123. if (rootUrl === "file:") {
  105124. var lastDelimiter = value.lastIndexOf("\\");
  105125. if (lastDelimiter === -1) {
  105126. lastDelimiter = value.lastIndexOf("/");
  105127. }
  105128. if (lastDelimiter > -1) {
  105129. url += value.substr(lastDelimiter + 1);
  105130. }
  105131. else {
  105132. url += value;
  105133. }
  105134. }
  105135. // Not from input file.
  105136. else {
  105137. url += value;
  105138. }
  105139. return new BABYLON.Texture(url, scene);
  105140. };
  105141. return MTLFileLoader;
  105142. }());
  105143. BABYLON.MTLFileLoader = MTLFileLoader;
  105144. var OBJFileLoader = /** @class */ (function () {
  105145. function OBJFileLoader() {
  105146. this.name = "obj";
  105147. this.extensions = ".obj";
  105148. this.obj = /^o/;
  105149. this.group = /^g/;
  105150. this.mtllib = /^mtllib /;
  105151. this.usemtl = /^usemtl /;
  105152. this.smooth = /^s /;
  105153. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105154. // vn float float float
  105155. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105156. // vt float float
  105157. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105158. // f vertex vertex vertex ...
  105159. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  105160. // f vertex/uvs vertex/uvs vertex/uvs ...
  105161. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105162. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  105163. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105164. // f vertex//normal vertex//normal vertex//normal ...
  105165. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105166. }
  105167. /**
  105168. * Calls synchronously the MTL file attached to this obj.
  105169. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105170. * Without this function materials are not displayed in the first frame (but displayed after).
  105171. * In consequence it is impossible to get material information in your HTML file
  105172. *
  105173. * @param url The URL of the MTL file
  105174. * @param rootUrl
  105175. * @param onSuccess Callback function to be called when the MTL file is loaded
  105176. * @private
  105177. */
  105178. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105179. //The complete path to the mtl file
  105180. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105181. // Loads through the babylon tools to allow fileInput search.
  105182. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105183. };
  105184. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105185. //get the meshes from OBJ file
  105186. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  105187. //Push meshes from OBJ file into the variable mesh of this function
  105188. if (meshes) {
  105189. loadedMeshes.forEach(function (mesh) {
  105190. meshes.push(mesh);
  105191. });
  105192. }
  105193. return true;
  105194. };
  105195. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  105196. //Get the 3D model
  105197. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  105198. };
  105199. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105200. var container = new BABYLON.AssetContainer(scene);
  105201. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105202. container.removeAllFromScene();
  105203. return container;
  105204. };
  105205. /**
  105206. * Read the OBJ file and create an Array of meshes.
  105207. * Each mesh contains all information given by the OBJ and the MTL file.
  105208. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105209. *
  105210. * @param meshesNames
  105211. * @param scene BABYLON.Scene The scene where are displayed the data
  105212. * @param data String The content of the obj file
  105213. * @param rootUrl String The path to the folder
  105214. * @returns Array<AbstractMesh>
  105215. * @private
  105216. */
  105217. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105218. var positions = []; //values for the positions of vertices
  105219. var normals = []; //Values for the normals
  105220. var uvs = []; //Values for the textures
  105221. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105222. var handledMesh; //The current mesh of meshes array
  105223. var indicesForBabylon = []; //The list of indices for VertexData
  105224. var wrappedPositionForBabylon = []; //The list of position in vectors
  105225. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105226. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105227. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105228. var curPositionInIndices = 0;
  105229. var hasMeshes = false; //Meshes are defined in the file
  105230. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105231. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105232. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105233. var triangles = []; //Indices from new triangles coming from polygons
  105234. var materialNameFromObj = ""; //The name of the current material
  105235. var fileToLoad = ""; //The name of the mtlFile to load
  105236. var materialsFromMTLFile = new MTLFileLoader();
  105237. var objMeshName = ""; //The name of the current obj mesh
  105238. var increment = 1; //Id for meshes created by the multimaterial
  105239. var isFirstMaterial = true;
  105240. /**
  105241. * Search for obj in the given array.
  105242. * This function is called to check if a couple of data already exists in an array.
  105243. *
  105244. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105245. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105246. * @param obj Array<number>
  105247. * @returns {boolean}
  105248. */
  105249. var isInArray = function (arr, obj) {
  105250. if (!arr[obj[0]])
  105251. arr[obj[0]] = { normals: [], idx: [] };
  105252. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105253. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  105254. };
  105255. var isInArrayUV = function (arr, obj) {
  105256. if (!arr[obj[0]])
  105257. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  105258. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105259. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  105260. return arr[obj[0]].idx[idx];
  105261. }
  105262. return -1;
  105263. };
  105264. /**
  105265. * This function set the data for each triangle.
  105266. * Data are position, normals and uvs
  105267. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  105268. * If the tuple already exist, add only their indice
  105269. *
  105270. * @param indicePositionFromObj Integer The index in positions array
  105271. * @param indiceUvsFromObj Integer The index in uvs array
  105272. * @param indiceNormalFromObj Integer The index in normals array
  105273. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  105274. * @param textureVectorFromOBJ Vector3 The value of uvs
  105275. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  105276. */
  105277. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  105278. //Check if this tuple already exists in the list of tuples
  105279. var _index;
  105280. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  105281. _index = isInArrayUV(tuplePosNorm, [
  105282. indicePositionFromObj,
  105283. indiceNormalFromObj,
  105284. indiceUvsFromObj
  105285. ]);
  105286. }
  105287. else {
  105288. _index = isInArray(tuplePosNorm, [
  105289. indicePositionFromObj,
  105290. indiceNormalFromObj
  105291. ]);
  105292. }
  105293. //If it not exists
  105294. if (_index == -1) {
  105295. //Add an new indice.
  105296. //The array of indices is only an array with his length equal to the number of triangles - 1.
  105297. //We add vertices data in this order
  105298. indicesForBabylon.push(wrappedPositionForBabylon.length);
  105299. //Push the position of vertice for Babylon
  105300. //Each element is a BABYLON.Vector3(x,y,z)
  105301. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  105302. //Push the uvs for Babylon
  105303. //Each element is a BABYLON.Vector3(u,v)
  105304. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  105305. //Push the normals for Babylon
  105306. //Each element is a BABYLON.Vector3(x,y,z)
  105307. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105308. //Add the tuple in the comparison list
  105309. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105310. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105311. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105312. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105313. }
  105314. else {
  105315. //The tuple already exists
  105316. //Add the index of the already existing tuple
  105317. //At this index we can get the value of position, normal and uvs of vertex
  105318. indicesForBabylon.push(_index);
  105319. }
  105320. };
  105321. /**
  105322. * Transform BABYLON.Vector() object onto 3 digits in an array
  105323. */
  105324. var unwrapData = function () {
  105325. //Every array has the same length
  105326. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105327. //Push the x, y, z values of each element in the unwrapped array
  105328. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105329. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105330. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105331. }
  105332. // Reset arrays for the next new meshes
  105333. wrappedPositionForBabylon = [];
  105334. wrappedNormalsForBabylon = [];
  105335. wrappedUvsForBabylon = [];
  105336. tuplePosNorm = [];
  105337. curPositionInIndices = 0;
  105338. };
  105339. /**
  105340. * Create triangles from polygons by recursion
  105341. * The best to understand how it works is to draw it in the same time you get the recursion.
  105342. * It is important to notice that a triangle is a polygon
  105343. * We get 4 patterns of face defined in OBJ File :
  105344. * facePattern1 = ["1","2","3","4","5","6"]
  105345. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105346. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105347. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105348. * Each pattern is divided by the same method
  105349. * @param face Array[String] The indices of elements
  105350. * @param v Integer The variable to increment
  105351. */
  105352. var getTriangles = function (face, v) {
  105353. //Work for each element of the array
  105354. if (v + 1 < face.length) {
  105355. //Add on the triangle variable the indexes to obtain triangles
  105356. triangles.push(face[0], face[v], face[v + 1]);
  105357. //Incrementation for recursion
  105358. v += 1;
  105359. //Recursion
  105360. getTriangles(face, v);
  105361. }
  105362. //Result obtained after 2 iterations:
  105363. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105364. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105365. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105366. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105367. };
  105368. /**
  105369. * Create triangles and push the data for each polygon for the pattern 1
  105370. * In this pattern we get vertice positions
  105371. * @param face
  105372. * @param v
  105373. */
  105374. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105375. //Get the indices of triangles for each polygon
  105376. getTriangles(face, v);
  105377. //For each element in the triangles array.
  105378. //This var could contains 1 to an infinity of triangles
  105379. for (var k = 0; k < triangles.length; k++) {
  105380. // Set position indice
  105381. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105382. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105383. positions[indicePositionFromObj], //Get the vectors data
  105384. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105385. );
  105386. }
  105387. //Reset variable for the next line
  105388. triangles = [];
  105389. };
  105390. /**
  105391. * Create triangles and push the data for each polygon for the pattern 2
  105392. * In this pattern we get vertice positions and uvsu
  105393. * @param face
  105394. * @param v
  105395. */
  105396. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105397. //Get the indices of triangles for each polygon
  105398. getTriangles(face, v);
  105399. for (var k = 0; k < triangles.length; k++) {
  105400. //triangle[k] = "1/1"
  105401. //Split the data for getting position and uv
  105402. var point = triangles[k].split("/"); // ["1", "1"]
  105403. //Set position indice
  105404. var indicePositionFromObj = parseInt(point[0]) - 1;
  105405. //Set uv indice
  105406. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105407. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105408. positions[indicePositionFromObj], //Get the values for each element
  105409. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105410. );
  105411. }
  105412. //Reset variable for the next line
  105413. triangles = [];
  105414. };
  105415. /**
  105416. * Create triangles and push the data for each polygon for the pattern 3
  105417. * In this pattern we get vertice positions, uvs and normals
  105418. * @param face
  105419. * @param v
  105420. */
  105421. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105422. //Get the indices of triangles for each polygon
  105423. getTriangles(face, v);
  105424. for (var k = 0; k < triangles.length; k++) {
  105425. //triangle[k] = "1/1/1"
  105426. //Split the data for getting position, uv, and normals
  105427. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105428. // Set position indice
  105429. var indicePositionFromObj = parseInt(point[0]) - 1;
  105430. // Set uv indice
  105431. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105432. // Set normal indice
  105433. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105434. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105435. );
  105436. }
  105437. //Reset variable for the next line
  105438. triangles = [];
  105439. };
  105440. /**
  105441. * Create triangles and push the data for each polygon for the pattern 4
  105442. * In this pattern we get vertice positions and normals
  105443. * @param face
  105444. * @param v
  105445. */
  105446. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105447. getTriangles(face, v);
  105448. for (var k = 0; k < triangles.length; k++) {
  105449. //triangle[k] = "1//1"
  105450. //Split the data for getting position and normals
  105451. var point = triangles[k].split("//"); // ["1", "1"]
  105452. // We check indices, and normals
  105453. var indicePositionFromObj = parseInt(point[0]) - 1;
  105454. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105455. setData(indicePositionFromObj, 1, //Default value for uv
  105456. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105457. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105458. }
  105459. //Reset variable for the next line
  105460. triangles = [];
  105461. };
  105462. var addPreviousObjMesh = function () {
  105463. //Check if it is not the first mesh. Otherwise we don't have data.
  105464. if (meshesFromObj.length > 0) {
  105465. //Get the previous mesh for applying the data about the faces
  105466. //=> in obj file, faces definition append after the name of the mesh
  105467. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105468. //Set the data into Array for the mesh
  105469. unwrapData();
  105470. // Reverse tab. Otherwise face are displayed in the wrong sens
  105471. indicesForBabylon.reverse();
  105472. //Set the information for the mesh
  105473. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105474. handledMesh.indices = indicesForBabylon.slice();
  105475. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105476. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105477. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105478. //Reset the array for the next mesh
  105479. indicesForBabylon = [];
  105480. unwrappedPositionsForBabylon = [];
  105481. unwrappedNormalsForBabylon = [];
  105482. unwrappedUVForBabylon = [];
  105483. }
  105484. };
  105485. //Main function
  105486. //Split the file into lines
  105487. var lines = data.split('\n');
  105488. //Look at each line
  105489. for (var i = 0; i < lines.length; i++) {
  105490. var line = lines[i].trim();
  105491. var result;
  105492. //Comment or newLine
  105493. if (line.length === 0 || line.charAt(0) === '#') {
  105494. continue;
  105495. //Get information about one position possible for the vertices
  105496. }
  105497. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105498. //Create a Vector3 with the position x, y, z
  105499. //Value of result:
  105500. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105501. //Add the Vector in the list of positions
  105502. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105503. }
  105504. else if ((result = this.normalPattern.exec(line)) !== null) {
  105505. //Create a Vector3 with the normals x, y, z
  105506. //Value of result
  105507. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105508. //Add the Vector in the list of normals
  105509. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105510. }
  105511. else if ((result = this.uvPattern.exec(line)) !== null) {
  105512. //Create a Vector2 with the normals u, v
  105513. //Value of result
  105514. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105515. //Add the Vector in the list of uvs
  105516. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105517. //Identify patterns of faces
  105518. //Face could be defined in different type of pattern
  105519. }
  105520. else if ((result = this.facePattern3.exec(line)) !== null) {
  105521. //Value of result:
  105522. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105523. //Set the data for this face
  105524. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105525. 1);
  105526. }
  105527. else if ((result = this.facePattern4.exec(line)) !== null) {
  105528. //Value of result:
  105529. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105530. //Set the data for this face
  105531. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105532. 1);
  105533. }
  105534. else if ((result = this.facePattern2.exec(line)) !== null) {
  105535. //Value of result:
  105536. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105537. //Set the data for this face
  105538. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105539. 1);
  105540. }
  105541. else if ((result = this.facePattern1.exec(line)) !== null) {
  105542. //Value of result
  105543. //["f 1 2 3", "1 2 3"...]
  105544. //Set the data for this face
  105545. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105546. 1);
  105547. //Define a mesh or an object
  105548. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105549. }
  105550. else if (this.group.test(line) || this.obj.test(line)) {
  105551. //Create a new mesh corresponding to the name of the group.
  105552. //Definition of the mesh
  105553. var objMesh =
  105554. //Set the name of the current obj mesh
  105555. {
  105556. name: line.substring(2).trim(),
  105557. indices: undefined,
  105558. positions: undefined,
  105559. normals: undefined,
  105560. uvs: undefined,
  105561. materialName: ""
  105562. };
  105563. addPreviousObjMesh();
  105564. //Push the last mesh created with only the name
  105565. meshesFromObj.push(objMesh);
  105566. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105567. hasMeshes = true;
  105568. isFirstMaterial = true;
  105569. increment = 1;
  105570. //Keyword for applying a material
  105571. }
  105572. else if (this.usemtl.test(line)) {
  105573. //Get the name of the material
  105574. materialNameFromObj = line.substring(7).trim();
  105575. //If this new material is in the same mesh
  105576. if (!isFirstMaterial) {
  105577. //Set the data for the previous mesh
  105578. addPreviousObjMesh();
  105579. //Create a new mesh
  105580. var objMesh =
  105581. //Set the name of the current obj mesh
  105582. {
  105583. name: objMeshName + "_mm" + increment.toString(),
  105584. indices: undefined,
  105585. positions: undefined,
  105586. normals: undefined,
  105587. uvs: undefined,
  105588. materialName: materialNameFromObj
  105589. };
  105590. increment++;
  105591. //If meshes are already defined
  105592. meshesFromObj.push(objMesh);
  105593. }
  105594. //Set the material name if the previous line define a mesh
  105595. if (hasMeshes && isFirstMaterial) {
  105596. //Set the material name to the previous mesh (1 material per mesh)
  105597. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105598. isFirstMaterial = false;
  105599. }
  105600. //Keyword for loading the mtl file
  105601. }
  105602. else if (this.mtllib.test(line)) {
  105603. //Get the name of mtl file
  105604. fileToLoad = line.substring(7).trim();
  105605. //Apply smoothing
  105606. }
  105607. else if (this.smooth.test(line)) {
  105608. // smooth shading => apply smoothing
  105609. //Toda y I don't know it work with babylon and with obj.
  105610. //With the obj file an integer is set
  105611. }
  105612. else {
  105613. //If there is another possibility
  105614. console.log("Unhandled expression at line : " + line);
  105615. }
  105616. }
  105617. //At the end of the file, add the last mesh into the meshesFromObj array
  105618. if (hasMeshes) {
  105619. //Set the data for the last mesh
  105620. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105621. //Reverse indices for displaying faces in the good sens
  105622. indicesForBabylon.reverse();
  105623. //Get the good array
  105624. unwrapData();
  105625. //Set array
  105626. handledMesh.indices = indicesForBabylon;
  105627. handledMesh.positions = unwrappedPositionsForBabylon;
  105628. handledMesh.normals = unwrappedNormalsForBabylon;
  105629. handledMesh.uvs = unwrappedUVForBabylon;
  105630. }
  105631. //If any o or g keyword found, create a mesj with a random id
  105632. if (!hasMeshes) {
  105633. // reverse tab of indices
  105634. indicesForBabylon.reverse();
  105635. //Get positions normals uvs
  105636. unwrapData();
  105637. //Set data for one mesh
  105638. meshesFromObj.push({
  105639. name: BABYLON.Geometry.RandomId(),
  105640. indices: indicesForBabylon,
  105641. positions: unwrappedPositionsForBabylon,
  105642. normals: unwrappedNormalsForBabylon,
  105643. uvs: unwrappedUVForBabylon,
  105644. materialName: materialNameFromObj
  105645. });
  105646. }
  105647. //Create a BABYLON.Mesh list
  105648. var babylonMeshesArray = []; //The mesh for babylon
  105649. var materialToUse = new Array();
  105650. //Set data for each mesh
  105651. for (var j = 0; j < meshesFromObj.length; j++) {
  105652. //check meshesNames (stlFileLoader)
  105653. if (meshesNames && meshesFromObj[j].name) {
  105654. if (meshesNames instanceof Array) {
  105655. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105656. continue;
  105657. }
  105658. }
  105659. else {
  105660. if (meshesFromObj[j].name !== meshesNames) {
  105661. continue;
  105662. }
  105663. }
  105664. }
  105665. //Get the current mesh
  105666. //Set the data with VertexBuffer for each mesh
  105667. handledMesh = meshesFromObj[j];
  105668. //Create a BABYLON.Mesh with the name of the obj mesh
  105669. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  105670. //Push the name of the material to an array
  105671. //This is indispensable for the importMesh function
  105672. materialToUse.push(meshesFromObj[j].materialName);
  105673. var vertexData = new BABYLON.VertexData(); //The container for the values
  105674. //Set the data for the babylonMesh
  105675. vertexData.positions = handledMesh.positions;
  105676. vertexData.normals = handledMesh.normals;
  105677. vertexData.uvs = handledMesh.uvs;
  105678. vertexData.indices = handledMesh.indices;
  105679. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  105680. vertexData.applyToMesh(babylonMesh);
  105681. if (OBJFileLoader.INVERT_Y) {
  105682. babylonMesh.scaling.y *= -1;
  105683. }
  105684. //Push the mesh into an array
  105685. babylonMeshesArray.push(babylonMesh);
  105686. }
  105687. //load the materials
  105688. //Check if we have a file to load
  105689. if (fileToLoad !== "") {
  105690. //Load the file synchronously
  105691. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  105692. //Create materials thanks MTLLoader function
  105693. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  105694. //Look at each material loaded in the mtl file
  105695. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  105696. //Three variables to get all meshes with the same material
  105697. var startIndex = 0;
  105698. var _indices = [];
  105699. var _index;
  105700. //The material from MTL file is used in the meshes loaded
  105701. //Push the indice in an array
  105702. //Check if the material is not used for another mesh
  105703. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  105704. _indices.push(_index);
  105705. startIndex = _index + 1;
  105706. }
  105707. //If the material is not used dispose it
  105708. if (_index == -1 && _indices.length == 0) {
  105709. //If the material is not needed, remove it
  105710. materialsFromMTLFile.materials[n].dispose();
  105711. }
  105712. else {
  105713. for (var o = 0; o < _indices.length; o++) {
  105714. //Apply the material to the BABYLON.Mesh for each mesh with the material
  105715. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  105716. }
  105717. }
  105718. }
  105719. });
  105720. }
  105721. //Return an array with all BABYLON.Mesh
  105722. return babylonMeshesArray;
  105723. };
  105724. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  105725. OBJFileLoader.INVERT_Y = false;
  105726. return OBJFileLoader;
  105727. }());
  105728. BABYLON.OBJFileLoader = OBJFileLoader;
  105729. if (BABYLON.SceneLoader) {
  105730. //Add this loader into the register plugin
  105731. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  105732. }
  105733. })(BABYLON || (BABYLON = {}));
  105734. //# sourceMappingURL=babylon.objFileLoader.js.map
  105735. var BABYLON;
  105736. (function (BABYLON) {
  105737. /**
  105738. * Mode that determines the coordinate system to use.
  105739. */
  105740. var GLTFLoaderCoordinateSystemMode;
  105741. (function (GLTFLoaderCoordinateSystemMode) {
  105742. /**
  105743. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  105744. */
  105745. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  105746. /**
  105747. * Sets the useRightHandedSystem flag on the scene.
  105748. */
  105749. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  105750. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  105751. /**
  105752. * Mode that determines what animations will start.
  105753. */
  105754. var GLTFLoaderAnimationStartMode;
  105755. (function (GLTFLoaderAnimationStartMode) {
  105756. /**
  105757. * No animation will start.
  105758. */
  105759. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  105760. /**
  105761. * The first animation will start.
  105762. */
  105763. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  105764. /**
  105765. * All animations will start.
  105766. */
  105767. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  105768. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  105769. /**
  105770. * Loader state.
  105771. */
  105772. var GLTFLoaderState;
  105773. (function (GLTFLoaderState) {
  105774. /**
  105775. * The asset is loading.
  105776. */
  105777. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  105778. /**
  105779. * The asset is ready for rendering.
  105780. */
  105781. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  105782. /**
  105783. * The asset is completely loaded.
  105784. */
  105785. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  105786. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  105787. /**
  105788. * File loader for loading glTF files into a scene.
  105789. */
  105790. var GLTFFileLoader = /** @class */ (function () {
  105791. function GLTFFileLoader() {
  105792. // #region Common options
  105793. /**
  105794. * Raised when the asset has been parsed
  105795. */
  105796. this.onParsedObservable = new BABYLON.Observable();
  105797. // #endregion
  105798. // #region V2 options
  105799. /**
  105800. * The coordinate system mode. Defaults to AUTO.
  105801. */
  105802. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  105803. /**
  105804. * The animation start mode. Defaults to FIRST.
  105805. */
  105806. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  105807. /**
  105808. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  105809. */
  105810. this.compileMaterials = false;
  105811. /**
  105812. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  105813. */
  105814. this.useClipPlane = false;
  105815. /**
  105816. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  105817. */
  105818. this.compileShadowGenerators = false;
  105819. /**
  105820. * Defines if the Alpha blended materials are only applied as coverage.
  105821. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  105822. * If true, no extra effects are applied to transparent pixels.
  105823. */
  105824. this.transparencyAsCoverage = false;
  105825. /** @hidden */
  105826. this._normalizeAnimationGroupsToBeginAtZero = true;
  105827. /**
  105828. * Function called before loading a url referenced by the asset.
  105829. */
  105830. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  105831. /**
  105832. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105833. */
  105834. this.onMeshLoadedObservable = new BABYLON.Observable();
  105835. /**
  105836. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  105837. */
  105838. this.onTextureLoadedObservable = new BABYLON.Observable();
  105839. /**
  105840. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  105841. */
  105842. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105843. /**
  105844. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  105845. */
  105846. this.onCameraLoadedObservable = new BABYLON.Observable();
  105847. /**
  105848. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  105849. * For assets with LODs, raised when all of the LODs are complete.
  105850. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  105851. */
  105852. this.onCompleteObservable = new BABYLON.Observable();
  105853. /**
  105854. * Observable raised after the loader is disposed.
  105855. */
  105856. this.onDisposeObservable = new BABYLON.Observable();
  105857. /**
  105858. * Observable raised after a loader extension is created.
  105859. * Set additional options for a loader extension in this event.
  105860. */
  105861. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105862. // #endregion
  105863. this._loader = null;
  105864. /**
  105865. * Name of the loader ("gltf")
  105866. */
  105867. this.name = "gltf";
  105868. /**
  105869. * Supported file extensions of the loader (.gltf, .glb)
  105870. */
  105871. this.extensions = {
  105872. ".gltf": { isBinary: false },
  105873. ".glb": { isBinary: true }
  105874. };
  105875. this._logIndentLevel = 0;
  105876. this._loggingEnabled = false;
  105877. /** @hidden */
  105878. this._log = this._logDisabled;
  105879. this._capturePerformanceCounters = false;
  105880. /** @hidden */
  105881. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  105882. /** @hidden */
  105883. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  105884. }
  105885. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  105886. /**
  105887. * Raised when the asset has been parsed
  105888. */
  105889. set: function (callback) {
  105890. if (this._onParsedObserver) {
  105891. this.onParsedObservable.remove(this._onParsedObserver);
  105892. }
  105893. this._onParsedObserver = this.onParsedObservable.add(callback);
  105894. },
  105895. enumerable: true,
  105896. configurable: true
  105897. });
  105898. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  105899. /**
  105900. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105901. */
  105902. set: function (callback) {
  105903. if (this._onMeshLoadedObserver) {
  105904. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  105905. }
  105906. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  105907. },
  105908. enumerable: true,
  105909. configurable: true
  105910. });
  105911. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  105912. /**
  105913. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  105914. */
  105915. set: function (callback) {
  105916. if (this._onTextureLoadedObserver) {
  105917. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  105918. }
  105919. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  105920. },
  105921. enumerable: true,
  105922. configurable: true
  105923. });
  105924. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  105925. /**
  105926. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  105927. */
  105928. set: function (callback) {
  105929. if (this._onMaterialLoadedObserver) {
  105930. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  105931. }
  105932. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  105933. },
  105934. enumerable: true,
  105935. configurable: true
  105936. });
  105937. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  105938. /**
  105939. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  105940. */
  105941. set: function (callback) {
  105942. if (this._onCameraLoadedObserver) {
  105943. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  105944. }
  105945. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  105946. },
  105947. enumerable: true,
  105948. configurable: true
  105949. });
  105950. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  105951. /**
  105952. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  105953. */
  105954. set: function (callback) {
  105955. if (this._onCompleteObserver) {
  105956. this.onCompleteObservable.remove(this._onCompleteObserver);
  105957. }
  105958. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  105959. },
  105960. enumerable: true,
  105961. configurable: true
  105962. });
  105963. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  105964. /**
  105965. * Callback raised after the loader is disposed.
  105966. */
  105967. set: function (callback) {
  105968. if (this._onDisposeObserver) {
  105969. this.onDisposeObservable.remove(this._onDisposeObserver);
  105970. }
  105971. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105972. },
  105973. enumerable: true,
  105974. configurable: true
  105975. });
  105976. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  105977. /**
  105978. * Callback raised after a loader extension is created.
  105979. */
  105980. set: function (callback) {
  105981. if (this._onExtensionLoadedObserver) {
  105982. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  105983. }
  105984. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  105985. },
  105986. enumerable: true,
  105987. configurable: true
  105988. });
  105989. /**
  105990. * Returns a promise that resolves when the asset is completely loaded.
  105991. * @returns a promise that resolves when the asset is completely loaded.
  105992. */
  105993. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  105994. var _this = this;
  105995. return new Promise(function (resolve) {
  105996. _this.onCompleteObservable.addOnce(function () {
  105997. resolve();
  105998. });
  105999. });
  106000. };
  106001. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  106002. /**
  106003. * The loader state or null if the loader is not active.
  106004. */
  106005. get: function () {
  106006. return this._loader ? this._loader.state : null;
  106007. },
  106008. enumerable: true,
  106009. configurable: true
  106010. });
  106011. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  106012. /**
  106013. * Defines if the loader logging is enabled.
  106014. */
  106015. get: function () {
  106016. return this._loggingEnabled;
  106017. },
  106018. set: function (value) {
  106019. if (this._loggingEnabled === value) {
  106020. return;
  106021. }
  106022. this._loggingEnabled = value;
  106023. if (this._loggingEnabled) {
  106024. this._log = this._logEnabled;
  106025. }
  106026. else {
  106027. this._log = this._logDisabled;
  106028. }
  106029. },
  106030. enumerable: true,
  106031. configurable: true
  106032. });
  106033. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  106034. /**
  106035. * Defines if the loader should capture performance counters.
  106036. */
  106037. get: function () {
  106038. return this._capturePerformanceCounters;
  106039. },
  106040. set: function (value) {
  106041. if (this._capturePerformanceCounters === value) {
  106042. return;
  106043. }
  106044. this._capturePerformanceCounters = value;
  106045. if (this._capturePerformanceCounters) {
  106046. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  106047. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  106048. }
  106049. else {
  106050. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  106051. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  106052. }
  106053. },
  106054. enumerable: true,
  106055. configurable: true
  106056. });
  106057. /**
  106058. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  106059. */
  106060. GLTFFileLoader.prototype.dispose = function () {
  106061. if (this._loader) {
  106062. this._loader.dispose();
  106063. this._loader = null;
  106064. }
  106065. this._clear();
  106066. this.onDisposeObservable.notifyObservers(undefined);
  106067. this.onDisposeObservable.clear();
  106068. };
  106069. /** @hidden */
  106070. GLTFFileLoader.prototype._clear = function () {
  106071. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106072. this.onMeshLoadedObservable.clear();
  106073. this.onTextureLoadedObservable.clear();
  106074. this.onMaterialLoadedObservable.clear();
  106075. this.onCameraLoadedObservable.clear();
  106076. this.onCompleteObservable.clear();
  106077. this.onExtensionLoadedObservable.clear();
  106078. };
  106079. /**
  106080. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  106081. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  106082. * @param scene the scene the meshes should be added to
  106083. * @param data the glTF data to load
  106084. * @param rootUrl root url to load from
  106085. * @param onProgress event that fires when loading progress has occured
  106086. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  106087. */
  106088. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106089. var _this = this;
  106090. return Promise.resolve().then(function () {
  106091. var loaderData = _this._parse(data);
  106092. _this._loader = _this._getLoader(loaderData);
  106093. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  106094. });
  106095. };
  106096. /**
  106097. * Imports all objects from the loaded glTF data and adds them to the scene
  106098. * @param scene the scene the objects should be added to
  106099. * @param data the glTF data to load
  106100. * @param rootUrl root url to load from
  106101. * @param onProgress event that fires when loading progress has occured
  106102. * @returns a promise which completes when objects have been loaded to the scene
  106103. */
  106104. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106105. var _this = this;
  106106. return Promise.resolve().then(function () {
  106107. var loaderData = _this._parse(data);
  106108. _this._loader = _this._getLoader(loaderData);
  106109. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  106110. });
  106111. };
  106112. /**
  106113. * Load into an asset container.
  106114. * @param scene The scene to load into
  106115. * @param data The data to import
  106116. * @param rootUrl The root url for scene and resources
  106117. * @param onProgress The callback when the load progresses
  106118. * @returns The loaded asset container
  106119. */
  106120. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106121. var _this = this;
  106122. return Promise.resolve().then(function () {
  106123. var loaderData = _this._parse(data);
  106124. _this._loader = _this._getLoader(loaderData);
  106125. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  106126. var container = new BABYLON.AssetContainer(scene);
  106127. Array.prototype.push.apply(container.meshes, result.meshes);
  106128. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  106129. Array.prototype.push.apply(container.skeletons, result.skeletons);
  106130. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  106131. container.removeAllFromScene();
  106132. return container;
  106133. });
  106134. });
  106135. };
  106136. /**
  106137. * If the data string can be loaded directly.
  106138. * @param data string contianing the file data
  106139. * @returns if the data can be loaded directly
  106140. */
  106141. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  106142. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  106143. };
  106144. /**
  106145. * Instantiates a glTF file loader plugin.
  106146. * @returns the created plugin
  106147. */
  106148. GLTFFileLoader.prototype.createPlugin = function () {
  106149. return new GLTFFileLoader();
  106150. };
  106151. GLTFFileLoader.prototype._parse = function (data) {
  106152. this._startPerformanceCounter("Parse");
  106153. var parsedData;
  106154. if (data instanceof ArrayBuffer) {
  106155. this._log("Parsing binary");
  106156. parsedData = this._parseBinary(data);
  106157. }
  106158. else {
  106159. this._log("Parsing JSON");
  106160. this._log("JSON length: " + data.length);
  106161. parsedData = {
  106162. json: JSON.parse(data),
  106163. bin: null
  106164. };
  106165. }
  106166. this.onParsedObservable.notifyObservers(parsedData);
  106167. this.onParsedObservable.clear();
  106168. this._endPerformanceCounter("Parse");
  106169. return parsedData;
  106170. };
  106171. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  106172. var asset = loaderData.json.asset || {};
  106173. this._log("Asset version: " + asset.version);
  106174. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  106175. asset.generator && this._log("Asset generator: " + asset.generator);
  106176. var version = GLTFFileLoader._parseVersion(asset.version);
  106177. if (!version) {
  106178. throw new Error("Invalid version: " + asset.version);
  106179. }
  106180. if (asset.minVersion !== undefined) {
  106181. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  106182. if (!minVersion) {
  106183. throw new Error("Invalid minimum version: " + asset.minVersion);
  106184. }
  106185. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  106186. throw new Error("Incompatible minimum version: " + asset.minVersion);
  106187. }
  106188. }
  106189. var createLoaders = {
  106190. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  106191. 2: GLTFFileLoader._CreateGLTFLoaderV2
  106192. };
  106193. var createLoader = createLoaders[version.major];
  106194. if (!createLoader) {
  106195. throw new Error("Unsupported version: " + asset.version);
  106196. }
  106197. return createLoader(this);
  106198. };
  106199. GLTFFileLoader.prototype._parseBinary = function (data) {
  106200. var Binary = {
  106201. Magic: 0x46546C67
  106202. };
  106203. this._log("Binary length: " + data.byteLength);
  106204. var binaryReader = new BinaryReader(data);
  106205. var magic = binaryReader.readUint32();
  106206. if (magic !== Binary.Magic) {
  106207. throw new Error("Unexpected magic: " + magic);
  106208. }
  106209. var version = binaryReader.readUint32();
  106210. if (this.loggingEnabled) {
  106211. this._log("Binary version: " + version);
  106212. }
  106213. switch (version) {
  106214. case 1: return this._parseV1(binaryReader);
  106215. case 2: return this._parseV2(binaryReader);
  106216. }
  106217. throw new Error("Unsupported version: " + version);
  106218. };
  106219. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  106220. var ContentFormat = {
  106221. JSON: 0
  106222. };
  106223. var length = binaryReader.readUint32();
  106224. if (length != binaryReader.getLength()) {
  106225. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106226. }
  106227. var contentLength = binaryReader.readUint32();
  106228. var contentFormat = binaryReader.readUint32();
  106229. var content;
  106230. switch (contentFormat) {
  106231. case ContentFormat.JSON: {
  106232. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  106233. break;
  106234. }
  106235. default: {
  106236. throw new Error("Unexpected content format: " + contentFormat);
  106237. }
  106238. }
  106239. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  106240. var body = binaryReader.readUint8Array(bytesRemaining);
  106241. return {
  106242. json: content,
  106243. bin: body
  106244. };
  106245. };
  106246. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  106247. var ChunkFormat = {
  106248. JSON: 0x4E4F534A,
  106249. BIN: 0x004E4942
  106250. };
  106251. var length = binaryReader.readUint32();
  106252. if (length !== binaryReader.getLength()) {
  106253. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106254. }
  106255. // JSON chunk
  106256. var chunkLength = binaryReader.readUint32();
  106257. var chunkFormat = binaryReader.readUint32();
  106258. if (chunkFormat !== ChunkFormat.JSON) {
  106259. throw new Error("First chunk format is not JSON");
  106260. }
  106261. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  106262. // Look for BIN chunk
  106263. var bin = null;
  106264. while (binaryReader.getPosition() < binaryReader.getLength()) {
  106265. var chunkLength_1 = binaryReader.readUint32();
  106266. var chunkFormat_1 = binaryReader.readUint32();
  106267. switch (chunkFormat_1) {
  106268. case ChunkFormat.JSON: {
  106269. throw new Error("Unexpected JSON chunk");
  106270. }
  106271. case ChunkFormat.BIN: {
  106272. bin = binaryReader.readUint8Array(chunkLength_1);
  106273. break;
  106274. }
  106275. default: {
  106276. // ignore unrecognized chunkFormat
  106277. binaryReader.skipBytes(chunkLength_1);
  106278. break;
  106279. }
  106280. }
  106281. }
  106282. return {
  106283. json: json,
  106284. bin: bin
  106285. };
  106286. };
  106287. GLTFFileLoader._parseVersion = function (version) {
  106288. if (version === "1.0" || version === "1.0.1") {
  106289. return {
  106290. major: 1,
  106291. minor: 0
  106292. };
  106293. }
  106294. var match = (version + "").match(/^(\d+)\.(\d+)/);
  106295. if (!match) {
  106296. return null;
  106297. }
  106298. return {
  106299. major: parseInt(match[1]),
  106300. minor: parseInt(match[2])
  106301. };
  106302. };
  106303. GLTFFileLoader._compareVersion = function (a, b) {
  106304. if (a.major > b.major)
  106305. return 1;
  106306. if (a.major < b.major)
  106307. return -1;
  106308. if (a.minor > b.minor)
  106309. return 1;
  106310. if (a.minor < b.minor)
  106311. return -1;
  106312. return 0;
  106313. };
  106314. GLTFFileLoader._decodeBufferToText = function (buffer) {
  106315. var result = "";
  106316. var length = buffer.byteLength;
  106317. for (var i = 0; i < length; i++) {
  106318. result += String.fromCharCode(buffer[i]);
  106319. }
  106320. return result;
  106321. };
  106322. /** @hidden */
  106323. GLTFFileLoader.prototype._logOpen = function (message) {
  106324. this._log(message);
  106325. this._logIndentLevel++;
  106326. };
  106327. /** @hidden */
  106328. GLTFFileLoader.prototype._logClose = function () {
  106329. --this._logIndentLevel;
  106330. };
  106331. GLTFFileLoader.prototype._logEnabled = function (message) {
  106332. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  106333. BABYLON.Tools.Log("" + spaces + message);
  106334. };
  106335. GLTFFileLoader.prototype._logDisabled = function (message) {
  106336. };
  106337. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  106338. BABYLON.Tools.StartPerformanceCounter(counterName);
  106339. };
  106340. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  106341. };
  106342. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  106343. BABYLON.Tools.EndPerformanceCounter(counterName);
  106344. };
  106345. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  106346. };
  106347. // #endregion
  106348. // #region V1 options
  106349. /**
  106350. * 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.
  106351. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  106352. * Defaults to true.
  106353. * @hidden
  106354. */
  106355. GLTFFileLoader.IncrementalLoading = true;
  106356. /**
  106357. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  106358. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  106359. * @hidden
  106360. */
  106361. GLTFFileLoader.HomogeneousCoordinates = false;
  106362. GLTFFileLoader._logSpaces = " ";
  106363. return GLTFFileLoader;
  106364. }());
  106365. BABYLON.GLTFFileLoader = GLTFFileLoader;
  106366. var BinaryReader = /** @class */ (function () {
  106367. function BinaryReader(arrayBuffer) {
  106368. this._arrayBuffer = arrayBuffer;
  106369. this._dataView = new DataView(arrayBuffer);
  106370. this._byteOffset = 0;
  106371. }
  106372. BinaryReader.prototype.getPosition = function () {
  106373. return this._byteOffset;
  106374. };
  106375. BinaryReader.prototype.getLength = function () {
  106376. return this._arrayBuffer.byteLength;
  106377. };
  106378. BinaryReader.prototype.readUint32 = function () {
  106379. var value = this._dataView.getUint32(this._byteOffset, true);
  106380. this._byteOffset += 4;
  106381. return value;
  106382. };
  106383. BinaryReader.prototype.readUint8Array = function (length) {
  106384. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  106385. this._byteOffset += length;
  106386. return value;
  106387. };
  106388. BinaryReader.prototype.skipBytes = function (length) {
  106389. this._byteOffset += length;
  106390. };
  106391. return BinaryReader;
  106392. }());
  106393. if (BABYLON.SceneLoader) {
  106394. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106395. }
  106396. })(BABYLON || (BABYLON = {}));
  106397. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106398. var BABYLON;
  106399. (function (BABYLON) {
  106400. var GLTF1;
  106401. (function (GLTF1) {
  106402. /**
  106403. * Enums
  106404. */
  106405. var EComponentType;
  106406. (function (EComponentType) {
  106407. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106408. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106409. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106410. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106411. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106412. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106413. var EShaderType;
  106414. (function (EShaderType) {
  106415. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106416. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106417. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106418. var EParameterType;
  106419. (function (EParameterType) {
  106420. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106421. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106422. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106423. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106424. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106425. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106426. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106427. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106428. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106429. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106430. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106431. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106432. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106433. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106434. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106435. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106436. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106437. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106438. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106439. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106440. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106441. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106442. var ETextureWrapMode;
  106443. (function (ETextureWrapMode) {
  106444. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106445. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106446. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106447. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106448. var ETextureFilterType;
  106449. (function (ETextureFilterType) {
  106450. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106451. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106452. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106453. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106454. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106455. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106456. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106457. var ETextureFormat;
  106458. (function (ETextureFormat) {
  106459. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106460. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106461. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106462. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106463. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106464. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106465. var ECullingType;
  106466. (function (ECullingType) {
  106467. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106468. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106469. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106470. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106471. var EBlendingFunction;
  106472. (function (EBlendingFunction) {
  106473. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106474. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106475. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106476. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106477. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106478. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106479. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106480. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106481. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106482. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106483. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106484. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106485. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106486. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106487. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106488. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106489. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106490. })(BABYLON || (BABYLON = {}));
  106491. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106492. var BABYLON;
  106493. (function (BABYLON) {
  106494. var GLTF1;
  106495. (function (GLTF1) {
  106496. /**
  106497. * Tokenizer. Used for shaders compatibility
  106498. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106499. */
  106500. var ETokenType;
  106501. (function (ETokenType) {
  106502. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106503. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106504. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106505. })(ETokenType || (ETokenType = {}));
  106506. var Tokenizer = /** @class */ (function () {
  106507. function Tokenizer(toParse) {
  106508. this._pos = 0;
  106509. this.currentToken = ETokenType.UNKNOWN;
  106510. this.currentIdentifier = "";
  106511. this.currentString = "";
  106512. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106513. this._toParse = toParse;
  106514. this._maxPos = toParse.length;
  106515. }
  106516. Tokenizer.prototype.getNextToken = function () {
  106517. if (this.isEnd())
  106518. return ETokenType.END_OF_INPUT;
  106519. this.currentString = this.read();
  106520. this.currentToken = ETokenType.UNKNOWN;
  106521. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106522. this.currentToken = ETokenType.IDENTIFIER;
  106523. this.currentIdentifier = this.currentString;
  106524. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106525. this.currentIdentifier += this.currentString;
  106526. this.forward();
  106527. }
  106528. }
  106529. return this.currentToken;
  106530. };
  106531. Tokenizer.prototype.peek = function () {
  106532. return this._toParse[this._pos];
  106533. };
  106534. Tokenizer.prototype.read = function () {
  106535. return this._toParse[this._pos++];
  106536. };
  106537. Tokenizer.prototype.forward = function () {
  106538. this._pos++;
  106539. };
  106540. Tokenizer.prototype.isEnd = function () {
  106541. return this._pos >= this._maxPos;
  106542. };
  106543. return Tokenizer;
  106544. }());
  106545. /**
  106546. * Values
  106547. */
  106548. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106549. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106550. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106551. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106552. /**
  106553. * Parse
  106554. */
  106555. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106556. for (var buf in parsedBuffers) {
  106557. var parsedBuffer = parsedBuffers[buf];
  106558. gltfRuntime.buffers[buf] = parsedBuffer;
  106559. gltfRuntime.buffersCount++;
  106560. }
  106561. };
  106562. var parseShaders = function (parsedShaders, gltfRuntime) {
  106563. for (var sha in parsedShaders) {
  106564. var parsedShader = parsedShaders[sha];
  106565. gltfRuntime.shaders[sha] = parsedShader;
  106566. gltfRuntime.shaderscount++;
  106567. }
  106568. };
  106569. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106570. for (var object in parsedObjects) {
  106571. var parsedObject = parsedObjects[object];
  106572. gltfRuntime[runtimeProperty][object] = parsedObject;
  106573. }
  106574. };
  106575. /**
  106576. * Utils
  106577. */
  106578. var normalizeUVs = function (buffer) {
  106579. if (!buffer) {
  106580. return;
  106581. }
  106582. for (var i = 0; i < buffer.length / 2; i++) {
  106583. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106584. }
  106585. };
  106586. var getAttribute = function (attributeParameter) {
  106587. if (attributeParameter.semantic === "NORMAL") {
  106588. return "normal";
  106589. }
  106590. else if (attributeParameter.semantic === "POSITION") {
  106591. return "position";
  106592. }
  106593. else if (attributeParameter.semantic === "JOINT") {
  106594. return "matricesIndices";
  106595. }
  106596. else if (attributeParameter.semantic === "WEIGHT") {
  106597. return "matricesWeights";
  106598. }
  106599. else if (attributeParameter.semantic === "COLOR") {
  106600. return "color";
  106601. }
  106602. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106603. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106604. return "uv" + (channel === 0 ? "" : channel + 1);
  106605. }
  106606. return null;
  106607. };
  106608. /**
  106609. * Loads and creates animations
  106610. */
  106611. var loadAnimations = function (gltfRuntime) {
  106612. for (var anim in gltfRuntime.animations) {
  106613. var animation = gltfRuntime.animations[anim];
  106614. if (!animation.channels || !animation.samplers) {
  106615. continue;
  106616. }
  106617. var lastAnimation = null;
  106618. for (var i = 0; i < animation.channels.length; i++) {
  106619. // Get parameters and load buffers
  106620. var channel = animation.channels[i];
  106621. var sampler = animation.samplers[channel.sampler];
  106622. if (!sampler) {
  106623. continue;
  106624. }
  106625. var inputData = null;
  106626. var outputData = null;
  106627. if (animation.parameters) {
  106628. inputData = animation.parameters[sampler.input];
  106629. outputData = animation.parameters[sampler.output];
  106630. }
  106631. else {
  106632. inputData = sampler.input;
  106633. outputData = sampler.output;
  106634. }
  106635. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106636. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106637. var targetID = channel.target.id;
  106638. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106639. if (targetNode === null) {
  106640. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106641. }
  106642. if (targetNode === null) {
  106643. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106644. continue;
  106645. }
  106646. var isBone = targetNode instanceof BABYLON.Bone;
  106647. // Get target path (position, rotation or scaling)
  106648. var targetPath = channel.target.path;
  106649. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106650. if (targetPathIndex !== -1) {
  106651. targetPath = babylonAnimationPaths[targetPathIndex];
  106652. }
  106653. // Determine animation type
  106654. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  106655. if (!isBone) {
  106656. if (targetPath === "rotationQuaternion") {
  106657. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106658. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  106659. }
  106660. else {
  106661. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106662. }
  106663. }
  106664. // Create animation and key frames
  106665. var babylonAnimation = null;
  106666. var keys = [];
  106667. var arrayOffset = 0;
  106668. var modifyKey = false;
  106669. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  106670. babylonAnimation = lastAnimation;
  106671. modifyKey = true;
  106672. }
  106673. if (!modifyKey) {
  106674. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  106675. }
  106676. // For each frame
  106677. for (var j = 0; j < bufferInput.length; j++) {
  106678. var value = null;
  106679. if (targetPath === "rotationQuaternion") { // VEC4
  106680. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  106681. arrayOffset += 4;
  106682. }
  106683. else { // Position and scaling are VEC3
  106684. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  106685. arrayOffset += 3;
  106686. }
  106687. if (isBone) {
  106688. var bone = targetNode;
  106689. var translation = BABYLON.Vector3.Zero();
  106690. var rotationQuaternion = new BABYLON.Quaternion();
  106691. var scaling = BABYLON.Vector3.Zero();
  106692. // Warning on decompose
  106693. var mat = bone.getBaseMatrix();
  106694. if (modifyKey && lastAnimation) {
  106695. mat = lastAnimation.getKeys()[j].value;
  106696. }
  106697. mat.decompose(scaling, rotationQuaternion, translation);
  106698. if (targetPath === "position") {
  106699. translation = value;
  106700. }
  106701. else if (targetPath === "rotationQuaternion") {
  106702. rotationQuaternion = value;
  106703. }
  106704. else {
  106705. scaling = value;
  106706. }
  106707. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  106708. }
  106709. if (!modifyKey) {
  106710. keys.push({
  106711. frame: bufferInput[j],
  106712. value: value
  106713. });
  106714. }
  106715. else if (lastAnimation) {
  106716. lastAnimation.getKeys()[j].value = value;
  106717. }
  106718. }
  106719. // Finish
  106720. if (!modifyKey && babylonAnimation) {
  106721. babylonAnimation.setKeys(keys);
  106722. targetNode.animations.push(babylonAnimation);
  106723. }
  106724. lastAnimation = babylonAnimation;
  106725. gltfRuntime.scene.stopAnimation(targetNode);
  106726. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  106727. }
  106728. }
  106729. };
  106730. /**
  106731. * Returns the bones transformation matrix
  106732. */
  106733. var configureBoneTransformation = function (node) {
  106734. var mat = null;
  106735. if (node.translation || node.rotation || node.scale) {
  106736. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  106737. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  106738. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  106739. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  106740. }
  106741. else {
  106742. mat = BABYLON.Matrix.FromArray(node.matrix);
  106743. }
  106744. return mat;
  106745. };
  106746. /**
  106747. * Returns the parent bone
  106748. */
  106749. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  106750. // Try to find
  106751. for (var i = 0; i < newSkeleton.bones.length; i++) {
  106752. if (newSkeleton.bones[i].name === jointName) {
  106753. return newSkeleton.bones[i];
  106754. }
  106755. }
  106756. // Not found, search in gltf nodes
  106757. var nodes = gltfRuntime.nodes;
  106758. for (var nde in nodes) {
  106759. var node = nodes[nde];
  106760. if (!node.jointName) {
  106761. continue;
  106762. }
  106763. var children = node.children;
  106764. for (var i = 0; i < children.length; i++) {
  106765. var child = gltfRuntime.nodes[children[i]];
  106766. if (!child.jointName) {
  106767. continue;
  106768. }
  106769. if (child.jointName === jointName) {
  106770. var mat = configureBoneTransformation(node);
  106771. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  106772. bone.id = nde;
  106773. return bone;
  106774. }
  106775. }
  106776. }
  106777. return null;
  106778. };
  106779. /**
  106780. * Returns the appropriate root node
  106781. */
  106782. var getNodeToRoot = function (nodesToRoot, id) {
  106783. for (var i = 0; i < nodesToRoot.length; i++) {
  106784. var nodeToRoot = nodesToRoot[i];
  106785. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  106786. var child = nodeToRoot.node.children[j];
  106787. if (child === id) {
  106788. return nodeToRoot.bone;
  106789. }
  106790. }
  106791. }
  106792. return null;
  106793. };
  106794. /**
  106795. * Returns the node with the joint name
  106796. */
  106797. var getJointNode = function (gltfRuntime, jointName) {
  106798. var nodes = gltfRuntime.nodes;
  106799. var node = nodes[jointName];
  106800. if (node) {
  106801. return {
  106802. node: node,
  106803. id: jointName
  106804. };
  106805. }
  106806. for (var nde in nodes) {
  106807. node = nodes[nde];
  106808. if (node.jointName === jointName) {
  106809. return {
  106810. node: node,
  106811. id: nde
  106812. };
  106813. }
  106814. }
  106815. return null;
  106816. };
  106817. /**
  106818. * Checks if a nodes is in joints
  106819. */
  106820. var nodeIsInJoints = function (skins, id) {
  106821. for (var i = 0; i < skins.jointNames.length; i++) {
  106822. if (skins.jointNames[i] === id) {
  106823. return true;
  106824. }
  106825. }
  106826. return false;
  106827. };
  106828. /**
  106829. * Fills the nodes to root for bones and builds hierarchy
  106830. */
  106831. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  106832. // Creates nodes for root
  106833. for (var nde in gltfRuntime.nodes) {
  106834. var node = gltfRuntime.nodes[nde];
  106835. var id = nde;
  106836. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  106837. continue;
  106838. }
  106839. // Create node to root bone
  106840. var mat = configureBoneTransformation(node);
  106841. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  106842. bone.id = id;
  106843. nodesToRoot.push({ bone: bone, node: node, id: id });
  106844. }
  106845. // Parenting
  106846. for (var i = 0; i < nodesToRoot.length; i++) {
  106847. var nodeToRoot = nodesToRoot[i];
  106848. var children = nodeToRoot.node.children;
  106849. for (var j = 0; j < children.length; j++) {
  106850. var child = null;
  106851. for (var k = 0; k < nodesToRoot.length; k++) {
  106852. if (nodesToRoot[k].id === children[j]) {
  106853. child = nodesToRoot[k];
  106854. break;
  106855. }
  106856. }
  106857. if (child) {
  106858. child.bone._parent = nodeToRoot.bone;
  106859. nodeToRoot.bone.children.push(child.bone);
  106860. }
  106861. }
  106862. }
  106863. };
  106864. /**
  106865. * Imports a skeleton
  106866. */
  106867. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  106868. if (!newSkeleton) {
  106869. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  106870. }
  106871. if (!skins.babylonSkeleton) {
  106872. return newSkeleton;
  106873. }
  106874. // Find the root bones
  106875. var nodesToRoot = [];
  106876. var nodesToRootToAdd = [];
  106877. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  106878. newSkeleton.bones = [];
  106879. // Joints
  106880. for (var i = 0; i < skins.jointNames.length; i++) {
  106881. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106882. if (!jointNode) {
  106883. continue;
  106884. }
  106885. var node = jointNode.node;
  106886. if (!node) {
  106887. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  106888. continue;
  106889. }
  106890. var id = jointNode.id;
  106891. // Optimize, if the bone already exists...
  106892. var existingBone = gltfRuntime.scene.getBoneByID(id);
  106893. if (existingBone) {
  106894. newSkeleton.bones.push(existingBone);
  106895. continue;
  106896. }
  106897. // Search for parent bone
  106898. var foundBone = false;
  106899. var parentBone = null;
  106900. for (var j = 0; j < i; j++) {
  106901. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  106902. if (!jointNode_1) {
  106903. continue;
  106904. }
  106905. var joint = jointNode_1.node;
  106906. if (!joint) {
  106907. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  106908. continue;
  106909. }
  106910. var children = joint.children;
  106911. if (!children) {
  106912. continue;
  106913. }
  106914. foundBone = false;
  106915. for (var k = 0; k < children.length; k++) {
  106916. if (children[k] === id) {
  106917. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  106918. foundBone = true;
  106919. break;
  106920. }
  106921. }
  106922. if (foundBone) {
  106923. break;
  106924. }
  106925. }
  106926. // Create bone
  106927. var mat = configureBoneTransformation(node);
  106928. if (!parentBone && nodesToRoot.length > 0) {
  106929. parentBone = getNodeToRoot(nodesToRoot, id);
  106930. if (parentBone) {
  106931. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  106932. nodesToRootToAdd.push(parentBone);
  106933. }
  106934. }
  106935. }
  106936. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  106937. bone.id = id;
  106938. }
  106939. // Polish
  106940. var bones = newSkeleton.bones;
  106941. newSkeleton.bones = [];
  106942. for (var i = 0; i < skins.jointNames.length; i++) {
  106943. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106944. if (!jointNode) {
  106945. continue;
  106946. }
  106947. for (var j = 0; j < bones.length; j++) {
  106948. if (bones[j].id === jointNode.id) {
  106949. newSkeleton.bones.push(bones[j]);
  106950. break;
  106951. }
  106952. }
  106953. }
  106954. newSkeleton.prepare();
  106955. // Finish
  106956. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  106957. newSkeleton.bones.push(nodesToRootToAdd[i]);
  106958. }
  106959. return newSkeleton;
  106960. };
  106961. /**
  106962. * Imports a mesh and its geometries
  106963. */
  106964. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  106965. if (!newMesh) {
  106966. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106967. newMesh.id = id;
  106968. }
  106969. if (!node.babylonNode) {
  106970. return newMesh;
  106971. }
  106972. var subMaterials = [];
  106973. var vertexData = null;
  106974. var verticesStarts = new Array();
  106975. var verticesCounts = new Array();
  106976. var indexStarts = new Array();
  106977. var indexCounts = new Array();
  106978. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106979. var meshID = meshes[meshIndex];
  106980. var mesh = gltfRuntime.meshes[meshID];
  106981. if (!mesh) {
  106982. continue;
  106983. }
  106984. // Positions, normals and UVs
  106985. for (var i = 0; i < mesh.primitives.length; i++) {
  106986. // Temporary vertex data
  106987. var tempVertexData = new BABYLON.VertexData();
  106988. var primitive = mesh.primitives[i];
  106989. if (primitive.mode !== 4) {
  106990. // continue;
  106991. }
  106992. var attributes = primitive.attributes;
  106993. var accessor = null;
  106994. var buffer = null;
  106995. // Set positions, normal and uvs
  106996. for (var semantic in attributes) {
  106997. // Link accessor and buffer view
  106998. accessor = gltfRuntime.accessors[attributes[semantic]];
  106999. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107000. if (semantic === "NORMAL") {
  107001. tempVertexData.normals = new Float32Array(buffer.length);
  107002. tempVertexData.normals.set(buffer);
  107003. }
  107004. else if (semantic === "POSITION") {
  107005. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  107006. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  107007. for (var j = 0; j < buffer.length; j += 4) {
  107008. tempVertexData.positions[j] = buffer[j];
  107009. tempVertexData.positions[j + 1] = buffer[j + 1];
  107010. tempVertexData.positions[j + 2] = buffer[j + 2];
  107011. }
  107012. }
  107013. else {
  107014. tempVertexData.positions = new Float32Array(buffer.length);
  107015. tempVertexData.positions.set(buffer);
  107016. }
  107017. verticesCounts.push(tempVertexData.positions.length);
  107018. }
  107019. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  107020. var channel = Number(semantic.split("_")[1]);
  107021. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  107022. var uvs = new Float32Array(buffer.length);
  107023. uvs.set(buffer);
  107024. normalizeUVs(uvs);
  107025. tempVertexData.set(uvs, uvKind);
  107026. }
  107027. else if (semantic === "JOINT") {
  107028. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  107029. tempVertexData.matricesIndices.set(buffer);
  107030. }
  107031. else if (semantic === "WEIGHT") {
  107032. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  107033. tempVertexData.matricesWeights.set(buffer);
  107034. }
  107035. else if (semantic === "COLOR") {
  107036. tempVertexData.colors = new Float32Array(buffer.length);
  107037. tempVertexData.colors.set(buffer);
  107038. }
  107039. }
  107040. // Indices
  107041. accessor = gltfRuntime.accessors[primitive.indices];
  107042. if (accessor) {
  107043. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107044. tempVertexData.indices = new Int32Array(buffer.length);
  107045. tempVertexData.indices.set(buffer);
  107046. indexCounts.push(tempVertexData.indices.length);
  107047. }
  107048. else {
  107049. // Set indices on the fly
  107050. var indices = [];
  107051. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  107052. indices.push(j);
  107053. }
  107054. tempVertexData.indices = new Int32Array(indices);
  107055. indexCounts.push(tempVertexData.indices.length);
  107056. }
  107057. if (!vertexData) {
  107058. vertexData = tempVertexData;
  107059. }
  107060. else {
  107061. vertexData.merge(tempVertexData);
  107062. }
  107063. // Sub material
  107064. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  107065. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  107066. // Update vertices start and index start
  107067. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  107068. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  107069. }
  107070. }
  107071. var material;
  107072. if (subMaterials.length > 1) {
  107073. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  107074. material.subMaterials = subMaterials;
  107075. }
  107076. else {
  107077. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  107078. }
  107079. if (subMaterials.length === 1) {
  107080. material = subMaterials[0];
  107081. }
  107082. if (!newMesh.material) {
  107083. newMesh.material = material;
  107084. }
  107085. // Apply geometry
  107086. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  107087. newMesh.computeWorldMatrix(true);
  107088. // Apply submeshes
  107089. newMesh.subMeshes = [];
  107090. var index = 0;
  107091. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107092. var meshID = meshes[meshIndex];
  107093. var mesh = gltfRuntime.meshes[meshID];
  107094. if (!mesh) {
  107095. continue;
  107096. }
  107097. for (var i = 0; i < mesh.primitives.length; i++) {
  107098. if (mesh.primitives[i].mode !== 4) {
  107099. //continue;
  107100. }
  107101. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  107102. index++;
  107103. }
  107104. }
  107105. // Finish
  107106. return newMesh;
  107107. };
  107108. /**
  107109. * Configure node transformation from position, rotation and scaling
  107110. */
  107111. var configureNode = function (newNode, position, rotation, scaling) {
  107112. if (newNode.position) {
  107113. newNode.position = position;
  107114. }
  107115. if (newNode.rotationQuaternion || newNode.rotation) {
  107116. newNode.rotationQuaternion = rotation;
  107117. }
  107118. if (newNode.scaling) {
  107119. newNode.scaling = scaling;
  107120. }
  107121. };
  107122. /**
  107123. * Configures node from transformation matrix
  107124. */
  107125. var configureNodeFromMatrix = function (newNode, node, parent) {
  107126. if (node.matrix) {
  107127. var position = new BABYLON.Vector3(0, 0, 0);
  107128. var rotation = new BABYLON.Quaternion();
  107129. var scaling = new BABYLON.Vector3(0, 0, 0);
  107130. var mat = BABYLON.Matrix.FromArray(node.matrix);
  107131. mat.decompose(scaling, rotation, position);
  107132. configureNode(newNode, position, rotation, scaling);
  107133. }
  107134. else if (node.translation && node.rotation && node.scale) {
  107135. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  107136. }
  107137. newNode.computeWorldMatrix(true);
  107138. };
  107139. /**
  107140. * Imports a node
  107141. */
  107142. var importNode = function (gltfRuntime, node, id, parent) {
  107143. var lastNode = null;
  107144. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  107145. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  107146. return null;
  107147. }
  107148. }
  107149. // Meshes
  107150. if (node.skin) {
  107151. if (node.meshes) {
  107152. var skin = gltfRuntime.skins[node.skin];
  107153. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  107154. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  107155. if (newMesh.skeleton === null) {
  107156. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  107157. if (!skin.babylonSkeleton) {
  107158. skin.babylonSkeleton = newMesh.skeleton;
  107159. }
  107160. }
  107161. lastNode = newMesh;
  107162. }
  107163. }
  107164. else if (node.meshes) {
  107165. /**
  107166. * Improve meshes property
  107167. */
  107168. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  107169. lastNode = newMesh;
  107170. }
  107171. // Lights
  107172. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107173. var light = gltfRuntime.lights[node.light];
  107174. if (light) {
  107175. if (light.type === "ambient") {
  107176. var ambienLight = light[light.type];
  107177. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107178. hemiLight.name = node.name || "";
  107179. if (ambienLight.color) {
  107180. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  107181. }
  107182. lastNode = hemiLight;
  107183. }
  107184. else if (light.type === "directional") {
  107185. var directionalLight = light[light.type];
  107186. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107187. dirLight.name = node.name || "";
  107188. if (directionalLight.color) {
  107189. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  107190. }
  107191. lastNode = dirLight;
  107192. }
  107193. else if (light.type === "point") {
  107194. var pointLight = light[light.type];
  107195. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107196. ptLight.name = node.name || "";
  107197. if (pointLight.color) {
  107198. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  107199. }
  107200. lastNode = ptLight;
  107201. }
  107202. else if (light.type === "spot") {
  107203. var spotLight = light[light.type];
  107204. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  107205. spLight.name = node.name || "";
  107206. if (spotLight.color) {
  107207. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  107208. }
  107209. if (spotLight.fallOfAngle) {
  107210. spLight.angle = spotLight.fallOfAngle;
  107211. }
  107212. if (spotLight.fallOffExponent) {
  107213. spLight.exponent = spotLight.fallOffExponent;
  107214. }
  107215. lastNode = spLight;
  107216. }
  107217. }
  107218. }
  107219. // Cameras
  107220. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107221. var camera = gltfRuntime.cameras[node.camera];
  107222. if (camera) {
  107223. if (camera.type === "orthographic") {
  107224. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  107225. orthoCamera.name = node.name || "";
  107226. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107227. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107228. lastNode = orthoCamera;
  107229. }
  107230. else if (camera.type === "perspective") {
  107231. var perspectiveCamera = camera[camera.type];
  107232. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  107233. persCamera.name = node.name || "";
  107234. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107235. if (!perspectiveCamera.aspectRatio) {
  107236. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  107237. }
  107238. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  107239. persCamera.maxZ = perspectiveCamera.zfar;
  107240. persCamera.minZ = perspectiveCamera.znear;
  107241. }
  107242. lastNode = persCamera;
  107243. }
  107244. }
  107245. }
  107246. // Empty node
  107247. if (!node.jointName) {
  107248. if (node.babylonNode) {
  107249. return node.babylonNode;
  107250. }
  107251. else if (lastNode === null) {
  107252. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107253. node.babylonNode = dummy;
  107254. lastNode = dummy;
  107255. }
  107256. }
  107257. if (lastNode !== null) {
  107258. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  107259. configureNodeFromMatrix(lastNode, node, parent);
  107260. }
  107261. else {
  107262. var translation = node.translation || [0, 0, 0];
  107263. var rotation = node.rotation || [0, 0, 0, 1];
  107264. var scale = node.scale || [1, 1, 1];
  107265. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  107266. }
  107267. lastNode.updateCache(true);
  107268. node.babylonNode = lastNode;
  107269. }
  107270. return lastNode;
  107271. };
  107272. /**
  107273. * Traverses nodes and creates them
  107274. */
  107275. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  107276. if (meshIncluded === void 0) { meshIncluded = false; }
  107277. var node = gltfRuntime.nodes[id];
  107278. var newNode = null;
  107279. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  107280. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  107281. meshIncluded = true;
  107282. }
  107283. else {
  107284. meshIncluded = false;
  107285. }
  107286. }
  107287. else {
  107288. meshIncluded = true;
  107289. }
  107290. if (!node.jointName && meshIncluded) {
  107291. newNode = importNode(gltfRuntime, node, id, parent);
  107292. if (newNode !== null) {
  107293. newNode.id = id;
  107294. newNode.parent = parent;
  107295. }
  107296. }
  107297. if (node.children) {
  107298. for (var i = 0; i < node.children.length; i++) {
  107299. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  107300. }
  107301. }
  107302. };
  107303. /**
  107304. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  107305. */
  107306. var postLoad = function (gltfRuntime) {
  107307. // Nodes
  107308. var currentScene = gltfRuntime.currentScene;
  107309. if (currentScene) {
  107310. for (var i = 0; i < currentScene.nodes.length; i++) {
  107311. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107312. }
  107313. }
  107314. else {
  107315. for (var thing in gltfRuntime.scenes) {
  107316. currentScene = gltfRuntime.scenes[thing];
  107317. for (var i = 0; i < currentScene.nodes.length; i++) {
  107318. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107319. }
  107320. }
  107321. }
  107322. // Set animations
  107323. loadAnimations(gltfRuntime);
  107324. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  107325. var skeleton = gltfRuntime.scene.skeletons[i];
  107326. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  107327. }
  107328. };
  107329. /**
  107330. * onBind shaderrs callback to set uniforms and matrices
  107331. */
  107332. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  107333. var materialValues = material.values || technique.parameters;
  107334. for (var unif in unTreatedUniforms) {
  107335. var uniform = unTreatedUniforms[unif];
  107336. var type = uniform.type;
  107337. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  107338. if (uniform.semantic && !uniform.source && !uniform.node) {
  107339. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  107340. }
  107341. else if (uniform.semantic && (uniform.source || uniform.node)) {
  107342. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  107343. if (source === null) {
  107344. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  107345. }
  107346. if (source === null) {
  107347. continue;
  107348. }
  107349. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  107350. }
  107351. }
  107352. else {
  107353. var value = materialValues[technique.uniforms[unif]];
  107354. if (!value) {
  107355. continue;
  107356. }
  107357. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107358. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  107359. if (texture === null || texture === undefined) {
  107360. continue;
  107361. }
  107362. shaderMaterial.getEffect().setTexture(unif, texture);
  107363. }
  107364. else {
  107365. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  107366. }
  107367. }
  107368. }
  107369. onSuccess(shaderMaterial);
  107370. };
  107371. /**
  107372. * Prepare uniforms to send the only one time
  107373. * Loads the appropriate textures
  107374. */
  107375. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  107376. var materialValues = material.values || technique.parameters;
  107377. var techniqueUniforms = technique.uniforms;
  107378. /**
  107379. * Prepare values here (not matrices)
  107380. */
  107381. for (var unif in unTreatedUniforms) {
  107382. var uniform = unTreatedUniforms[unif];
  107383. var type = uniform.type;
  107384. var value = materialValues[techniqueUniforms[unif]];
  107385. if (value === undefined) {
  107386. // In case the value is the same for all materials
  107387. value = uniform.value;
  107388. }
  107389. if (!value) {
  107390. continue;
  107391. }
  107392. var onLoadTexture = function (uniformName) {
  107393. return function (texture) {
  107394. if (uniform.value && uniformName) {
  107395. // Static uniform
  107396. shaderMaterial.setTexture(uniformName, texture);
  107397. delete unTreatedUniforms[uniformName];
  107398. }
  107399. };
  107400. };
  107401. // Texture (sampler2D)
  107402. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107403. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107404. }
  107405. // Others
  107406. else {
  107407. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107408. // Static uniform
  107409. delete unTreatedUniforms[unif];
  107410. }
  107411. }
  107412. }
  107413. };
  107414. /**
  107415. * Shader compilation failed
  107416. */
  107417. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107418. return function (effect, error) {
  107419. shaderMaterial.dispose(true);
  107420. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107421. };
  107422. };
  107423. /**
  107424. * Shader compilation success
  107425. */
  107426. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107427. return function (_) {
  107428. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107429. shaderMaterial.onBind = function (mesh) {
  107430. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107431. };
  107432. };
  107433. };
  107434. /**
  107435. * Returns the appropriate uniform if already handled by babylon
  107436. */
  107437. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107438. for (var unif in technique.uniforms) {
  107439. var uniform = technique.uniforms[unif];
  107440. var uniformParameter = technique.parameters[uniform];
  107441. if (tokenizer.currentIdentifier === unif) {
  107442. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107443. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107444. if (transformIndex !== -1) {
  107445. delete unTreatedUniforms[unif];
  107446. return babylonTransforms[transformIndex];
  107447. }
  107448. }
  107449. }
  107450. }
  107451. return tokenizer.currentIdentifier;
  107452. };
  107453. /**
  107454. * All shaders loaded. Create materials one by one
  107455. */
  107456. var importMaterials = function (gltfRuntime) {
  107457. // Create materials
  107458. for (var mat in gltfRuntime.materials) {
  107459. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107460. }
  107461. };
  107462. /**
  107463. * Implementation of the base glTF spec
  107464. */
  107465. var GLTFLoaderBase = /** @class */ (function () {
  107466. function GLTFLoaderBase() {
  107467. }
  107468. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107469. var gltfRuntime = {
  107470. extensions: {},
  107471. accessors: {},
  107472. buffers: {},
  107473. bufferViews: {},
  107474. meshes: {},
  107475. lights: {},
  107476. cameras: {},
  107477. nodes: {},
  107478. images: {},
  107479. textures: {},
  107480. shaders: {},
  107481. programs: {},
  107482. samplers: {},
  107483. techniques: {},
  107484. materials: {},
  107485. animations: {},
  107486. skins: {},
  107487. extensionsUsed: [],
  107488. scenes: {},
  107489. buffersCount: 0,
  107490. shaderscount: 0,
  107491. scene: scene,
  107492. rootUrl: rootUrl,
  107493. loadedBufferCount: 0,
  107494. loadedBufferViews: {},
  107495. loadedShaderCount: 0,
  107496. importOnlyMeshes: false,
  107497. dummyNodes: []
  107498. };
  107499. // Parse
  107500. if (parsedData.extensions) {
  107501. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107502. }
  107503. if (parsedData.extensionsUsed) {
  107504. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107505. }
  107506. if (parsedData.buffers) {
  107507. parseBuffers(parsedData.buffers, gltfRuntime);
  107508. }
  107509. if (parsedData.bufferViews) {
  107510. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107511. }
  107512. if (parsedData.accessors) {
  107513. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107514. }
  107515. if (parsedData.meshes) {
  107516. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107517. }
  107518. if (parsedData.lights) {
  107519. parseObject(parsedData.lights, "lights", gltfRuntime);
  107520. }
  107521. if (parsedData.cameras) {
  107522. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107523. }
  107524. if (parsedData.nodes) {
  107525. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107526. }
  107527. if (parsedData.images) {
  107528. parseObject(parsedData.images, "images", gltfRuntime);
  107529. }
  107530. if (parsedData.textures) {
  107531. parseObject(parsedData.textures, "textures", gltfRuntime);
  107532. }
  107533. if (parsedData.shaders) {
  107534. parseShaders(parsedData.shaders, gltfRuntime);
  107535. }
  107536. if (parsedData.programs) {
  107537. parseObject(parsedData.programs, "programs", gltfRuntime);
  107538. }
  107539. if (parsedData.samplers) {
  107540. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107541. }
  107542. if (parsedData.techniques) {
  107543. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107544. }
  107545. if (parsedData.materials) {
  107546. parseObject(parsedData.materials, "materials", gltfRuntime);
  107547. }
  107548. if (parsedData.animations) {
  107549. parseObject(parsedData.animations, "animations", gltfRuntime);
  107550. }
  107551. if (parsedData.skins) {
  107552. parseObject(parsedData.skins, "skins", gltfRuntime);
  107553. }
  107554. if (parsedData.scenes) {
  107555. gltfRuntime.scenes = parsedData.scenes;
  107556. }
  107557. if (parsedData.scene && parsedData.scenes) {
  107558. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107559. }
  107560. return gltfRuntime;
  107561. };
  107562. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107563. var buffer = gltfRuntime.buffers[id];
  107564. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107565. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107566. }
  107567. else {
  107568. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107569. if (request) {
  107570. onError(request.status + " " + request.statusText);
  107571. }
  107572. });
  107573. }
  107574. };
  107575. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107576. var texture = gltfRuntime.textures[id];
  107577. if (!texture || !texture.source) {
  107578. onError("");
  107579. return;
  107580. }
  107581. if (texture.babylonTexture) {
  107582. onSuccess(null);
  107583. return;
  107584. }
  107585. var source = gltfRuntime.images[texture.source];
  107586. if (BABYLON.Tools.IsBase64(source.uri)) {
  107587. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107588. }
  107589. else {
  107590. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107591. if (request) {
  107592. onError(request.status + " " + request.statusText);
  107593. }
  107594. });
  107595. }
  107596. };
  107597. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107598. var texture = gltfRuntime.textures[id];
  107599. if (texture.babylonTexture) {
  107600. onSuccess(texture.babylonTexture);
  107601. return;
  107602. }
  107603. var sampler = gltfRuntime.samplers[texture.sampler];
  107604. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107605. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107606. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107607. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107608. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107609. var blob = new Blob([buffer]);
  107610. var blobURL = URL.createObjectURL(blob);
  107611. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107612. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107613. if (sampler.wrapS !== undefined) {
  107614. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107615. }
  107616. if (sampler.wrapT !== undefined) {
  107617. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107618. }
  107619. newTexture.name = id;
  107620. texture.babylonTexture = newTexture;
  107621. onSuccess(newTexture);
  107622. };
  107623. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107624. var shader = gltfRuntime.shaders[id];
  107625. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107626. var shaderString = atob(shader.uri.split(",")[1]);
  107627. if (onSuccess) {
  107628. onSuccess(shaderString);
  107629. }
  107630. }
  107631. else {
  107632. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107633. if (request && onError) {
  107634. onError(request.status + " " + request.statusText);
  107635. }
  107636. });
  107637. }
  107638. };
  107639. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107640. var material = gltfRuntime.materials[id];
  107641. if (!material.technique) {
  107642. if (onError) {
  107643. onError("No technique found.");
  107644. }
  107645. return;
  107646. }
  107647. var technique = gltfRuntime.techniques[material.technique];
  107648. if (!technique) {
  107649. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107650. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  107651. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107652. onSuccess(defaultMaterial);
  107653. return;
  107654. }
  107655. var program = gltfRuntime.programs[technique.program];
  107656. var states = technique.states;
  107657. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  107658. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  107659. var newVertexShader = "";
  107660. var newPixelShader = "";
  107661. var vertexTokenizer = new Tokenizer(vertexShader);
  107662. var pixelTokenizer = new Tokenizer(pixelShader);
  107663. var unTreatedUniforms = {};
  107664. var uniforms = [];
  107665. var attributes = [];
  107666. var samplers = [];
  107667. // Fill uniform, sampler2D and attributes
  107668. for (var unif in technique.uniforms) {
  107669. var uniform = technique.uniforms[unif];
  107670. var uniformParameter = technique.parameters[uniform];
  107671. unTreatedUniforms[unif] = uniformParameter;
  107672. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  107673. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107674. if (transformIndex !== -1) {
  107675. uniforms.push(babylonTransforms[transformIndex]);
  107676. delete unTreatedUniforms[unif];
  107677. }
  107678. else {
  107679. uniforms.push(unif);
  107680. }
  107681. }
  107682. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  107683. samplers.push(unif);
  107684. }
  107685. else {
  107686. uniforms.push(unif);
  107687. }
  107688. }
  107689. for (var attr in technique.attributes) {
  107690. var attribute = technique.attributes[attr];
  107691. var attributeParameter = technique.parameters[attribute];
  107692. if (attributeParameter.semantic) {
  107693. attributes.push(getAttribute(attributeParameter));
  107694. }
  107695. }
  107696. // Configure vertex shader
  107697. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  107698. var tokenType = vertexTokenizer.currentToken;
  107699. if (tokenType !== ETokenType.IDENTIFIER) {
  107700. newVertexShader += vertexTokenizer.currentString;
  107701. continue;
  107702. }
  107703. var foundAttribute = false;
  107704. for (var attr in technique.attributes) {
  107705. var attribute = technique.attributes[attr];
  107706. var attributeParameter = technique.parameters[attribute];
  107707. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  107708. newVertexShader += getAttribute(attributeParameter);
  107709. foundAttribute = true;
  107710. break;
  107711. }
  107712. }
  107713. if (foundAttribute) {
  107714. continue;
  107715. }
  107716. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  107717. }
  107718. // Configure pixel shader
  107719. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  107720. var tokenType = pixelTokenizer.currentToken;
  107721. if (tokenType !== ETokenType.IDENTIFIER) {
  107722. newPixelShader += pixelTokenizer.currentString;
  107723. continue;
  107724. }
  107725. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  107726. }
  107727. // Create shader material
  107728. var shaderPath = {
  107729. vertex: program.vertexShader + id,
  107730. fragment: program.fragmentShader + id
  107731. };
  107732. var options = {
  107733. attributes: attributes,
  107734. uniforms: uniforms,
  107735. samplers: samplers,
  107736. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  107737. };
  107738. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  107739. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  107740. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  107741. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  107742. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  107743. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107744. if (states && states.functions) {
  107745. var functions = states.functions;
  107746. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  107747. shaderMaterial.backFaceCulling = false;
  107748. }
  107749. var blendFunc = functions.blendFuncSeparate;
  107750. if (blendFunc) {
  107751. 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) {
  107752. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  107753. }
  107754. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107755. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  107756. }
  107757. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107758. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  107759. }
  107760. 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) {
  107761. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  107762. }
  107763. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107764. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  107765. }
  107766. 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) {
  107767. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  107768. }
  107769. }
  107770. }
  107771. };
  107772. return GLTFLoaderBase;
  107773. }());
  107774. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  107775. /**
  107776. * glTF V1 Loader
  107777. */
  107778. var GLTFLoader = /** @class */ (function () {
  107779. function GLTFLoader() {
  107780. this.state = null;
  107781. }
  107782. GLTFLoader.RegisterExtension = function (extension) {
  107783. if (GLTFLoader.Extensions[extension.name]) {
  107784. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  107785. return;
  107786. }
  107787. GLTFLoader.Extensions[extension.name] = extension;
  107788. };
  107789. GLTFLoader.prototype.dispose = function () {
  107790. // do nothing
  107791. };
  107792. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  107793. var _this = this;
  107794. scene.useRightHandedSystem = true;
  107795. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107796. gltfRuntime.importOnlyMeshes = true;
  107797. if (meshesNames === "") {
  107798. gltfRuntime.importMeshesNames = [];
  107799. }
  107800. else if (typeof meshesNames === "string") {
  107801. gltfRuntime.importMeshesNames = [meshesNames];
  107802. }
  107803. else if (meshesNames && !(meshesNames instanceof Array)) {
  107804. gltfRuntime.importMeshesNames = [meshesNames];
  107805. }
  107806. else {
  107807. gltfRuntime.importMeshesNames = [];
  107808. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  107809. }
  107810. // Create nodes
  107811. _this._createNodes(gltfRuntime);
  107812. var meshes = new Array();
  107813. var skeletons = new Array();
  107814. // Fill arrays of meshes and skeletons
  107815. for (var nde in gltfRuntime.nodes) {
  107816. var node = gltfRuntime.nodes[nde];
  107817. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  107818. meshes.push(node.babylonNode);
  107819. }
  107820. }
  107821. for (var skl in gltfRuntime.skins) {
  107822. var skin = gltfRuntime.skins[skl];
  107823. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  107824. skeletons.push(skin.babylonSkeleton);
  107825. }
  107826. }
  107827. // Load buffers, shaders, materials, etc.
  107828. _this._loadBuffersAsync(gltfRuntime, function () {
  107829. _this._loadShadersAsync(gltfRuntime, function () {
  107830. importMaterials(gltfRuntime);
  107831. postLoad(gltfRuntime);
  107832. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107833. onSuccess(meshes, skeletons);
  107834. }
  107835. });
  107836. }, onProgress);
  107837. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107838. onSuccess(meshes, skeletons);
  107839. }
  107840. }, onError);
  107841. return true;
  107842. };
  107843. /**
  107844. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  107845. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  107846. * @param scene the scene the meshes should be added to
  107847. * @param data gltf data containing information of the meshes in a loaded file
  107848. * @param rootUrl root url to load from
  107849. * @param onProgress event that fires when loading progress has occured
  107850. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  107851. */
  107852. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107853. var _this = this;
  107854. return new Promise(function (resolve, reject) {
  107855. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  107856. resolve({
  107857. meshes: meshes,
  107858. particleSystems: [],
  107859. skeletons: skeletons,
  107860. animationGroups: []
  107861. });
  107862. }, onProgress, function (message) {
  107863. reject(new Error(message));
  107864. });
  107865. });
  107866. };
  107867. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  107868. var _this = this;
  107869. scene.useRightHandedSystem = true;
  107870. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107871. // Load runtime extensios
  107872. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  107873. // Create nodes
  107874. _this._createNodes(gltfRuntime);
  107875. // Load buffers, shaders, materials, etc.
  107876. _this._loadBuffersAsync(gltfRuntime, function () {
  107877. _this._loadShadersAsync(gltfRuntime, function () {
  107878. importMaterials(gltfRuntime);
  107879. postLoad(gltfRuntime);
  107880. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  107881. onSuccess();
  107882. }
  107883. });
  107884. });
  107885. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  107886. onSuccess();
  107887. }
  107888. }, onError);
  107889. }, onError);
  107890. };
  107891. /**
  107892. * Imports all objects from a loaded gltf file and adds them to the scene
  107893. * @param scene the scene the objects should be added to
  107894. * @param data gltf data containing information of the meshes in a loaded file
  107895. * @param rootUrl root url to load from
  107896. * @param onProgress event that fires when loading progress has occured
  107897. * @returns a promise which completes when objects have been loaded to the scene
  107898. */
  107899. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107900. var _this = this;
  107901. return new Promise(function (resolve, reject) {
  107902. _this._loadAsync(scene, data, rootUrl, function () {
  107903. resolve();
  107904. }, onProgress, function (message) {
  107905. reject(new Error(message));
  107906. });
  107907. });
  107908. };
  107909. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  107910. var hasShaders = false;
  107911. var processShader = function (sha, shader) {
  107912. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  107913. if (shaderString instanceof ArrayBuffer) {
  107914. return;
  107915. }
  107916. gltfRuntime.loadedShaderCount++;
  107917. if (shaderString) {
  107918. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  107919. }
  107920. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  107921. onload();
  107922. }
  107923. }, function () {
  107924. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  107925. });
  107926. };
  107927. for (var sha in gltfRuntime.shaders) {
  107928. hasShaders = true;
  107929. var shader = gltfRuntime.shaders[sha];
  107930. if (shader) {
  107931. processShader.bind(this, sha, shader)();
  107932. }
  107933. else {
  107934. BABYLON.Tools.Error("No shader named: " + sha);
  107935. }
  107936. }
  107937. if (!hasShaders) {
  107938. onload();
  107939. }
  107940. };
  107941. ;
  107942. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  107943. var hasBuffers = false;
  107944. var processBuffer = function (buf, buffer) {
  107945. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  107946. gltfRuntime.loadedBufferCount++;
  107947. if (bufferView) {
  107948. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  107949. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  107950. }
  107951. gltfRuntime.loadedBufferViews[buf] = bufferView;
  107952. }
  107953. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  107954. onLoad();
  107955. }
  107956. }, function () {
  107957. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  107958. });
  107959. };
  107960. for (var buf in gltfRuntime.buffers) {
  107961. hasBuffers = true;
  107962. var buffer = gltfRuntime.buffers[buf];
  107963. if (buffer) {
  107964. processBuffer.bind(this, buf, buffer)();
  107965. }
  107966. else {
  107967. BABYLON.Tools.Error("No buffer named: " + buf);
  107968. }
  107969. }
  107970. if (!hasBuffers) {
  107971. onLoad();
  107972. }
  107973. };
  107974. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  107975. var currentScene = gltfRuntime.currentScene;
  107976. if (currentScene) {
  107977. // Only one scene even if multiple scenes are defined
  107978. for (var i = 0; i < currentScene.nodes.length; i++) {
  107979. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107980. }
  107981. }
  107982. else {
  107983. // Load all scenes
  107984. for (var thing in gltfRuntime.scenes) {
  107985. currentScene = gltfRuntime.scenes[thing];
  107986. for (var i = 0; i < currentScene.nodes.length; i++) {
  107987. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107988. }
  107989. }
  107990. }
  107991. };
  107992. GLTFLoader.Extensions = {};
  107993. return GLTFLoader;
  107994. }());
  107995. GLTF1.GLTFLoader = GLTFLoader;
  107996. ;
  107997. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  107998. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107999. })(BABYLON || (BABYLON = {}));
  108000. //# sourceMappingURL=babylon.glTFLoader.js.map
  108001. var BABYLON;
  108002. (function (BABYLON) {
  108003. var GLTF1;
  108004. (function (GLTF1) {
  108005. /**
  108006. * Utils functions for GLTF
  108007. */
  108008. var GLTFUtils = /** @class */ (function () {
  108009. function GLTFUtils() {
  108010. }
  108011. /**
  108012. * Sets the given "parameter" matrix
  108013. * @param scene: the {BABYLON.Scene} object
  108014. * @param source: the source node where to pick the matrix
  108015. * @param parameter: the GLTF technique parameter
  108016. * @param uniformName: the name of the shader's uniform
  108017. * @param shaderMaterial: the shader material
  108018. */
  108019. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  108020. var mat = null;
  108021. if (parameter.semantic === "MODEL") {
  108022. mat = source.getWorldMatrix();
  108023. }
  108024. else if (parameter.semantic === "PROJECTION") {
  108025. mat = scene.getProjectionMatrix();
  108026. }
  108027. else if (parameter.semantic === "VIEW") {
  108028. mat = scene.getViewMatrix();
  108029. }
  108030. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  108031. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  108032. }
  108033. else if (parameter.semantic === "MODELVIEW") {
  108034. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  108035. }
  108036. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  108037. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  108038. }
  108039. else if (parameter.semantic === "MODELINVERSE") {
  108040. mat = source.getWorldMatrix().invert();
  108041. }
  108042. else if (parameter.semantic === "VIEWINVERSE") {
  108043. mat = scene.getViewMatrix().invert();
  108044. }
  108045. else if (parameter.semantic === "PROJECTIONINVERSE") {
  108046. mat = scene.getProjectionMatrix().invert();
  108047. }
  108048. else if (parameter.semantic === "MODELVIEWINVERSE") {
  108049. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  108050. }
  108051. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  108052. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  108053. }
  108054. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  108055. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  108056. }
  108057. else {
  108058. debugger;
  108059. }
  108060. if (mat) {
  108061. switch (parameter.type) {
  108062. case GLTF1.EParameterType.FLOAT_MAT2:
  108063. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  108064. break;
  108065. case GLTF1.EParameterType.FLOAT_MAT3:
  108066. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  108067. break;
  108068. case GLTF1.EParameterType.FLOAT_MAT4:
  108069. shaderMaterial.setMatrix(uniformName, mat);
  108070. break;
  108071. default: break;
  108072. }
  108073. }
  108074. };
  108075. /**
  108076. * Sets the given "parameter" matrix
  108077. * @param shaderMaterial: the shader material
  108078. * @param uniform: the name of the shader's uniform
  108079. * @param value: the value of the uniform
  108080. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  108081. */
  108082. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  108083. switch (type) {
  108084. case GLTF1.EParameterType.FLOAT:
  108085. shaderMaterial.setFloat(uniform, value);
  108086. return true;
  108087. case GLTF1.EParameterType.FLOAT_VEC2:
  108088. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  108089. return true;
  108090. case GLTF1.EParameterType.FLOAT_VEC3:
  108091. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  108092. return true;
  108093. case GLTF1.EParameterType.FLOAT_VEC4:
  108094. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  108095. return true;
  108096. default: return false;
  108097. }
  108098. };
  108099. /**
  108100. * Returns the wrap mode of the texture
  108101. * @param mode: the mode value
  108102. */
  108103. GLTFUtils.GetWrapMode = function (mode) {
  108104. switch (mode) {
  108105. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108106. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108107. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108108. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108109. }
  108110. };
  108111. /**
  108112. * Returns the byte stride giving an accessor
  108113. * @param accessor: the GLTF accessor objet
  108114. */
  108115. GLTFUtils.GetByteStrideFromType = function (accessor) {
  108116. // Needs this function since "byteStride" isn't requiered in glTF format
  108117. var type = accessor.type;
  108118. switch (type) {
  108119. case "VEC2": return 2;
  108120. case "VEC3": return 3;
  108121. case "VEC4": return 4;
  108122. case "MAT2": return 4;
  108123. case "MAT3": return 9;
  108124. case "MAT4": return 16;
  108125. default: return 1;
  108126. }
  108127. };
  108128. /**
  108129. * Returns the texture filter mode giving a mode value
  108130. * @param mode: the filter mode value
  108131. */
  108132. GLTFUtils.GetTextureFilterMode = function (mode) {
  108133. switch (mode) {
  108134. case GLTF1.ETextureFilterType.LINEAR:
  108135. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  108136. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108137. case GLTF1.ETextureFilterType.NEAREST:
  108138. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  108139. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108140. }
  108141. };
  108142. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  108143. var byteOffset = bufferView.byteOffset + byteOffset;
  108144. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  108145. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  108146. throw new Error("Buffer access is out of range");
  108147. }
  108148. var buffer = loadedBufferView.buffer;
  108149. byteOffset += loadedBufferView.byteOffset;
  108150. switch (componentType) {
  108151. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  108152. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  108153. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  108154. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  108155. default: return new Float32Array(buffer, byteOffset, byteLength);
  108156. }
  108157. };
  108158. /**
  108159. * Returns a buffer from its accessor
  108160. * @param gltfRuntime: the GLTF runtime
  108161. * @param accessor: the GLTF accessor
  108162. */
  108163. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  108164. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  108165. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  108166. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  108167. };
  108168. /**
  108169. * Decodes a buffer view into a string
  108170. * @param view: the buffer view
  108171. */
  108172. GLTFUtils.DecodeBufferToText = function (view) {
  108173. var result = "";
  108174. var length = view.byteLength;
  108175. for (var i = 0; i < length; ++i) {
  108176. result += String.fromCharCode(view[i]);
  108177. }
  108178. return result;
  108179. };
  108180. /**
  108181. * Returns the default material of gltf. Related to
  108182. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  108183. * @param scene: the Babylon.js scene
  108184. */
  108185. GLTFUtils.GetDefaultMaterial = function (scene) {
  108186. if (!GLTFUtils._DefaultMaterial) {
  108187. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  108188. "precision highp float;",
  108189. "",
  108190. "uniform mat4 worldView;",
  108191. "uniform mat4 projection;",
  108192. "",
  108193. "attribute vec3 position;",
  108194. "",
  108195. "void main(void)",
  108196. "{",
  108197. " gl_Position = projection * worldView * vec4(position, 1.0);",
  108198. "}"
  108199. ].join("\n");
  108200. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  108201. "precision highp float;",
  108202. "",
  108203. "uniform vec4 u_emission;",
  108204. "",
  108205. "void main(void)",
  108206. "{",
  108207. " gl_FragColor = u_emission;",
  108208. "}"
  108209. ].join("\n");
  108210. var shaderPath = {
  108211. vertex: "GLTFDefaultMaterial",
  108212. fragment: "GLTFDefaultMaterial"
  108213. };
  108214. var options = {
  108215. attributes: ["position"],
  108216. uniforms: ["worldView", "projection", "u_emission"],
  108217. samplers: new Array(),
  108218. needAlphaBlending: false
  108219. };
  108220. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  108221. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  108222. }
  108223. return GLTFUtils._DefaultMaterial;
  108224. };
  108225. // The GLTF default material
  108226. GLTFUtils._DefaultMaterial = null;
  108227. return GLTFUtils;
  108228. }());
  108229. GLTF1.GLTFUtils = GLTFUtils;
  108230. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108231. })(BABYLON || (BABYLON = {}));
  108232. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  108233. var BABYLON;
  108234. (function (BABYLON) {
  108235. var GLTF1;
  108236. (function (GLTF1) {
  108237. var GLTFLoaderExtension = /** @class */ (function () {
  108238. function GLTFLoaderExtension(name) {
  108239. this._name = name;
  108240. }
  108241. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  108242. get: function () {
  108243. return this._name;
  108244. },
  108245. enumerable: true,
  108246. configurable: true
  108247. });
  108248. /**
  108249. * Defines an override for loading the runtime
  108250. * Return true to stop further extensions from loading the runtime
  108251. */
  108252. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108253. return false;
  108254. };
  108255. /**
  108256. * Defines an onverride for creating gltf runtime
  108257. * Return true to stop further extensions from creating the runtime
  108258. */
  108259. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108260. return false;
  108261. };
  108262. /**
  108263. * Defines an override for loading buffers
  108264. * Return true to stop further extensions from loading this buffer
  108265. */
  108266. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108267. return false;
  108268. };
  108269. /**
  108270. * Defines an override for loading texture buffers
  108271. * Return true to stop further extensions from loading this texture data
  108272. */
  108273. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108274. return false;
  108275. };
  108276. /**
  108277. * Defines an override for creating textures
  108278. * Return true to stop further extensions from loading this texture
  108279. */
  108280. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108281. return false;
  108282. };
  108283. /**
  108284. * Defines an override for loading shader strings
  108285. * Return true to stop further extensions from loading this shader data
  108286. */
  108287. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108288. return false;
  108289. };
  108290. /**
  108291. * Defines an override for loading materials
  108292. * Return true to stop further extensions from loading this material
  108293. */
  108294. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108295. return false;
  108296. };
  108297. // ---------
  108298. // Utilities
  108299. // ---------
  108300. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108301. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108302. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  108303. }, function () {
  108304. setTimeout(function () {
  108305. if (!onSuccess) {
  108306. return;
  108307. }
  108308. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108309. });
  108310. });
  108311. };
  108312. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108313. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108314. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  108315. }, function () {
  108316. setTimeout(function () {
  108317. onSuccess();
  108318. });
  108319. });
  108320. };
  108321. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108322. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108323. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108324. }, function () {
  108325. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108326. });
  108327. };
  108328. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  108329. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108330. if (buffer) {
  108331. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108332. }
  108333. }, onError);
  108334. };
  108335. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108336. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108337. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108338. }, function () {
  108339. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108340. });
  108341. };
  108342. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108343. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108344. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108345. }, function () {
  108346. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108347. });
  108348. };
  108349. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108350. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108351. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108352. }, function () {
  108353. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108354. });
  108355. };
  108356. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108357. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108358. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108359. }, function () {
  108360. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108361. });
  108362. };
  108363. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  108364. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  108365. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  108366. if (func(loaderExtension)) {
  108367. return;
  108368. }
  108369. }
  108370. defaultFunc();
  108371. };
  108372. return GLTFLoaderExtension;
  108373. }());
  108374. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  108375. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108376. })(BABYLON || (BABYLON = {}));
  108377. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108378. var BABYLON;
  108379. (function (BABYLON) {
  108380. var GLTF1;
  108381. (function (GLTF1) {
  108382. var BinaryExtensionBufferName = "binary_glTF";
  108383. ;
  108384. ;
  108385. var GLTFBinaryExtension = /** @class */ (function (_super) {
  108386. __extends(GLTFBinaryExtension, _super);
  108387. function GLTFBinaryExtension() {
  108388. return _super.call(this, "KHR_binary_glTF") || this;
  108389. }
  108390. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108391. var extensionsUsed = data.json.extensionsUsed;
  108392. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  108393. return false;
  108394. }
  108395. this._bin = data.bin;
  108396. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108397. return true;
  108398. };
  108399. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108400. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108401. return false;
  108402. }
  108403. if (id !== BinaryExtensionBufferName) {
  108404. return false;
  108405. }
  108406. onSuccess(this._bin);
  108407. return true;
  108408. };
  108409. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108410. var texture = gltfRuntime.textures[id];
  108411. var source = gltfRuntime.images[texture.source];
  108412. if (!source.extensions || !(this.name in source.extensions)) {
  108413. return false;
  108414. }
  108415. var sourceExt = source.extensions[this.name];
  108416. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108417. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108418. onSuccess(buffer);
  108419. return true;
  108420. };
  108421. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108422. var shader = gltfRuntime.shaders[id];
  108423. if (!shader.extensions || !(this.name in shader.extensions)) {
  108424. return false;
  108425. }
  108426. var binaryExtensionShader = shader.extensions[this.name];
  108427. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108428. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108429. setTimeout(function () {
  108430. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108431. onSuccess(shaderString);
  108432. });
  108433. return true;
  108434. };
  108435. return GLTFBinaryExtension;
  108436. }(GLTF1.GLTFLoaderExtension));
  108437. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108438. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108439. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108440. })(BABYLON || (BABYLON = {}));
  108441. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108442. var BABYLON;
  108443. (function (BABYLON) {
  108444. var GLTF1;
  108445. (function (GLTF1) {
  108446. ;
  108447. ;
  108448. ;
  108449. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108450. __extends(GLTFMaterialsCommonExtension, _super);
  108451. function GLTFMaterialsCommonExtension() {
  108452. return _super.call(this, "KHR_materials_common") || this;
  108453. }
  108454. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108455. if (!gltfRuntime.extensions)
  108456. return false;
  108457. var extension = gltfRuntime.extensions[this.name];
  108458. if (!extension)
  108459. return false;
  108460. // Create lights
  108461. var lights = extension.lights;
  108462. if (lights) {
  108463. for (var thing in lights) {
  108464. var light = lights[thing];
  108465. switch (light.type) {
  108466. case "ambient":
  108467. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108468. var ambient = light.ambient;
  108469. if (ambient) {
  108470. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108471. }
  108472. break;
  108473. case "point":
  108474. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108475. var point = light.point;
  108476. if (point) {
  108477. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108478. }
  108479. break;
  108480. case "directional":
  108481. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108482. var directional = light.directional;
  108483. if (directional) {
  108484. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108485. }
  108486. break;
  108487. case "spot":
  108488. var spot = light.spot;
  108489. if (spot) {
  108490. 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);
  108491. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108492. }
  108493. break;
  108494. default:
  108495. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108496. break;
  108497. }
  108498. }
  108499. }
  108500. return false;
  108501. };
  108502. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108503. var material = gltfRuntime.materials[id];
  108504. if (!material || !material.extensions)
  108505. return false;
  108506. var extension = material.extensions[this.name];
  108507. if (!extension)
  108508. return false;
  108509. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108510. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108511. if (extension.technique === "CONSTANT") {
  108512. standardMaterial.disableLighting = true;
  108513. }
  108514. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108515. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108516. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108517. // Ambient
  108518. if (typeof extension.values.ambient === "string") {
  108519. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108520. }
  108521. else {
  108522. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108523. }
  108524. // Diffuse
  108525. if (typeof extension.values.diffuse === "string") {
  108526. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108527. }
  108528. else {
  108529. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108530. }
  108531. // Emission
  108532. if (typeof extension.values.emission === "string") {
  108533. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108534. }
  108535. else {
  108536. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108537. }
  108538. // Specular
  108539. if (typeof extension.values.specular === "string") {
  108540. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108541. }
  108542. else {
  108543. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108544. }
  108545. return true;
  108546. };
  108547. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108548. // Create buffer from texture url
  108549. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108550. // Create texture from buffer
  108551. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108552. }, onError);
  108553. };
  108554. return GLTFMaterialsCommonExtension;
  108555. }(GLTF1.GLTFLoaderExtension));
  108556. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108557. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108558. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108559. })(BABYLON || (BABYLON = {}));
  108560. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108561. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108562. /**
  108563. * Defines the module used to import/export glTF 2.0 assets
  108564. */
  108565. var BABYLON;
  108566. (function (BABYLON) {
  108567. var GLTF2;
  108568. (function (GLTF2) {
  108569. var _ArrayItem = /** @class */ (function () {
  108570. function _ArrayItem() {
  108571. }
  108572. _ArrayItem.Assign = function (values) {
  108573. if (values) {
  108574. for (var index = 0; index < values.length; index++) {
  108575. values[index]._index = index;
  108576. }
  108577. }
  108578. };
  108579. return _ArrayItem;
  108580. }());
  108581. /** @hidden */
  108582. var GLTFLoader = /** @class */ (function () {
  108583. function GLTFLoader(parent) {
  108584. this._completePromises = new Array();
  108585. this._disposed = false;
  108586. this._state = null;
  108587. this._extensions = {};
  108588. this._defaultSampler = {};
  108589. this._defaultBabylonMaterials = {};
  108590. this._requests = new Array();
  108591. this._parent = parent;
  108592. }
  108593. GLTFLoader._Register = function (name, factory) {
  108594. if (GLTFLoader._ExtensionFactories[name]) {
  108595. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108596. return;
  108597. }
  108598. GLTFLoader._ExtensionFactories[name] = factory;
  108599. // Keep the order of registration so that extensions registered first are called first.
  108600. GLTFLoader._ExtensionNames.push(name);
  108601. };
  108602. Object.defineProperty(GLTFLoader.prototype, "state", {
  108603. /**
  108604. * Loader state or null if the loader is not active.
  108605. */
  108606. get: function () {
  108607. return this._state;
  108608. },
  108609. enumerable: true,
  108610. configurable: true
  108611. });
  108612. GLTFLoader.prototype.dispose = function () {
  108613. if (this._disposed) {
  108614. return;
  108615. }
  108616. this._disposed = true;
  108617. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108618. var request = _a[_i];
  108619. request.abort();
  108620. }
  108621. this._requests.length = 0;
  108622. delete this._gltf;
  108623. delete this._babylonScene;
  108624. delete this._readyPromise;
  108625. this._completePromises.length = 0;
  108626. for (var name_1 in this._extensions) {
  108627. this._extensions[name_1].dispose();
  108628. }
  108629. this._extensions = {};
  108630. delete this._rootBabylonMesh;
  108631. delete this._progressCallback;
  108632. this._parent._clear();
  108633. };
  108634. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108635. var _this = this;
  108636. return Promise.resolve().then(function () {
  108637. _this._babylonScene = scene;
  108638. _this._rootUrl = rootUrl;
  108639. _this._progressCallback = onProgress;
  108640. _this._loadData(data);
  108641. var nodes = null;
  108642. if (meshesNames) {
  108643. var nodeMap_1 = {};
  108644. if (_this._gltf.nodes) {
  108645. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108646. var node = _a[_i];
  108647. if (node.name) {
  108648. nodeMap_1[node.name] = node._index;
  108649. }
  108650. }
  108651. }
  108652. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  108653. nodes = names.map(function (name) {
  108654. var node = nodeMap_1[name];
  108655. if (node === undefined) {
  108656. throw new Error("Failed to find node '" + name + "'");
  108657. }
  108658. return node;
  108659. });
  108660. }
  108661. return _this._loadAsync(nodes).then(function () {
  108662. return {
  108663. meshes: _this._getMeshes(),
  108664. particleSystems: [],
  108665. skeletons: _this._getSkeletons(),
  108666. animationGroups: _this._getAnimationGroups()
  108667. };
  108668. });
  108669. });
  108670. };
  108671. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108672. var _this = this;
  108673. return Promise.resolve().then(function () {
  108674. _this._babylonScene = scene;
  108675. _this._rootUrl = rootUrl;
  108676. _this._progressCallback = onProgress;
  108677. _this._loadData(data);
  108678. return _this._loadAsync(null);
  108679. });
  108680. };
  108681. GLTFLoader.prototype._loadAsync = function (nodes) {
  108682. var _this = this;
  108683. return Promise.resolve().then(function () {
  108684. _this._parent._startPerformanceCounter("Loading => Ready");
  108685. _this._parent._startPerformanceCounter("Loading => Complete");
  108686. _this._state = BABYLON.GLTFLoaderState.LOADING;
  108687. _this._parent._log("Loading");
  108688. var readyDeferred = new BABYLON.Deferred();
  108689. _this._readyPromise = readyDeferred.promise;
  108690. _this._loadExtensions();
  108691. _this._checkExtensions();
  108692. var promises = new Array();
  108693. if (nodes) {
  108694. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  108695. }
  108696. else {
  108697. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  108698. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  108699. }
  108700. if (_this._parent.compileMaterials) {
  108701. promises.push(_this._compileMaterialsAsync());
  108702. }
  108703. if (_this._parent.compileShadowGenerators) {
  108704. promises.push(_this._compileShadowGeneratorsAsync());
  108705. }
  108706. var resultPromise = Promise.all(promises).then(function () {
  108707. _this._state = BABYLON.GLTFLoaderState.READY;
  108708. _this._parent._log("Ready");
  108709. readyDeferred.resolve();
  108710. _this._startAnimations();
  108711. });
  108712. resultPromise.then(function () {
  108713. _this._parent._endPerformanceCounter("Loading => Ready");
  108714. BABYLON.Tools.SetImmediate(function () {
  108715. if (!_this._disposed) {
  108716. Promise.all(_this._completePromises).then(function () {
  108717. _this._parent._endPerformanceCounter("Loading => Complete");
  108718. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  108719. _this._parent._log("Complete");
  108720. _this._parent.onCompleteObservable.notifyObservers(undefined);
  108721. _this._parent.onCompleteObservable.clear();
  108722. _this.dispose();
  108723. }).catch(function (error) {
  108724. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108725. _this.dispose();
  108726. });
  108727. }
  108728. });
  108729. });
  108730. return resultPromise;
  108731. }).catch(function (error) {
  108732. if (!_this._disposed) {
  108733. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108734. _this.dispose();
  108735. throw error;
  108736. }
  108737. });
  108738. };
  108739. GLTFLoader.prototype._loadData = function (data) {
  108740. this._gltf = data.json;
  108741. this._setupData();
  108742. if (data.bin) {
  108743. var buffers = this._gltf.buffers;
  108744. if (buffers && buffers[0] && !buffers[0].uri) {
  108745. var binaryBuffer = buffers[0];
  108746. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  108747. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  108748. }
  108749. binaryBuffer._data = Promise.resolve(data.bin);
  108750. }
  108751. else {
  108752. BABYLON.Tools.Warn("Unexpected BIN chunk");
  108753. }
  108754. }
  108755. };
  108756. GLTFLoader.prototype._setupData = function () {
  108757. _ArrayItem.Assign(this._gltf.accessors);
  108758. _ArrayItem.Assign(this._gltf.animations);
  108759. _ArrayItem.Assign(this._gltf.buffers);
  108760. _ArrayItem.Assign(this._gltf.bufferViews);
  108761. _ArrayItem.Assign(this._gltf.cameras);
  108762. _ArrayItem.Assign(this._gltf.images);
  108763. _ArrayItem.Assign(this._gltf.materials);
  108764. _ArrayItem.Assign(this._gltf.meshes);
  108765. _ArrayItem.Assign(this._gltf.nodes);
  108766. _ArrayItem.Assign(this._gltf.samplers);
  108767. _ArrayItem.Assign(this._gltf.scenes);
  108768. _ArrayItem.Assign(this._gltf.skins);
  108769. _ArrayItem.Assign(this._gltf.textures);
  108770. if (this._gltf.nodes) {
  108771. var nodeParents = {};
  108772. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  108773. var node = _a[_i];
  108774. if (node.children) {
  108775. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  108776. var index = _c[_b];
  108777. nodeParents[index] = node._index;
  108778. }
  108779. }
  108780. }
  108781. var rootNode = this._createRootNode();
  108782. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  108783. var node = _e[_d];
  108784. var parentIndex = nodeParents[node._index];
  108785. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  108786. }
  108787. }
  108788. };
  108789. GLTFLoader.prototype._loadExtensions = function () {
  108790. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  108791. var name_2 = _a[_i];
  108792. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  108793. this._extensions[name_2] = extension;
  108794. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  108795. }
  108796. this._parent.onExtensionLoadedObservable.clear();
  108797. };
  108798. GLTFLoader.prototype._checkExtensions = function () {
  108799. if (this._gltf.extensionsRequired) {
  108800. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  108801. var name_3 = _a[_i];
  108802. var extension = this._extensions[name_3];
  108803. if (!extension || !extension.enabled) {
  108804. throw new Error("Require extension " + name_3 + " is not available");
  108805. }
  108806. }
  108807. }
  108808. };
  108809. GLTFLoader.prototype._createRootNode = function () {
  108810. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  108811. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  108812. switch (this._parent.coordinateSystemMode) {
  108813. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  108814. if (!this._babylonScene.useRightHandedSystem) {
  108815. rootNode.rotation = [0, 1, 0, 0];
  108816. rootNode.scale = [1, 1, -1];
  108817. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  108818. }
  108819. break;
  108820. }
  108821. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  108822. this._babylonScene.useRightHandedSystem = true;
  108823. break;
  108824. }
  108825. default: {
  108826. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  108827. }
  108828. }
  108829. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  108830. return rootNode;
  108831. };
  108832. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  108833. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  108834. if (promise) {
  108835. return promise;
  108836. }
  108837. var promises = new Array();
  108838. this._parent._logOpen(context + " " + (scene.name || ""));
  108839. if (scene.nodes) {
  108840. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  108841. var index = _a[_i];
  108842. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  108843. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108844. }
  108845. }
  108846. promises.push(this._loadAnimationsAsync());
  108847. this._parent._logClose();
  108848. return Promise.all(promises).then(function () { });
  108849. };
  108850. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  108851. if (node._primitiveBabylonMeshes) {
  108852. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108853. var babylonMesh = _a[_i];
  108854. callback(babylonMesh);
  108855. }
  108856. }
  108857. else {
  108858. callback(node._babylonMesh);
  108859. }
  108860. };
  108861. GLTFLoader.prototype._getMeshes = function () {
  108862. var meshes = new Array();
  108863. // Root mesh is always first.
  108864. meshes.push(this._rootBabylonMesh);
  108865. var nodes = this._gltf.nodes;
  108866. if (nodes) {
  108867. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  108868. var node = nodes_1[_i];
  108869. if (node._babylonMesh) {
  108870. meshes.push(node._babylonMesh);
  108871. }
  108872. if (node._primitiveBabylonMeshes) {
  108873. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  108874. var babylonMesh = _b[_a];
  108875. meshes.push(babylonMesh);
  108876. }
  108877. }
  108878. }
  108879. }
  108880. return meshes;
  108881. };
  108882. GLTFLoader.prototype._getSkeletons = function () {
  108883. var skeletons = new Array();
  108884. var skins = this._gltf.skins;
  108885. if (skins) {
  108886. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  108887. var skin = skins_1[_i];
  108888. if (skin._babylonSkeleton) {
  108889. skeletons.push(skin._babylonSkeleton);
  108890. }
  108891. }
  108892. }
  108893. return skeletons;
  108894. };
  108895. GLTFLoader.prototype._getAnimationGroups = function () {
  108896. var animationGroups = new Array();
  108897. var animations = this._gltf.animations;
  108898. if (animations) {
  108899. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  108900. var animation = animations_1[_i];
  108901. if (animation._babylonAnimationGroup) {
  108902. animationGroups.push(animation._babylonAnimationGroup);
  108903. }
  108904. }
  108905. }
  108906. return animationGroups;
  108907. };
  108908. GLTFLoader.prototype._startAnimations = function () {
  108909. switch (this._parent.animationStartMode) {
  108910. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  108911. // do nothing
  108912. break;
  108913. }
  108914. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  108915. var babylonAnimationGroups = this._getAnimationGroups();
  108916. if (babylonAnimationGroups.length !== 0) {
  108917. babylonAnimationGroups[0].start(true);
  108918. }
  108919. break;
  108920. }
  108921. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  108922. var babylonAnimationGroups = this._getAnimationGroups();
  108923. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  108924. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  108925. babylonAnimationGroup.start(true);
  108926. }
  108927. break;
  108928. }
  108929. default: {
  108930. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  108931. return;
  108932. }
  108933. }
  108934. };
  108935. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  108936. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  108937. if (promise) {
  108938. return promise;
  108939. }
  108940. if (node._babylonMesh) {
  108941. throw new Error(context + ": Invalid recursive node hierarchy");
  108942. }
  108943. var promises = new Array();
  108944. this._parent._logOpen(context + " " + (node.name || ""));
  108945. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  108946. node._babylonMesh = babylonMesh;
  108947. babylonMesh.setEnabled(false);
  108948. GLTFLoader._LoadTransform(node, babylonMesh);
  108949. if (node.mesh != undefined) {
  108950. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  108951. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  108952. }
  108953. if (node.camera != undefined) {
  108954. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  108955. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  108956. }
  108957. if (node.children) {
  108958. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  108959. var index = _a[_i];
  108960. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  108961. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  108962. }
  108963. }
  108964. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108965. this._parent._logClose();
  108966. return Promise.all(promises).then(function () {
  108967. babylonMesh.setEnabled(true);
  108968. });
  108969. };
  108970. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  108971. var _this = this;
  108972. var promises = new Array();
  108973. this._parent._logOpen(context + " " + (mesh.name || ""));
  108974. var primitives = mesh.primitives;
  108975. if (!primitives || primitives.length === 0) {
  108976. throw new Error(context + ": Primitives are missing");
  108977. }
  108978. _ArrayItem.Assign(primitives);
  108979. if (primitives.length === 1) {
  108980. var primitive = primitives[0];
  108981. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  108982. }
  108983. else {
  108984. node._primitiveBabylonMeshes = [];
  108985. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  108986. var primitive = primitives_1[_i];
  108987. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  108988. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  108989. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  108990. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108991. }
  108992. }
  108993. if (node.skin != undefined) {
  108994. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  108995. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  108996. }
  108997. this._parent._logClose();
  108998. return Promise.all(promises).then(function () {
  108999. _this._forEachPrimitive(node, function (babylonMesh) {
  109000. babylonMesh._refreshBoundingInfo(true);
  109001. });
  109002. });
  109003. };
  109004. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  109005. var _this = this;
  109006. var promises = new Array();
  109007. this._parent._logOpen("" + context);
  109008. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  109009. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  109010. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  109011. babylonGeometry.applyToMesh(babylonMesh);
  109012. });
  109013. }));
  109014. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  109015. if (primitive.material == undefined) {
  109016. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  109017. }
  109018. else {
  109019. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  109020. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109021. babylonMesh.material = babylonMaterial;
  109022. }));
  109023. }
  109024. this._parent._logClose();
  109025. return Promise.all(promises).then(function () { });
  109026. };
  109027. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109028. var _this = this;
  109029. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  109030. if (promise) {
  109031. return promise;
  109032. }
  109033. var attributes = primitive.attributes;
  109034. if (!attributes) {
  109035. throw new Error(context + ": Attributes are missing");
  109036. }
  109037. var promises = new Array();
  109038. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  109039. if (primitive.indices == undefined) {
  109040. babylonMesh.isUnIndexed = true;
  109041. }
  109042. else {
  109043. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  109044. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109045. babylonGeometry.setIndices(data);
  109046. }));
  109047. }
  109048. var loadAttribute = function (attribute, kind, callback) {
  109049. if (attributes[attribute] == undefined) {
  109050. return;
  109051. }
  109052. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109053. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109054. babylonMesh._delayInfo.push(kind);
  109055. }
  109056. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109057. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  109058. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  109059. }));
  109060. if (callback) {
  109061. callback(accessor);
  109062. }
  109063. };
  109064. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109065. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109066. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109067. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109068. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109069. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109070. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109071. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  109072. if (accessor.type === "VEC4" /* VEC4 */) {
  109073. babylonMesh.hasVertexAlpha = true;
  109074. }
  109075. });
  109076. return Promise.all(promises).then(function () {
  109077. return babylonGeometry;
  109078. });
  109079. };
  109080. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  109081. if (!primitive.targets) {
  109082. return;
  109083. }
  109084. if (node._numMorphTargets == undefined) {
  109085. node._numMorphTargets = primitive.targets.length;
  109086. }
  109087. else if (primitive.targets.length !== node._numMorphTargets) {
  109088. throw new Error(context + ": Primitives do not have the same number of targets");
  109089. }
  109090. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  109091. for (var index = 0; index < primitive.targets.length; index++) {
  109092. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  109093. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  109094. // TODO: tell the target whether it has positions, normals, tangents
  109095. }
  109096. };
  109097. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  109098. if (!primitive.targets) {
  109099. return Promise.resolve();
  109100. }
  109101. var promises = new Array();
  109102. var morphTargetManager = babylonMesh.morphTargetManager;
  109103. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  109104. var babylonMorphTarget = morphTargetManager.getTarget(index);
  109105. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  109106. }
  109107. return Promise.all(promises).then(function () { });
  109108. };
  109109. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  109110. var _this = this;
  109111. var promises = new Array();
  109112. var loadAttribute = function (attribute, kind, setData) {
  109113. if (attributes[attribute] == undefined) {
  109114. return;
  109115. }
  109116. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  109117. if (!babylonVertexBuffer) {
  109118. return;
  109119. }
  109120. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109121. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109122. setData(babylonVertexBuffer, data);
  109123. }));
  109124. };
  109125. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  109126. babylonVertexBuffer.forEach(data.length, function (value, index) {
  109127. data[index] += value;
  109128. });
  109129. babylonMorphTarget.setPositions(data);
  109130. });
  109131. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  109132. babylonVertexBuffer.forEach(data.length, function (value, index) {
  109133. data[index] += value;
  109134. });
  109135. babylonMorphTarget.setNormals(data);
  109136. });
  109137. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  109138. var dataIndex = 0;
  109139. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  109140. // Tangent data for morph targets is stored as xyz delta.
  109141. // The vertexData.tangent is stored as xyzw.
  109142. // So we need to skip every fourth vertexData.tangent.
  109143. if (((index + 1) % 4) !== 0) {
  109144. data[dataIndex++] += value;
  109145. }
  109146. });
  109147. babylonMorphTarget.setTangents(data);
  109148. });
  109149. return Promise.all(promises).then(function () { });
  109150. };
  109151. GLTFLoader._LoadTransform = function (node, babylonNode) {
  109152. var position = BABYLON.Vector3.Zero();
  109153. var rotation = BABYLON.Quaternion.Identity();
  109154. var scaling = BABYLON.Vector3.One();
  109155. if (node.matrix) {
  109156. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  109157. matrix.decompose(scaling, rotation, position);
  109158. }
  109159. else {
  109160. if (node.translation)
  109161. position = BABYLON.Vector3.FromArray(node.translation);
  109162. if (node.rotation)
  109163. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  109164. if (node.scale)
  109165. scaling = BABYLON.Vector3.FromArray(node.scale);
  109166. }
  109167. babylonNode.position = position;
  109168. babylonNode.rotationQuaternion = rotation;
  109169. babylonNode.scaling = scaling;
  109170. };
  109171. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  109172. var _this = this;
  109173. var assignSkeleton = function (skeleton) {
  109174. _this._forEachPrimitive(node, function (babylonMesh) {
  109175. babylonMesh.skeleton = skeleton;
  109176. });
  109177. // Ignore the TRS of skinned nodes.
  109178. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  109179. node._babylonMesh.parent = _this._rootBabylonMesh;
  109180. node._babylonMesh.position = BABYLON.Vector3.Zero();
  109181. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  109182. node._babylonMesh.scaling = BABYLON.Vector3.One();
  109183. };
  109184. if (skin._loaded) {
  109185. return skin._loaded.then(function () {
  109186. assignSkeleton(skin._babylonSkeleton);
  109187. });
  109188. }
  109189. var skeletonId = "skeleton" + skin._index;
  109190. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  109191. skin._babylonSkeleton = babylonSkeleton;
  109192. this._loadBones(context, skin);
  109193. assignSkeleton(babylonSkeleton);
  109194. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  109195. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  109196. }));
  109197. };
  109198. GLTFLoader.prototype._loadBones = function (context, skin) {
  109199. var babylonBones = {};
  109200. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  109201. var index = _a[_i];
  109202. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  109203. this._loadBone(node, skin, babylonBones);
  109204. }
  109205. };
  109206. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  109207. var babylonBone = babylonBones[node._index];
  109208. if (babylonBone) {
  109209. return babylonBone;
  109210. }
  109211. var babylonParentBone = null;
  109212. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  109213. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  109214. }
  109215. var boneIndex = skin.joints.indexOf(node._index);
  109216. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  109217. babylonBones[node._index] = babylonBone;
  109218. node._babylonBones = node._babylonBones || [];
  109219. node._babylonBones.push(babylonBone);
  109220. return babylonBone;
  109221. };
  109222. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  109223. if (skin.inverseBindMatrices == undefined) {
  109224. return Promise.resolve(null);
  109225. }
  109226. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  109227. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  109228. };
  109229. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  109230. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  109231. var babylonBone = _a[_i];
  109232. var baseMatrix = BABYLON.Matrix.Identity();
  109233. var boneIndex = babylonBone._index;
  109234. if (inverseBindMatricesData && boneIndex !== -1) {
  109235. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  109236. baseMatrix.invertToRef(baseMatrix);
  109237. }
  109238. var babylonParentBone = babylonBone.getParent();
  109239. if (babylonParentBone) {
  109240. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  109241. }
  109242. babylonBone.updateMatrix(baseMatrix, false, false);
  109243. babylonBone._updateDifferenceMatrix(undefined, false);
  109244. }
  109245. };
  109246. GLTFLoader.prototype._getNodeMatrix = function (node) {
  109247. return node.matrix ?
  109248. BABYLON.Matrix.FromArray(node.matrix) :
  109249. 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());
  109250. };
  109251. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  109252. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  109253. babylonCamera.parent = babylonMesh;
  109254. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  109255. switch (camera.type) {
  109256. case "perspective" /* PERSPECTIVE */: {
  109257. var perspective = camera.perspective;
  109258. if (!perspective) {
  109259. throw new Error(context + ": Camera perspective properties are missing");
  109260. }
  109261. babylonCamera.fov = perspective.yfov;
  109262. babylonCamera.minZ = perspective.znear;
  109263. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  109264. break;
  109265. }
  109266. case "orthographic" /* ORTHOGRAPHIC */: {
  109267. if (!camera.orthographic) {
  109268. throw new Error(context + ": Camera orthographic properties are missing");
  109269. }
  109270. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  109271. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  109272. babylonCamera.orthoRight = camera.orthographic.xmag;
  109273. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  109274. babylonCamera.orthoTop = camera.orthographic.ymag;
  109275. babylonCamera.minZ = camera.orthographic.znear;
  109276. babylonCamera.maxZ = camera.orthographic.zfar;
  109277. break;
  109278. }
  109279. default: {
  109280. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  109281. }
  109282. }
  109283. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  109284. };
  109285. GLTFLoader.prototype._loadAnimationsAsync = function () {
  109286. var animations = this._gltf.animations;
  109287. if (!animations) {
  109288. return Promise.resolve();
  109289. }
  109290. var promises = new Array();
  109291. for (var index = 0; index < animations.length; index++) {
  109292. var animation = animations[index];
  109293. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  109294. }
  109295. return Promise.all(promises).then(function () { });
  109296. };
  109297. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  109298. var _this = this;
  109299. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  109300. animation._babylonAnimationGroup = babylonAnimationGroup;
  109301. var promises = new Array();
  109302. _ArrayItem.Assign(animation.channels);
  109303. _ArrayItem.Assign(animation.samplers);
  109304. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  109305. var channel = _a[_i];
  109306. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  109307. }
  109308. return Promise.all(promises).then(function () {
  109309. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  109310. });
  109311. };
  109312. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  109313. var _this = this;
  109314. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  109315. // Ignore animations that have no animation targets.
  109316. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  109317. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  109318. return Promise.resolve();
  109319. }
  109320. // Ignore animations targeting TRS of skinned nodes.
  109321. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  109322. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  109323. return Promise.resolve();
  109324. }
  109325. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  109326. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  109327. var targetPath;
  109328. var animationType;
  109329. switch (channel.target.path) {
  109330. case "translation" /* TRANSLATION */: {
  109331. targetPath = "position";
  109332. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109333. break;
  109334. }
  109335. case "rotation" /* ROTATION */: {
  109336. targetPath = "rotationQuaternion";
  109337. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  109338. break;
  109339. }
  109340. case "scale" /* SCALE */: {
  109341. targetPath = "scaling";
  109342. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109343. break;
  109344. }
  109345. case "weights" /* WEIGHTS */: {
  109346. targetPath = "influence";
  109347. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  109348. break;
  109349. }
  109350. default: {
  109351. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  109352. }
  109353. }
  109354. var outputBufferOffset = 0;
  109355. var getNextOutputValue;
  109356. switch (targetPath) {
  109357. case "position": {
  109358. getNextOutputValue = function () {
  109359. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109360. outputBufferOffset += 3;
  109361. return value;
  109362. };
  109363. break;
  109364. }
  109365. case "rotationQuaternion": {
  109366. getNextOutputValue = function () {
  109367. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  109368. outputBufferOffset += 4;
  109369. return value;
  109370. };
  109371. break;
  109372. }
  109373. case "scaling": {
  109374. getNextOutputValue = function () {
  109375. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109376. outputBufferOffset += 3;
  109377. return value;
  109378. };
  109379. break;
  109380. }
  109381. case "influence": {
  109382. getNextOutputValue = function () {
  109383. var value = new Array(targetNode._numMorphTargets);
  109384. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  109385. value[i] = data.output[outputBufferOffset++];
  109386. }
  109387. return value;
  109388. };
  109389. break;
  109390. }
  109391. }
  109392. var getNextKey;
  109393. switch (data.interpolation) {
  109394. case "STEP" /* STEP */: {
  109395. getNextKey = function (frameIndex) { return ({
  109396. frame: data.input[frameIndex],
  109397. value: getNextOutputValue(),
  109398. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  109399. }); };
  109400. break;
  109401. }
  109402. case "LINEAR" /* LINEAR */: {
  109403. getNextKey = function (frameIndex) { return ({
  109404. frame: data.input[frameIndex],
  109405. value: getNextOutputValue()
  109406. }); };
  109407. break;
  109408. }
  109409. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109410. getNextKey = function (frameIndex) { return ({
  109411. frame: data.input[frameIndex],
  109412. inTangent: getNextOutputValue(),
  109413. value: getNextOutputValue(),
  109414. outTangent: getNextOutputValue()
  109415. }); };
  109416. break;
  109417. }
  109418. }
  109419. var keys = new Array(data.input.length);
  109420. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109421. keys[frameIndex] = getNextKey(frameIndex);
  109422. }
  109423. if (targetPath === "influence") {
  109424. var _loop_1 = function (targetIndex) {
  109425. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109426. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109427. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109428. frame: key.frame,
  109429. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109430. value: key.value[targetIndex],
  109431. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109432. }); }));
  109433. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  109434. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109435. var babylonAnimationClone = babylonAnimation.clone();
  109436. morphTarget.animations.push(babylonAnimationClone);
  109437. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  109438. });
  109439. };
  109440. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109441. _loop_1(targetIndex);
  109442. }
  109443. }
  109444. else {
  109445. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109446. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109447. babylonAnimation.setKeys(keys);
  109448. if (targetNode._babylonBones) {
  109449. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  109450. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  109451. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  109452. babylonAnimationTarget.animations.push(babylonAnimation);
  109453. }
  109454. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  109455. }
  109456. else {
  109457. targetNode._babylonMesh.animations.push(babylonAnimation);
  109458. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  109459. }
  109460. }
  109461. });
  109462. };
  109463. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109464. if (sampler._data) {
  109465. return sampler._data;
  109466. }
  109467. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109468. switch (interpolation) {
  109469. case "STEP" /* STEP */:
  109470. case "LINEAR" /* LINEAR */:
  109471. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109472. break;
  109473. }
  109474. default: {
  109475. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109476. }
  109477. }
  109478. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109479. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109480. sampler._data = Promise.all([
  109481. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  109482. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  109483. ]).then(function (_a) {
  109484. var inputData = _a[0], outputData = _a[1];
  109485. return {
  109486. input: inputData,
  109487. interpolation: interpolation,
  109488. output: outputData,
  109489. };
  109490. });
  109491. return sampler._data;
  109492. };
  109493. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109494. if (buffer._data) {
  109495. return buffer._data;
  109496. }
  109497. if (!buffer.uri) {
  109498. throw new Error(context + ": Uri is missing");
  109499. }
  109500. buffer._data = this._loadUriAsync(context, buffer.uri);
  109501. return buffer._data;
  109502. };
  109503. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109504. if (bufferView._data) {
  109505. return bufferView._data;
  109506. }
  109507. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109508. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  109509. try {
  109510. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109511. }
  109512. catch (e) {
  109513. throw new Error(context + ": " + e.message);
  109514. }
  109515. });
  109516. return bufferView._data;
  109517. };
  109518. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  109519. if (accessor.type !== "SCALAR" /* SCALAR */) {
  109520. throw new Error(context + ": Invalid type " + accessor.type);
  109521. }
  109522. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  109523. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  109524. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  109525. throw new Error(context + ": Invalid component type " + accessor.componentType);
  109526. }
  109527. if (accessor._data) {
  109528. return accessor._data;
  109529. }
  109530. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109531. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109532. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  109533. });
  109534. return accessor._data;
  109535. };
  109536. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  109537. // TODO: support normalized and stride
  109538. var _this = this;
  109539. if (accessor.componentType !== 5126 /* FLOAT */) {
  109540. throw new Error("Invalid component type " + accessor.componentType);
  109541. }
  109542. if (accessor._data) {
  109543. return accessor._data;
  109544. }
  109545. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109546. var length = numComponents * accessor.count;
  109547. if (accessor.bufferView == undefined) {
  109548. accessor._data = Promise.resolve(new Float32Array(length));
  109549. }
  109550. else {
  109551. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109552. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109553. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  109554. });
  109555. }
  109556. if (accessor.sparse) {
  109557. var sparse_1 = accessor.sparse;
  109558. accessor._data = accessor._data.then(function (data) {
  109559. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  109560. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  109561. return Promise.all([
  109562. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  109563. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  109564. ]).then(function (_a) {
  109565. var indicesData = _a[0], valuesData = _a[1];
  109566. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  109567. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  109568. var valuesIndex = 0;
  109569. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  109570. var dataIndex = indices[indicesIndex] * numComponents;
  109571. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109572. data[dataIndex++] = values[valuesIndex++];
  109573. }
  109574. }
  109575. return data;
  109576. });
  109577. });
  109578. }
  109579. return accessor._data;
  109580. };
  109581. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  109582. var _this = this;
  109583. if (bufferView._babylonBuffer) {
  109584. return bufferView._babylonBuffer;
  109585. }
  109586. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  109587. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  109588. });
  109589. return bufferView._babylonBuffer;
  109590. };
  109591. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  109592. var _this = this;
  109593. if (accessor._babylonVertexBuffer) {
  109594. return accessor._babylonVertexBuffer;
  109595. }
  109596. if (accessor.sparse) {
  109597. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  109598. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  109599. });
  109600. }
  109601. else {
  109602. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109603. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  109604. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  109605. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  109606. });
  109607. }
  109608. return accessor._babylonVertexBuffer;
  109609. };
  109610. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  109611. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  109612. if (!babylonMaterial) {
  109613. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  109614. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109615. babylonMaterial.metallic = 1;
  109616. babylonMaterial.roughness = 1;
  109617. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109618. }
  109619. return babylonMaterial;
  109620. };
  109621. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  109622. var promises = new Array();
  109623. // Ensure metallic workflow
  109624. babylonMaterial.metallic = 1;
  109625. babylonMaterial.roughness = 1;
  109626. var properties = material.pbrMetallicRoughness;
  109627. if (properties) {
  109628. if (properties.baseColorFactor) {
  109629. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109630. babylonMaterial.alpha = properties.baseColorFactor[3];
  109631. }
  109632. else {
  109633. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109634. }
  109635. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109636. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109637. if (properties.baseColorTexture) {
  109638. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109639. babylonMaterial.albedoTexture = texture;
  109640. }));
  109641. }
  109642. if (properties.metallicRoughnessTexture) {
  109643. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109644. babylonMaterial.metallicTexture = texture;
  109645. }));
  109646. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109647. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109648. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109649. }
  109650. }
  109651. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  109652. return Promise.all(promises).then(function () { });
  109653. };
  109654. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109655. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  109656. if (promise) {
  109657. return promise;
  109658. }
  109659. material._babylonData = material._babylonData || {};
  109660. var babylonData = material._babylonData[babylonDrawMode];
  109661. if (!babylonData) {
  109662. this._parent._logOpen(context + " " + (material.name || ""));
  109663. var name_4 = material.name || "material" + material._index;
  109664. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  109665. babylonData = {
  109666. material: babylonMaterial,
  109667. meshes: [],
  109668. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  109669. };
  109670. material._babylonData[babylonDrawMode] = babylonData;
  109671. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109672. this._parent._logClose();
  109673. }
  109674. babylonData.meshes.push(babylonMesh);
  109675. babylonMesh.onDisposeObservable.addOnce(function () {
  109676. var index = babylonData.meshes.indexOf(babylonMesh);
  109677. if (index !== -1) {
  109678. babylonData.meshes.splice(index, 1);
  109679. }
  109680. });
  109681. assign(babylonData.material);
  109682. return babylonData.loaded;
  109683. };
  109684. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  109685. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  109686. if (promise) {
  109687. return promise;
  109688. }
  109689. var promises = new Array();
  109690. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  109691. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  109692. return Promise.all(promises).then(function () { });
  109693. };
  109694. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  109695. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  109696. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109697. babylonMaterial.fillMode = drawMode;
  109698. babylonMaterial.enableSpecularAntiAliasing = true;
  109699. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  109700. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  109701. return babylonMaterial;
  109702. };
  109703. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  109704. var promises = new Array();
  109705. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  109706. if (material.doubleSided) {
  109707. babylonMaterial.backFaceCulling = false;
  109708. babylonMaterial.twoSidedLighting = true;
  109709. }
  109710. if (material.normalTexture) {
  109711. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  109712. babylonMaterial.bumpTexture = texture;
  109713. }));
  109714. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  109715. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  109716. if (material.normalTexture.scale != undefined) {
  109717. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  109718. }
  109719. }
  109720. if (material.occlusionTexture) {
  109721. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  109722. babylonMaterial.ambientTexture = texture;
  109723. }));
  109724. babylonMaterial.useAmbientInGrayScale = true;
  109725. if (material.occlusionTexture.strength != undefined) {
  109726. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  109727. }
  109728. }
  109729. if (material.emissiveTexture) {
  109730. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  109731. babylonMaterial.emissiveTexture = texture;
  109732. }));
  109733. }
  109734. return Promise.all(promises).then(function () { });
  109735. };
  109736. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  109737. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  109738. switch (alphaMode) {
  109739. case "OPAQUE" /* OPAQUE */: {
  109740. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109741. break;
  109742. }
  109743. case "MASK" /* MASK */: {
  109744. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  109745. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  109746. if (babylonMaterial.albedoTexture) {
  109747. babylonMaterial.albedoTexture.hasAlpha = true;
  109748. }
  109749. break;
  109750. }
  109751. case "BLEND" /* BLEND */: {
  109752. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  109753. if (babylonMaterial.albedoTexture) {
  109754. babylonMaterial.albedoTexture.hasAlpha = true;
  109755. babylonMaterial.useAlphaFromAlbedoTexture = true;
  109756. }
  109757. break;
  109758. }
  109759. default: {
  109760. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  109761. }
  109762. }
  109763. };
  109764. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109765. var _this = this;
  109766. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  109767. if (promise) {
  109768. return promise;
  109769. }
  109770. this._parent._logOpen("" + context);
  109771. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  109772. context = "#/textures/" + textureInfo.index;
  109773. var promises = new Array();
  109774. this._parent._logOpen(context + " " + (texture.name || ""));
  109775. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  109776. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  109777. var deferred = new BABYLON.Deferred();
  109778. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  109779. if (!_this._disposed) {
  109780. deferred.resolve();
  109781. }
  109782. }, function (message, exception) {
  109783. if (!_this._disposed) {
  109784. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  109785. }
  109786. });
  109787. promises.push(deferred.promise);
  109788. babylonTexture.name = texture.name || "texture" + texture._index;
  109789. babylonTexture.wrapU = samplerData.wrapU;
  109790. babylonTexture.wrapV = samplerData.wrapV;
  109791. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  109792. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  109793. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  109794. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  109795. babylonTexture.updateURL(dataUrl, blob);
  109796. }));
  109797. assign(babylonTexture);
  109798. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  109799. this._parent._logClose();
  109800. this._parent._logClose();
  109801. return Promise.all(promises).then(function () { });
  109802. };
  109803. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  109804. if (!sampler._data) {
  109805. sampler._data = {
  109806. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  109807. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  109808. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  109809. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  109810. };
  109811. }
  109812. ;
  109813. return sampler._data;
  109814. };
  109815. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  109816. if (!image._blob) {
  109817. this._parent._logOpen(context + " " + (image.name || ""));
  109818. var promise = void 0;
  109819. if (image.uri) {
  109820. promise = this._loadUriAsync(context, image.uri);
  109821. }
  109822. else {
  109823. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  109824. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  109825. }
  109826. image._blob = promise.then(function (data) {
  109827. return new Blob([data], { type: image.mimeType });
  109828. });
  109829. this._parent._logClose();
  109830. }
  109831. return image._blob;
  109832. };
  109833. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  109834. var _this = this;
  109835. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  109836. if (promise) {
  109837. return promise;
  109838. }
  109839. if (!GLTFLoader._ValidateUri(uri)) {
  109840. throw new Error(context + ": Uri '" + uri + "' is invalid");
  109841. }
  109842. if (BABYLON.Tools.IsBase64(uri)) {
  109843. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  109844. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  109845. return Promise.resolve(data);
  109846. }
  109847. this._parent._log("Loading " + uri);
  109848. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  109849. return new Promise(function (resolve, reject) {
  109850. if (!_this._disposed) {
  109851. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  109852. if (!_this._disposed) {
  109853. var data = new Uint8Array(fileData);
  109854. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  109855. resolve(data);
  109856. }
  109857. }, function (event) {
  109858. if (!_this._disposed) {
  109859. if (request_1) {
  109860. request_1._lengthComputable = event.lengthComputable;
  109861. request_1._loaded = event.loaded;
  109862. request_1._total = event.total;
  109863. }
  109864. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  109865. try {
  109866. _this._onProgress();
  109867. }
  109868. catch (e) {
  109869. reject(e);
  109870. }
  109871. }
  109872. }
  109873. }, _this._babylonScene.database, true, function (request, exception) {
  109874. if (!_this._disposed) {
  109875. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  109876. }
  109877. });
  109878. _this._requests.push(request_1);
  109879. }
  109880. });
  109881. });
  109882. };
  109883. GLTFLoader.prototype._onProgress = function () {
  109884. if (!this._progressCallback) {
  109885. return;
  109886. }
  109887. var lengthComputable = true;
  109888. var loaded = 0;
  109889. var total = 0;
  109890. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109891. var request = _a[_i];
  109892. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  109893. return;
  109894. }
  109895. lengthComputable = lengthComputable && request._lengthComputable;
  109896. loaded += request._loaded;
  109897. total += request._total;
  109898. }
  109899. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  109900. };
  109901. GLTFLoader._GetProperty = function (context, array, index) {
  109902. if (!array || index == undefined || !array[index]) {
  109903. throw new Error(context + ": Failed to find index (" + index + ")");
  109904. }
  109905. return array[index];
  109906. };
  109907. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  109908. // Set defaults if undefined
  109909. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  109910. switch (mode) {
  109911. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109912. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109913. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109914. default:
  109915. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  109916. return BABYLON.Texture.WRAP_ADDRESSMODE;
  109917. }
  109918. };
  109919. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  109920. // Set defaults if undefined
  109921. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  109922. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  109923. if (magFilter === 9729 /* LINEAR */) {
  109924. switch (minFilter) {
  109925. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  109926. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  109927. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  109928. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  109929. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  109930. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109931. default:
  109932. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109933. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109934. }
  109935. }
  109936. else {
  109937. if (magFilter !== 9728 /* NEAREST */) {
  109938. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  109939. }
  109940. switch (minFilter) {
  109941. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  109942. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  109943. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109944. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  109945. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  109946. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  109947. default:
  109948. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109949. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109950. }
  109951. }
  109952. };
  109953. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  109954. var buffer = bufferView.buffer;
  109955. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  109956. try {
  109957. switch (componentType) {
  109958. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  109959. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  109960. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  109961. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  109962. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  109963. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  109964. default: throw new Error("Invalid component type " + componentType);
  109965. }
  109966. }
  109967. catch (e) {
  109968. throw new Error(context + ": " + e);
  109969. }
  109970. };
  109971. GLTFLoader._GetNumComponents = function (context, type) {
  109972. switch (type) {
  109973. case "SCALAR": return 1;
  109974. case "VEC2": return 2;
  109975. case "VEC3": return 3;
  109976. case "VEC4": return 4;
  109977. case "MAT2": return 4;
  109978. case "MAT3": return 9;
  109979. case "MAT4": return 16;
  109980. }
  109981. throw new Error(context + ": Invalid type (" + type + ")");
  109982. };
  109983. GLTFLoader._ValidateUri = function (uri) {
  109984. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  109985. };
  109986. GLTFLoader._GetDrawMode = function (context, mode) {
  109987. if (mode == undefined) {
  109988. mode = 4 /* TRIANGLES */;
  109989. }
  109990. switch (mode) {
  109991. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  109992. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  109993. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  109994. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  109995. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  109996. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  109997. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  109998. }
  109999. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  110000. };
  110001. GLTFLoader.prototype._compileMaterialsAsync = function () {
  110002. var _this = this;
  110003. this._parent._startPerformanceCounter("Compile materials");
  110004. var promises = new Array();
  110005. if (this._gltf.materials) {
  110006. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  110007. var material = _a[_i];
  110008. if (material._babylonData) {
  110009. for (var babylonDrawMode in material._babylonData) {
  110010. var babylonData = material._babylonData[babylonDrawMode];
  110011. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  110012. var babylonMesh = _c[_b];
  110013. // Ensure nonUniformScaling is set if necessary.
  110014. babylonMesh.computeWorldMatrix(true);
  110015. var babylonMaterial = babylonData.material;
  110016. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  110017. if (this._parent.useClipPlane) {
  110018. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  110019. }
  110020. }
  110021. }
  110022. }
  110023. }
  110024. }
  110025. return Promise.all(promises).then(function () {
  110026. _this._parent._endPerformanceCounter("Compile materials");
  110027. });
  110028. };
  110029. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  110030. var _this = this;
  110031. this._parent._startPerformanceCounter("Compile shadow generators");
  110032. var promises = new Array();
  110033. var lights = this._babylonScene.lights;
  110034. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  110035. var light = lights_1[_i];
  110036. var generator = light.getShadowGenerator();
  110037. if (generator) {
  110038. promises.push(generator.forceCompilationAsync());
  110039. }
  110040. }
  110041. return Promise.all(promises).then(function () {
  110042. _this._parent._endPerformanceCounter("Compile shadow generators");
  110043. });
  110044. };
  110045. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  110046. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  110047. var name_5 = _a[_i];
  110048. var extension = this._extensions[name_5];
  110049. if (extension.enabled) {
  110050. var promise = actionAsync(extension);
  110051. if (promise) {
  110052. return promise;
  110053. }
  110054. }
  110055. }
  110056. return null;
  110057. };
  110058. GLTFLoader._ExtensionNames = new Array();
  110059. GLTFLoader._ExtensionFactories = {};
  110060. return GLTFLoader;
  110061. }());
  110062. GLTF2.GLTFLoader = GLTFLoader;
  110063. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  110064. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110065. })(BABYLON || (BABYLON = {}));
  110066. //# sourceMappingURL=babylon.glTFLoader.js.map
  110067. var BABYLON;
  110068. (function (BABYLON) {
  110069. var GLTF2;
  110070. (function (GLTF2) {
  110071. /**
  110072. * Abstract class that can be implemented to extend existing glTF loader behavior.
  110073. */
  110074. var GLTFLoaderExtension = /** @class */ (function () {
  110075. /**
  110076. * Creates new GLTFLoaderExtension
  110077. * @param loader defines the GLTFLoader to use
  110078. */
  110079. function GLTFLoaderExtension(loader) {
  110080. /**
  110081. * Gets or sets a boolean indicating if the extension is enabled
  110082. */
  110083. this.enabled = true;
  110084. this._loader = loader;
  110085. }
  110086. /**
  110087. * Release all resources
  110088. */
  110089. GLTFLoaderExtension.prototype.dispose = function () {
  110090. delete this._loader;
  110091. };
  110092. // #region Overridable Methods
  110093. /**
  110094. * Override this method to modify the default behavior for loading scenes.
  110095. * @hidden
  110096. */
  110097. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  110098. /**
  110099. * Override this method to modify the default behavior for loading nodes.
  110100. * @hidden
  110101. */
  110102. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  110103. /**
  110104. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  110105. * @hidden
  110106. */
  110107. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  110108. /**
  110109. * Override this method to modify the default behavior for loading materials.
  110110. * @hidden
  110111. */
  110112. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  110113. /**
  110114. * Override this method to modify the default behavior for loading material properties.
  110115. * @hidden
  110116. */
  110117. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  110118. /**
  110119. * Override this method to modify the default behavior for loading textures.
  110120. * @hidden
  110121. */
  110122. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  110123. /**
  110124. * Override this method to modify the default behavior for loading uris.
  110125. * @hidden
  110126. */
  110127. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  110128. // #endregion
  110129. /**
  110130. * Helper method called by a loader extension to load an glTF extension.
  110131. * @hidden
  110132. */
  110133. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  110134. if (!property.extensions) {
  110135. return null;
  110136. }
  110137. var extensions = property.extensions;
  110138. var extension = extensions[this.name];
  110139. if (!extension) {
  110140. return null;
  110141. }
  110142. // Clear out the extension before executing the action to avoid infinite recursion.
  110143. delete extensions[this.name];
  110144. try {
  110145. return actionAsync(context + "/extensions/" + this.name, extension);
  110146. }
  110147. finally {
  110148. // Restore the extension after executing the action.
  110149. extensions[this.name] = extension;
  110150. }
  110151. };
  110152. /**
  110153. * Helper method called by the loader to allow extensions to override loading scenes.
  110154. * @hidden
  110155. */
  110156. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  110157. if (!property.extras) {
  110158. return null;
  110159. }
  110160. var extras = property.extras;
  110161. var value = extras[this.name];
  110162. if (value === undefined) {
  110163. return null;
  110164. }
  110165. // Clear out the extras value before executing the action to avoid infinite recursion.
  110166. delete extras[this.name];
  110167. try {
  110168. return actionAsync(context + "/extras/" + this.name, value);
  110169. }
  110170. finally {
  110171. // Restore the extras value after executing the action.
  110172. extras[this.name] = value;
  110173. }
  110174. };
  110175. /**
  110176. * Helper method called by the loader to allow extensions to override loading scenes.
  110177. * @hidden
  110178. */
  110179. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  110180. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  110181. };
  110182. /**
  110183. * Helper method called by the loader to allow extensions to override loading nodes.
  110184. * @hidden
  110185. */
  110186. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  110187. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  110188. };
  110189. /**
  110190. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  110191. * @hidden
  110192. */
  110193. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  110194. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  110195. };
  110196. /**
  110197. * Helper method called by the loader to allow extensions to override loading materials.
  110198. * @hidden
  110199. */
  110200. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110201. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  110202. };
  110203. /**
  110204. * Helper method called by the loader to allow extensions to override loading material properties.
  110205. * @hidden
  110206. */
  110207. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  110208. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  110209. };
  110210. /**
  110211. * Helper method called by the loader to allow extensions to override loading textures.
  110212. * @hidden
  110213. */
  110214. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  110215. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  110216. };
  110217. /**
  110218. * Helper method called by the loader to allow extensions to override loading uris.
  110219. * @hidden
  110220. */
  110221. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  110222. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  110223. };
  110224. return GLTFLoaderExtension;
  110225. }());
  110226. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  110227. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110228. })(BABYLON || (BABYLON = {}));
  110229. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  110230. var BABYLON;
  110231. (function (BABYLON) {
  110232. var GLTF2;
  110233. (function (GLTF2) {
  110234. var Extensions;
  110235. (function (Extensions) {
  110236. var NAME = "MSFT_lod";
  110237. /**
  110238. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  110239. */
  110240. var MSFT_lod = /** @class */ (function (_super) {
  110241. __extends(MSFT_lod, _super);
  110242. function MSFT_lod(loader) {
  110243. var _this = _super.call(this, loader) || this;
  110244. _this.name = NAME;
  110245. /**
  110246. * Maximum number of LODs to load, starting from the lowest LOD.
  110247. */
  110248. _this.maxLODsToLoad = Number.MAX_VALUE;
  110249. /**
  110250. * Observable raised when all node LODs of one level are loaded.
  110251. * The event data is the index of the loaded LOD starting from zero.
  110252. * Dispose the loader to cancel the loading of the next level of LODs.
  110253. */
  110254. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  110255. /**
  110256. * Observable raised when all material LODs of one level are loaded.
  110257. * The event data is the index of the loaded LOD starting from zero.
  110258. * Dispose the loader to cancel the loading of the next level of LODs.
  110259. */
  110260. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  110261. _this._nodeIndexLOD = null;
  110262. _this._nodeSignalLODs = new Array();
  110263. _this._nodePromiseLODs = new Array();
  110264. _this._materialIndexLOD = null;
  110265. _this._materialSignalLODs = new Array();
  110266. _this._materialPromiseLODs = new Array();
  110267. _this._loader._readyPromise.then(function () {
  110268. var _loop_1 = function (indexLOD) {
  110269. var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {
  110270. if (indexLOD !== 0) {
  110271. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  110272. }
  110273. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  110274. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  110275. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  110276. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  110277. _this._nodeSignalLODs[indexLOD].resolve();
  110278. }
  110279. });
  110280. _this._loader._completePromises.push(promise);
  110281. };
  110282. for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {
  110283. _loop_1(indexLOD);
  110284. }
  110285. var _loop_2 = function (indexLOD) {
  110286. var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {
  110287. if (indexLOD !== 0) {
  110288. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  110289. }
  110290. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  110291. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  110292. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  110293. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  110294. _this._materialSignalLODs[indexLOD].resolve();
  110295. }
  110296. });
  110297. _this._loader._completePromises.push(promise);
  110298. };
  110299. for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {
  110300. _loop_2(indexLOD);
  110301. }
  110302. });
  110303. return _this;
  110304. }
  110305. MSFT_lod.prototype.dispose = function () {
  110306. _super.prototype.dispose.call(this);
  110307. this._nodeIndexLOD = null;
  110308. this._nodeSignalLODs.length = 0;
  110309. this._nodePromiseLODs.length = 0;
  110310. this._materialIndexLOD = null;
  110311. this._materialSignalLODs.length = 0;
  110312. this._materialPromiseLODs.length = 0;
  110313. this.onMaterialLODsLoadedObservable.clear();
  110314. this.onNodeLODsLoadedObservable.clear();
  110315. };
  110316. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  110317. var _this = this;
  110318. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  110319. var firstPromise;
  110320. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  110321. _this._loader._parent._logOpen("" + extensionContext);
  110322. var _loop_3 = function (indexLOD) {
  110323. var nodeLOD = nodeLODs[indexLOD];
  110324. if (indexLOD !== 0) {
  110325. _this._nodeIndexLOD = indexLOD;
  110326. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  110327. }
  110328. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  110329. if (indexLOD !== 0) {
  110330. var previousNodeLOD = nodeLODs[indexLOD - 1];
  110331. if (previousNodeLOD._babylonMesh) {
  110332. previousNodeLOD._babylonMesh.dispose();
  110333. delete previousNodeLOD._babylonMesh;
  110334. _this._disposeUnusedMaterials();
  110335. }
  110336. }
  110337. });
  110338. if (indexLOD === 0) {
  110339. firstPromise = promise;
  110340. }
  110341. else {
  110342. _this._nodeIndexLOD = null;
  110343. }
  110344. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  110345. _this._nodePromiseLODs[indexLOD].push(promise);
  110346. };
  110347. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  110348. _loop_3(indexLOD);
  110349. }
  110350. _this._loader._parent._logClose();
  110351. return firstPromise;
  110352. });
  110353. };
  110354. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110355. var _this = this;
  110356. // Don't load material LODs if already loading a node LOD.
  110357. if (this._nodeIndexLOD) {
  110358. return null;
  110359. }
  110360. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  110361. var firstPromise;
  110362. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  110363. _this._loader._parent._logOpen("" + extensionContext);
  110364. var _loop_4 = function (indexLOD) {
  110365. var materialLOD = materialLODs[indexLOD];
  110366. if (indexLOD !== 0) {
  110367. _this._materialIndexLOD = indexLOD;
  110368. }
  110369. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  110370. if (indexLOD !== 0) {
  110371. var babylonDataLOD = materialLOD._babylonData;
  110372. assign(babylonDataLOD[babylonDrawMode].material);
  110373. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  110374. if (previousBabylonDataLOD[babylonDrawMode]) {
  110375. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  110376. delete previousBabylonDataLOD[babylonDrawMode];
  110377. }
  110378. }
  110379. });
  110380. if (indexLOD === 0) {
  110381. firstPromise = promise;
  110382. }
  110383. else {
  110384. _this._materialIndexLOD = null;
  110385. }
  110386. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  110387. _this._materialPromiseLODs[indexLOD].push(promise);
  110388. };
  110389. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  110390. _loop_4(indexLOD);
  110391. }
  110392. _this._loader._parent._logClose();
  110393. return firstPromise;
  110394. });
  110395. };
  110396. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  110397. var _this = this;
  110398. // Defer the loading of uris if loading a material or node LOD.
  110399. if (this._materialIndexLOD !== null) {
  110400. this._loader._parent._log("deferred");
  110401. var previousIndexLOD = this._materialIndexLOD - 1;
  110402. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  110403. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  110404. return _this._loader._loadUriAsync(context, uri);
  110405. });
  110406. }
  110407. else if (this._nodeIndexLOD !== null) {
  110408. this._loader._parent._log("deferred");
  110409. var previousIndexLOD = this._nodeIndexLOD - 1;
  110410. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  110411. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  110412. return _this._loader._loadUriAsync(context, uri);
  110413. });
  110414. }
  110415. return null;
  110416. };
  110417. /**
  110418. * Gets an array of LOD properties from lowest to highest.
  110419. */
  110420. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  110421. if (this.maxLODsToLoad <= 0) {
  110422. throw new Error("maxLODsToLoad must be greater than zero");
  110423. }
  110424. var properties = new Array();
  110425. for (var i = ids.length - 1; i >= 0; i--) {
  110426. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  110427. if (properties.length === this.maxLODsToLoad) {
  110428. return properties;
  110429. }
  110430. }
  110431. properties.push(property);
  110432. return properties;
  110433. };
  110434. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  110435. var materials = this._loader._gltf.materials;
  110436. if (materials) {
  110437. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  110438. var material = materials_1[_i];
  110439. if (material._babylonData) {
  110440. for (var drawMode in material._babylonData) {
  110441. var babylonData = material._babylonData[drawMode];
  110442. if (babylonData.meshes.length === 0) {
  110443. babylonData.material.dispose(false, true);
  110444. delete material._babylonData[drawMode];
  110445. }
  110446. }
  110447. }
  110448. }
  110449. }
  110450. };
  110451. return MSFT_lod;
  110452. }(GLTF2.GLTFLoaderExtension));
  110453. Extensions.MSFT_lod = MSFT_lod;
  110454. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  110455. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110456. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110457. })(BABYLON || (BABYLON = {}));
  110458. //# sourceMappingURL=MSFT_lod.js.map
  110459. var BABYLON;
  110460. (function (BABYLON) {
  110461. var GLTF2;
  110462. (function (GLTF2) {
  110463. var Extensions;
  110464. (function (Extensions) {
  110465. var NAME = "MSFT_minecraftMesh";
  110466. /** @hidden */
  110467. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  110468. __extends(MSFT_minecraftMesh, _super);
  110469. function MSFT_minecraftMesh() {
  110470. var _this = _super !== null && _super.apply(this, arguments) || this;
  110471. _this.name = NAME;
  110472. return _this;
  110473. }
  110474. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110475. var _this = this;
  110476. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  110477. if (value) {
  110478. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  110479. if (babylonMaterial.needAlphaBlending()) {
  110480. babylonMaterial.forceDepthWrite = true;
  110481. babylonMaterial.separateCullingPass = true;
  110482. }
  110483. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  110484. babylonMaterial.twoSidedLighting = true;
  110485. assign(babylonMaterial);
  110486. });
  110487. }
  110488. return null;
  110489. });
  110490. };
  110491. return MSFT_minecraftMesh;
  110492. }(GLTF2.GLTFLoaderExtension));
  110493. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  110494. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  110495. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110496. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110497. })(BABYLON || (BABYLON = {}));
  110498. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  110499. var BABYLON;
  110500. (function (BABYLON) {
  110501. var GLTF2;
  110502. (function (GLTF2) {
  110503. var Extensions;
  110504. (function (Extensions) {
  110505. var NAME = "MSFT_sRGBFactors";
  110506. /** @hidden */
  110507. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  110508. __extends(MSFT_sRGBFactors, _super);
  110509. function MSFT_sRGBFactors() {
  110510. var _this = _super !== null && _super.apply(this, arguments) || this;
  110511. _this.name = NAME;
  110512. return _this;
  110513. }
  110514. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110515. var _this = this;
  110516. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  110517. if (value) {
  110518. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  110519. if (!babylonMaterial.albedoTexture) {
  110520. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  110521. }
  110522. if (!babylonMaterial.reflectivityTexture) {
  110523. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  110524. }
  110525. assign(babylonMaterial);
  110526. });
  110527. }
  110528. return null;
  110529. });
  110530. };
  110531. return MSFT_sRGBFactors;
  110532. }(GLTF2.GLTFLoaderExtension));
  110533. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  110534. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  110535. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110536. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110537. })(BABYLON || (BABYLON = {}));
  110538. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  110539. var BABYLON;
  110540. (function (BABYLON) {
  110541. var GLTF2;
  110542. (function (GLTF2) {
  110543. var Extensions;
  110544. (function (Extensions) {
  110545. var NAME = "KHR_draco_mesh_compression";
  110546. /**
  110547. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  110548. */
  110549. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  110550. __extends(KHR_draco_mesh_compression, _super);
  110551. function KHR_draco_mesh_compression(loader) {
  110552. var _this = _super.call(this, loader) || this;
  110553. _this.name = NAME;
  110554. _this._dracoCompression = null;
  110555. // Disable extension if decoder is not available.
  110556. if (!BABYLON.DracoCompression.DecoderAvailable) {
  110557. _this.enabled = false;
  110558. }
  110559. return _this;
  110560. }
  110561. KHR_draco_mesh_compression.prototype.dispose = function () {
  110562. if (this._dracoCompression) {
  110563. this._dracoCompression.dispose();
  110564. }
  110565. _super.prototype.dispose.call(this);
  110566. };
  110567. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110568. var _this = this;
  110569. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  110570. if (primitive.mode != undefined) {
  110571. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  110572. primitive.mode !== 4 /* TRIANGLES */) {
  110573. throw new Error(context + ": Unsupported mode " + primitive.mode);
  110574. }
  110575. // TODO: handle triangle strips
  110576. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  110577. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  110578. }
  110579. }
  110580. var attributes = {};
  110581. var loadAttribute = function (name, kind) {
  110582. var uniqueId = extension.attributes[name];
  110583. if (uniqueId == undefined) {
  110584. return;
  110585. }
  110586. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  110587. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  110588. babylonMesh._delayInfo.push(kind);
  110589. }
  110590. attributes[kind] = uniqueId;
  110591. };
  110592. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  110593. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  110594. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  110595. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110596. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110597. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110598. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110599. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  110600. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  110601. if (!bufferView._dracoBabylonGeometry) {
  110602. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110603. if (!_this._dracoCompression) {
  110604. _this._dracoCompression = new BABYLON.DracoCompression();
  110605. }
  110606. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  110607. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  110608. babylonVertexData.applyToGeometry(babylonGeometry);
  110609. return babylonGeometry;
  110610. }).catch(function (error) {
  110611. throw new Error(context + ": " + error.message);
  110612. });
  110613. });
  110614. }
  110615. return bufferView._dracoBabylonGeometry;
  110616. });
  110617. };
  110618. return KHR_draco_mesh_compression;
  110619. }(GLTF2.GLTFLoaderExtension));
  110620. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  110621. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  110622. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110623. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110624. })(BABYLON || (BABYLON = {}));
  110625. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  110626. var BABYLON;
  110627. (function (BABYLON) {
  110628. var GLTF2;
  110629. (function (GLTF2) {
  110630. var Extensions;
  110631. (function (Extensions) {
  110632. var NAME = "KHR_materials_pbrSpecularGlossiness";
  110633. /**
  110634. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  110635. */
  110636. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  110637. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  110638. function KHR_materials_pbrSpecularGlossiness() {
  110639. var _this = _super !== null && _super.apply(this, arguments) || this;
  110640. _this.name = NAME;
  110641. return _this;
  110642. }
  110643. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  110644. var _this = this;
  110645. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  110646. var promises = new Array();
  110647. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  110648. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  110649. return Promise.all(promises).then(function () { });
  110650. });
  110651. };
  110652. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  110653. var promises = new Array();
  110654. if (properties.diffuseFactor) {
  110655. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  110656. babylonMaterial.alpha = properties.diffuseFactor[3];
  110657. }
  110658. else {
  110659. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110660. }
  110661. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  110662. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  110663. if (properties.diffuseTexture) {
  110664. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  110665. babylonMaterial.albedoTexture = texture;
  110666. }));
  110667. }
  110668. if (properties.specularGlossinessTexture) {
  110669. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  110670. babylonMaterial.reflectivityTexture = texture;
  110671. }));
  110672. babylonMaterial.reflectivityTexture.hasAlpha = true;
  110673. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  110674. }
  110675. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110676. return Promise.all(promises).then(function () { });
  110677. };
  110678. return KHR_materials_pbrSpecularGlossiness;
  110679. }(GLTF2.GLTFLoaderExtension));
  110680. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  110681. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  110682. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110683. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110684. })(BABYLON || (BABYLON = {}));
  110685. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  110686. var BABYLON;
  110687. (function (BABYLON) {
  110688. var GLTF2;
  110689. (function (GLTF2) {
  110690. var Extensions;
  110691. (function (Extensions) {
  110692. var NAME = "KHR_materials_unlit";
  110693. /**
  110694. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  110695. */
  110696. var KHR_materials_unlit = /** @class */ (function (_super) {
  110697. __extends(KHR_materials_unlit, _super);
  110698. function KHR_materials_unlit() {
  110699. var _this = _super !== null && _super.apply(this, arguments) || this;
  110700. _this.name = NAME;
  110701. return _this;
  110702. }
  110703. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  110704. var _this = this;
  110705. return this._loadExtensionAsync(context, material, function () {
  110706. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  110707. });
  110708. };
  110709. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  110710. var promises = new Array();
  110711. babylonMaterial.unlit = true;
  110712. // Ensure metallic workflow
  110713. babylonMaterial.metallic = 1;
  110714. babylonMaterial.roughness = 1;
  110715. var properties = material.pbrMetallicRoughness;
  110716. if (properties) {
  110717. if (properties.baseColorFactor) {
  110718. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  110719. babylonMaterial.alpha = properties.baseColorFactor[3];
  110720. }
  110721. else {
  110722. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110723. }
  110724. if (properties.baseColorTexture) {
  110725. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  110726. babylonMaterial.albedoTexture = texture;
  110727. }));
  110728. }
  110729. }
  110730. if (material.doubleSided) {
  110731. babylonMaterial.backFaceCulling = false;
  110732. babylonMaterial.twoSidedLighting = true;
  110733. }
  110734. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110735. return Promise.all(promises).then(function () { });
  110736. };
  110737. return KHR_materials_unlit;
  110738. }(GLTF2.GLTFLoaderExtension));
  110739. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  110740. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  110741. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110742. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110743. })(BABYLON || (BABYLON = {}));
  110744. //# sourceMappingURL=KHR_materials_unlit.js.map
  110745. var BABYLON;
  110746. (function (BABYLON) {
  110747. var GLTF2;
  110748. (function (GLTF2) {
  110749. var Extensions;
  110750. (function (Extensions) {
  110751. var NAME = "KHR_lights";
  110752. var LightType;
  110753. (function (LightType) {
  110754. LightType["AMBIENT"] = "ambient";
  110755. LightType["DIRECTIONAL"] = "directional";
  110756. LightType["POINT"] = "point";
  110757. LightType["SPOT"] = "spot";
  110758. })(LightType || (LightType = {}));
  110759. /**
  110760. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  110761. */
  110762. var KHR_lights = /** @class */ (function (_super) {
  110763. __extends(KHR_lights, _super);
  110764. function KHR_lights() {
  110765. var _this = _super !== null && _super.apply(this, arguments) || this;
  110766. _this.name = NAME;
  110767. return _this;
  110768. }
  110769. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  110770. var _this = this;
  110771. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  110772. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  110773. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  110774. if (light.type !== LightType.AMBIENT) {
  110775. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  110776. }
  110777. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  110778. return promise;
  110779. });
  110780. };
  110781. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  110782. var _this = this;
  110783. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  110784. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  110785. var babylonLight;
  110786. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  110787. var name = node._babylonMesh.name;
  110788. switch (light.type) {
  110789. case LightType.AMBIENT: {
  110790. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  110791. }
  110792. case LightType.DIRECTIONAL: {
  110793. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  110794. break;
  110795. }
  110796. case LightType.POINT: {
  110797. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  110798. break;
  110799. }
  110800. case LightType.SPOT: {
  110801. var spotLight = light;
  110802. // TODO: support inner and outer cone angles
  110803. //const innerConeAngle = spotLight.innerConeAngle || 0;
  110804. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  110805. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  110806. break;
  110807. }
  110808. default: {
  110809. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  110810. }
  110811. }
  110812. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  110813. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  110814. babylonLight.parent = node._babylonMesh;
  110815. return promise;
  110816. });
  110817. };
  110818. Object.defineProperty(KHR_lights.prototype, "_lights", {
  110819. get: function () {
  110820. var extensions = this._loader._gltf.extensions;
  110821. if (!extensions || !extensions[this.name]) {
  110822. throw new Error("#/extensions: '" + this.name + "' not found");
  110823. }
  110824. var extension = extensions[this.name];
  110825. return extension.lights;
  110826. },
  110827. enumerable: true,
  110828. configurable: true
  110829. });
  110830. return KHR_lights;
  110831. }(GLTF2.GLTFLoaderExtension));
  110832. Extensions.KHR_lights = KHR_lights;
  110833. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  110834. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110835. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110836. })(BABYLON || (BABYLON = {}));
  110837. var BABYLON;
  110838. (function (BABYLON) {
  110839. var GLTF2;
  110840. (function (GLTF2) {
  110841. var Extensions;
  110842. (function (Extensions) {
  110843. var NAME = "KHR_texture_transform";
  110844. /**
  110845. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  110846. */
  110847. var KHR_texture_transform = /** @class */ (function (_super) {
  110848. __extends(KHR_texture_transform, _super);
  110849. function KHR_texture_transform() {
  110850. var _this = _super !== null && _super.apply(this, arguments) || this;
  110851. _this.name = NAME;
  110852. return _this;
  110853. }
  110854. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  110855. var _this = this;
  110856. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  110857. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  110858. if (extension.offset) {
  110859. babylonTexture.uOffset = extension.offset[0];
  110860. babylonTexture.vOffset = extension.offset[1];
  110861. }
  110862. // Always rotate around the origin.
  110863. babylonTexture.uRotationCenter = 0;
  110864. babylonTexture.vRotationCenter = 0;
  110865. if (extension.rotation) {
  110866. babylonTexture.wAng = -extension.rotation;
  110867. }
  110868. if (extension.scale) {
  110869. babylonTexture.uScale = extension.scale[0];
  110870. babylonTexture.vScale = extension.scale[1];
  110871. }
  110872. if (extension.texCoord != undefined) {
  110873. babylonTexture.coordinatesIndex = extension.texCoord;
  110874. }
  110875. assign(babylonTexture);
  110876. });
  110877. });
  110878. };
  110879. return KHR_texture_transform;
  110880. }(GLTF2.GLTFLoaderExtension));
  110881. Extensions.KHR_texture_transform = KHR_texture_transform;
  110882. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  110883. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110884. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110885. })(BABYLON || (BABYLON = {}));
  110886. return BABYLON;
  110887. });
  110888. /***/ }),
  110889. /* 15 */
  110890. /***/ (function(module, exports, __webpack_require__) {
  110891. module.exports = __webpack_require__(16);
  110892. /***/ }),
  110893. /* 16 */
  110894. /***/ (function(module, exports, __webpack_require__) {
  110895. "use strict";
  110896. function __export(m) {
  110897. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  110898. }
  110899. Object.defineProperty(exports, "__esModule", { value: true });
  110900. var mappers_1 = __webpack_require__(3);
  110901. exports.mapperManager = mappers_1.mapperManager;
  110902. var globals_1 = __webpack_require__(4);
  110903. exports.viewerGlobals = globals_1.viewerGlobals;
  110904. var viewerManager_1 = __webpack_require__(7);
  110905. exports.viewerManager = viewerManager_1.viewerManager;
  110906. var defaultViewer_1 = __webpack_require__(8);
  110907. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  110908. var viewer_1 = __webpack_require__(9);
  110909. exports.AbstractViewer = viewer_1.AbstractViewer;
  110910. var telemetryManager_1 = __webpack_require__(6);
  110911. exports.telemetryManager = telemetryManager_1.telemetryManager;
  110912. var modelLoader_1 = __webpack_require__(13);
  110913. exports.ModelLoader = modelLoader_1.ModelLoader;
  110914. var viewerModel_1 = __webpack_require__(5);
  110915. exports.ViewerModel = viewerModel_1.ViewerModel;
  110916. exports.ModelState = viewerModel_1.ModelState;
  110917. /**
  110918. * BabylonJS Viewer
  110919. *
  110920. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  110921. */
  110922. var BABYLON = __webpack_require__(0);
  110923. exports.BABYLON = BABYLON;
  110924. // load needed modules.
  110925. __webpack_require__(14);
  110926. __webpack_require__(64);
  110927. var initializer_1 = __webpack_require__(65);
  110928. exports.InitTags = initializer_1.InitTags;
  110929. // promise polyfill, if needed!
  110930. BABYLON.PromisePolyfill.Apply();
  110931. initializer_1.initListeners();
  110932. //deprectaed, here for backwards compatibility
  110933. var disableInit = globals_1.viewerGlobals.disableInit;
  110934. exports.disableInit = disableInit;
  110935. /**
  110936. * Dispose all viewers currently registered
  110937. */
  110938. function disposeAll() {
  110939. viewerManager_1.viewerManager.dispose();
  110940. mappers_1.mapperManager.dispose();
  110941. telemetryManager_1.telemetryManager.dispose();
  110942. }
  110943. exports.disposeAll = disposeAll;
  110944. var Version = globals_1.viewerGlobals.version;
  110945. exports.Version = Version;
  110946. console.log("Babylon.js viewer (v" + Version + ")");
  110947. // export publicliy all configuration interfaces
  110948. __export(__webpack_require__(10));
  110949. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxtREFBd0Q7QUE4Q3lFLHdCQTlDeEgsdUJBQWEsQ0E4Q3dIO0FBN0M5SSxtREFBd0Q7QUE2Q1ksd0JBN0MzRCx1QkFBYSxDQTZDMkQ7QUE1Q2pGLHdEQUF1RDtBQTRDMkQsd0JBNUN6Ryw2QkFBYSxDQTRDeUc7QUEzQy9ILHdEQUF1RDtBQTJDbEIsd0JBM0M1Qiw2QkFBYSxDQTJDNEI7QUExQ2xELDBDQUFpRDtBQTBDRyx5QkExQzNDLHVCQUFjLENBMEMyQztBQXpDbEUsZ0VBQStEO0FBeUNvQiwyQkF6QzFFLG1DQUFnQixDQXlDMEU7QUF4Q25HLG9EQUFtRDtBQXdDeUcsc0JBeENuSix5QkFBVyxDQXdDbUo7QUF2Q3ZLLG1EQUE4RDtBQXVDMkcsc0JBdkNoSyx5QkFBVyxDQXVDZ0s7QUFBcUMscUJBdkNuTSx3QkFBVSxDQXVDbU07QUFuQ25POzs7O0dBSUc7QUFFSCxtQ0FBcUM7QUE2QjVCLDBCQUFPO0FBM0JoQix1QkFBdUI7QUFDdkIsNkJBQTJCO0FBQzNCLGlCQUFlO0FBRWYsNkNBQXdEO0FBdUI3QixtQkF2Qkgsc0JBQVEsQ0F1Qkc7QUFyQm5DLCtCQUErQjtBQUMvQixPQUFPLENBQUMsZUFBZSxDQUFDLEtBQUssRUFBRSxDQUFDO0FBQ2hDLDJCQUFhLEVBQUUsQ0FBQztBQUVoQiw4Q0FBOEM7QUFDOUMsSUFBSSxXQUFXLEdBQVksdUJBQWEsQ0FBQyxXQUFXLENBQUM7QUFnQmdELGtDQUFXO0FBZGhIOztHQUVHO0FBQ0g7SUFDSSw2QkFBYSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ3hCLHVCQUFhLENBQUMsT0FBTyxFQUFFLENBQUM7SUFDeEIsbUNBQWdCLENBQUMsT0FBTyxFQUFFLENBQUM7QUFDL0IsQ0FBQztBQU8rSSxnQ0FBVTtBQUwxSixJQUFNLE9BQU8sR0FBRyx1QkFBYSxDQUFDLE9BQU8sQ0FBQztBQUtwQiwwQkFBTztBQUh6QixPQUFPLENBQUMsR0FBRyxDQUFDLHNCQUFzQixHQUFHLE9BQU8sR0FBRyxHQUFHLENBQUMsQ0FBQztBQUlwRCxnREFBZ0Q7QUFDaEQscUNBQWdDIn0=
  110950. /***/ }),
  110951. /* 17 */
  110952. /***/ (function(module, exports) {
  110953. var g;
  110954. // This works in non-strict mode
  110955. g = (function() {
  110956. return this;
  110957. })();
  110958. try {
  110959. // This works if eval is allowed (see CSP)
  110960. g = g || Function("return this")() || (1,eval)("this");
  110961. } catch(e) {
  110962. // This works if the window reference is available
  110963. if(typeof window === "object")
  110964. g = window;
  110965. }
  110966. // g can still be undefined, but nothing to do about it...
  110967. // We return undefined, instead of nothing here, so it's
  110968. // easier to handle this case. if(!global) { ...}
  110969. module.exports = g;
  110970. /***/ }),
  110971. /* 18 */
  110972. /***/ (function(module, exports) {
  110973. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  110974. module.exports = CANNON;
  110975. /***/ }),
  110976. /* 19 */
  110977. /***/ (function(module, exports) {
  110978. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  110979. module.exports = OIMO;
  110980. /***/ }),
  110981. /* 20 */
  110982. /***/ (function(module, exports) {
  110983. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  110984. module.exports = earcut;
  110985. /***/ }),
  110986. /* 21 */
  110987. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  110988. "use strict";
  110989. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  110990. var isMergeableObject = function isMergeableObject(value) {
  110991. return isNonNullObject(value)
  110992. && !isSpecial(value)
  110993. };
  110994. function isNonNullObject(value) {
  110995. return !!value && typeof value === 'object'
  110996. }
  110997. function isSpecial(value) {
  110998. var stringValue = Object.prototype.toString.call(value);
  110999. return stringValue === '[object RegExp]'
  111000. || stringValue === '[object Date]'
  111001. || isReactElement(value)
  111002. }
  111003. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  111004. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  111005. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  111006. function isReactElement(value) {
  111007. return value.$$typeof === REACT_ELEMENT_TYPE
  111008. }
  111009. function emptyTarget(val) {
  111010. return Array.isArray(val) ? [] : {}
  111011. }
  111012. function cloneUnlessOtherwiseSpecified(value, options) {
  111013. return (options.clone !== false && options.isMergeableObject(value))
  111014. ? deepmerge(emptyTarget(value), value, options)
  111015. : value
  111016. }
  111017. function defaultArrayMerge(target, source, options) {
  111018. return target.concat(source).map(function(element) {
  111019. return cloneUnlessOtherwiseSpecified(element, options)
  111020. })
  111021. }
  111022. function mergeObject(target, source, options) {
  111023. var destination = {};
  111024. if (options.isMergeableObject(target)) {
  111025. Object.keys(target).forEach(function(key) {
  111026. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  111027. });
  111028. }
  111029. Object.keys(source).forEach(function(key) {
  111030. if (!options.isMergeableObject(source[key]) || !target[key]) {
  111031. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  111032. } else {
  111033. destination[key] = deepmerge(target[key], source[key], options);
  111034. }
  111035. });
  111036. return destination
  111037. }
  111038. function deepmerge(target, source, options) {
  111039. options = options || {};
  111040. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  111041. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  111042. var sourceIsArray = Array.isArray(source);
  111043. var targetIsArray = Array.isArray(target);
  111044. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  111045. if (!sourceAndTargetTypesMatch) {
  111046. return cloneUnlessOtherwiseSpecified(source, options)
  111047. } else if (sourceIsArray) {
  111048. return options.arrayMerge(target, source, options)
  111049. } else {
  111050. return mergeObject(target, source, options)
  111051. }
  111052. }
  111053. deepmerge.all = function deepmergeAll(array, options) {
  111054. if (!Array.isArray(array)) {
  111055. throw new Error('first argument should be an array')
  111056. }
  111057. return array.reduce(function(prev, next) {
  111058. return deepmerge(prev, next, options)
  111059. }, {})
  111060. };
  111061. var deepmerge_1 = deepmerge;
  111062. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  111063. /***/ }),
  111064. /* 22 */
  111065. /***/ (function(module, exports, __webpack_require__) {
  111066. "use strict";
  111067. Object.defineProperty(exports, "__esModule", { value: true });
  111068. var babylonjs_1 = __webpack_require__(0);
  111069. var configuration_1 = __webpack_require__(10);
  111070. var viewerModel_1 = __webpack_require__(5);
  111071. var helper_1 = __webpack_require__(1);
  111072. var viewerLabs_1 = __webpack_require__(24);
  111073. var _1 = __webpack_require__(26);
  111074. var SceneManager = /** @class */ (function () {
  111075. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  111076. var _this = this;
  111077. this._engine = _engine;
  111078. this._configurationContainer = _configurationContainer;
  111079. this._observablesManager = _observablesManager;
  111080. this._animationBlendingEnabled = true;
  111081. this._white = babylonjs_1.Color3.White();
  111082. this._forceShadowUpdate = false;
  111083. this._processShadows = true;
  111084. this._groundEnabled = true;
  111085. this._groundMirrorEnabled = true;
  111086. this._defaultRenderingPipelineEnabled = false;
  111087. this._globalConfiguration = {};
  111088. this._defaultRenderingPipelineShouldBuild = true;
  111089. // default from rendering pipeline
  111090. this._bloomEnabled = false;
  111091. // default from rendering pipeline
  111092. this._fxaaEnabled = false;
  111093. this._focusOnModel = function (model) {
  111094. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  111095. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  111096. var halfSizeVec = sizeVec.scale(0.5);
  111097. var center = boundingInfo.min.add(halfSizeVec);
  111098. _this.camera.setTarget(center);
  111099. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  111100. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  111101. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  111102. var sceneDiagonalLenght = sizeVec.length();
  111103. if (isFinite(sceneDiagonalLenght))
  111104. _this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  111105. if (_this._configurationContainer.configuration)
  111106. _this._configureEnvironment(_this._configurationContainer.configuration.skybox, _this._configurationContainer.configuration.ground);
  111107. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  111108. // casting ais safe, due to the constraints tested before
  111109. (<ShadowLight>light).setDirectionToTarget(center);
  111110. });*/
  111111. };
  111112. this._cameraBehaviorMapping = {};
  111113. this.models = [];
  111114. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  111115. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  111116. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  111117. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  111118. this.onSceneInitObservable = new babylonjs_1.Observable();
  111119. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  111120. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  111121. //this._viewer.onEngineInitObservable.add(() => {
  111122. this._handleHardwareLimitations();
  111123. //});
  111124. this.onSceneInitObservable.add(function (scene) {
  111125. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  111126. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  111127. var updateShadows = function () {
  111128. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  111129. var light = _a[_i];
  111130. var generator = light.getShadowGenerator();
  111131. if (generator) {
  111132. // Processing shadows if animates
  111133. var shadowMap = generator.getShadowMap();
  111134. if (shadowMap) {
  111135. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  111136. }
  111137. }
  111138. }
  111139. };
  111140. scene.registerBeforeRender(function () {
  111141. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  111142. // make sure all models are loaded
  111143. updateShadows();
  111144. _this._forceShadowUpdate = false;
  111145. }
  111146. else if (!(_this.models.every(function (model) {
  111147. if (!model.shadowsRenderedAfterLoad) {
  111148. model.shadowsRenderedAfterLoad = true;
  111149. return false;
  111150. }
  111151. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  111152. }))) {
  111153. updateShadows();
  111154. }
  111155. });
  111156. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  111157. });
  111158. if (this._observablesManager) {
  111159. this._observablesManager.onModelLoadedObservable.add(function (model) {
  111160. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  111161. var light = _a[_i];
  111162. var generator = light.getShadowGenerator();
  111163. if (generator) {
  111164. // Processing shadows if animates
  111165. var shadowMap = generator.getShadowMap();
  111166. if (shadowMap) {
  111167. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  111168. }
  111169. }
  111170. }
  111171. _this._focusOnModel(model);
  111172. });
  111173. this._observablesManager.onModelAddedObservable.add(function (model) {
  111174. _this.models.push(model);
  111175. });
  111176. this._observablesManager.onModelRemovedObservable.add(function (model) {
  111177. _this.models.splice(_this.models.indexOf(model), 1);
  111178. });
  111179. }
  111180. }
  111181. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  111182. get: function () {
  111183. return this._defaultRenderingPipeline;
  111184. },
  111185. enumerable: true,
  111186. configurable: true
  111187. });
  111188. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  111189. /**
  111190. * Returns a boolean representing HDR support
  111191. */
  111192. get: function () {
  111193. return this._hdrSupport;
  111194. },
  111195. enumerable: true,
  111196. configurable: true
  111197. });
  111198. Object.defineProperty(SceneManager.prototype, "mainColor", {
  111199. /**
  111200. * Return the main color defined in the configuration.
  111201. */
  111202. get: function () {
  111203. return this._configurationContainer.mainColor;
  111204. },
  111205. enumerable: true,
  111206. configurable: true
  111207. });
  111208. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  111209. get: function () {
  111210. return this._configurationContainer.reflectionColor;
  111211. },
  111212. enumerable: true,
  111213. configurable: true
  111214. });
  111215. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  111216. get: function () {
  111217. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  111218. },
  111219. set: function (value) {
  111220. this.scene.animationPropertiesOverride.enableBlending = value;
  111221. },
  111222. enumerable: true,
  111223. configurable: true
  111224. });
  111225. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  111226. get: function () {
  111227. return this._observablesManager;
  111228. },
  111229. enumerable: true,
  111230. configurable: true
  111231. });
  111232. Object.defineProperty(SceneManager.prototype, "processShadows", {
  111233. /**
  111234. * The flag defining whether shadows are rendered constantly or once.
  111235. */
  111236. get: function () {
  111237. return this._processShadows;
  111238. },
  111239. /**
  111240. * Should shadows be rendered every frame, or only once and stop.
  111241. * This can be used to optimize a scene.
  111242. *
  111243. * Not that the shadows will NOT disapear but will remain in place.
  111244. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  111245. */
  111246. set: function (process) {
  111247. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  111248. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  111249. var light = _a[_i];
  111250. var generator = light.getShadowGenerator();
  111251. if (generator) {
  111252. var shadowMap = generator.getShadowMap();
  111253. if (shadowMap) {
  111254. shadowMap.refreshRate = refreshType;
  111255. }
  111256. }
  111257. }
  111258. this._processShadows = process;
  111259. },
  111260. enumerable: true,
  111261. configurable: true
  111262. });
  111263. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  111264. get: function () {
  111265. return this._groundEnabled;
  111266. },
  111267. set: function (newValue) {
  111268. if (newValue === this._groundEnabled)
  111269. return;
  111270. this._groundEnabled = newValue;
  111271. if (this.environmentHelper && this.environmentHelper.ground) {
  111272. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  111273. }
  111274. },
  111275. enumerable: true,
  111276. configurable: true
  111277. });
  111278. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  111279. /**
  111280. * gets wether the reflection is disabled.
  111281. */
  111282. get: function () {
  111283. return this._groundMirrorEnabled;
  111284. },
  111285. /**
  111286. * sets wether the reflection is disabled.
  111287. */
  111288. set: function (value) {
  111289. if (this._groundMirrorEnabled === value) {
  111290. return;
  111291. }
  111292. this._groundMirrorEnabled = value;
  111293. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  111294. if (!value) {
  111295. this.environmentHelper.groundMaterial.reflectionTexture = null;
  111296. }
  111297. else {
  111298. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  111299. }
  111300. }
  111301. },
  111302. enumerable: true,
  111303. configurable: true
  111304. });
  111305. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  111306. get: function () {
  111307. return this._defaultRenderingPipelineEnabled;
  111308. },
  111309. set: function (value) {
  111310. if (value === this._defaultRenderingPipelineEnabled) {
  111311. return;
  111312. }
  111313. this._defaultRenderingPipelineEnabled = value;
  111314. this._rebuildPostprocesses();
  111315. if (this._defaultRenderingPipeline) {
  111316. this._defaultRenderingPipelineShouldBuild = false;
  111317. this._defaultRenderingPipeline.prepare();
  111318. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  111319. }
  111320. },
  111321. enumerable: true,
  111322. configurable: true
  111323. });
  111324. /**
  111325. * Sets the engine flags to unlock all babylon features.
  111326. * Can also be configured using the scene.flags configuration object
  111327. */
  111328. SceneManager.prototype.unlockBabylonFeatures = function () {
  111329. this.scene.shadowsEnabled = true;
  111330. this.scene.particlesEnabled = true;
  111331. this.scene.postProcessesEnabled = true;
  111332. this.scene.collisionsEnabled = true;
  111333. this.scene.lightsEnabled = true;
  111334. this.scene.texturesEnabled = true;
  111335. this.scene.lensFlaresEnabled = true;
  111336. this.scene.proceduralTexturesEnabled = true;
  111337. this.scene.renderTargetsEnabled = true;
  111338. this.scene.spritesEnabled = true;
  111339. this.scene.skeletonsEnabled = true;
  111340. this.scene.audioEnabled = true;
  111341. };
  111342. /**
  111343. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  111344. */
  111345. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  111346. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  111347. // if the scen exists, dispose it.
  111348. if (this.scene) {
  111349. this.scene.dispose();
  111350. }
  111351. // create a new scene
  111352. this.scene = new babylonjs_1.Scene(this._engine);
  111353. this._configurationContainer.scene = this.scene;
  111354. // set a default PBR material
  111355. if (!sceneConfiguration.defaultMaterial) {
  111356. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  111357. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  111358. defaultMaterial.microSurface = 0.6;
  111359. if (this.scene.defaultMaterial) {
  111360. this.scene.defaultMaterial.dispose();
  111361. }
  111362. this.scene.defaultMaterial = defaultMaterial;
  111363. }
  111364. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  111365. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  111366. /*if (sceneConfiguration.glow) {
  111367. let options: Partial<IGlowLayerOptions> = {
  111368. mainTextureFixedSize: 512
  111369. };
  111370. if (typeof sceneConfiguration.glow === 'object') {
  111371. options = sceneConfiguration.glow
  111372. }
  111373. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  111374. }*/
  111375. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  111376. };
  111377. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  111378. if (clearModels === void 0) { clearModels = true; }
  111379. if (clearLights === void 0) { clearLights = false; }
  111380. if (clearModels) {
  111381. this.models.forEach(function (m) { return m.dispose(); });
  111382. this.models.length = 0;
  111383. }
  111384. if (clearLights) {
  111385. this.scene.lights.forEach(function (l) { return l.dispose(); });
  111386. }
  111387. };
  111388. /**
  111389. * This will update the scene's configuration, including camera, lights, environment.
  111390. * @param newConfiguration the delta that should be configured. This includes only the changes
  111391. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  111392. */
  111393. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  111394. var _this = this;
  111395. if (this._configurationContainer) {
  111396. this._globalConfiguration = this._configurationContainer.configuration;
  111397. }
  111398. else {
  111399. this._globalConfiguration = newConfiguration;
  111400. }
  111401. if (newConfiguration.lab) {
  111402. if (newConfiguration.lab.assetsRootURL) {
  111403. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  111404. }
  111405. }
  111406. // update scene configuration
  111407. if (newConfiguration.scene) {
  111408. this._configureScene(newConfiguration.scene);
  111409. }
  111410. // optimizer
  111411. if (newConfiguration.optimizer !== undefined) {
  111412. this._configureOptimizer(newConfiguration.optimizer);
  111413. }
  111414. // configure model
  111415. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  111416. this._configureModel(newConfiguration.model);
  111417. }*/
  111418. // lights
  111419. this._configureLights(newConfiguration.lights);
  111420. // environment
  111421. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  111422. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  111423. }
  111424. // camera
  111425. this._configureCamera(newConfiguration.camera);
  111426. if (newConfiguration.lab) {
  111427. if (newConfiguration.lab.environmentMap) {
  111428. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  111429. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  111430. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  111431. });
  111432. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  111433. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  111434. }
  111435. }
  111436. // rendering piplines
  111437. if (newConfiguration.lab.defaultRenderingPipelines) {
  111438. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  111439. if (typeof pipelineConfig === 'boolean') {
  111440. this.defaultRenderingPipelineEnabled = pipelineConfig;
  111441. }
  111442. else {
  111443. this.defaultRenderingPipelineEnabled = true;
  111444. }
  111445. }
  111446. if (this.environmentHelper && newConfiguration.lab.environmentMainColor) {
  111447. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  111448. this.environmentHelper.setMainColor(mainColor);
  111449. }
  111450. if (newConfiguration.lab.globalLightRotation !== undefined) {
  111451. // rotate all lights that are shadow lights
  111452. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  111453. // casting and '!' are safe, due to the constraints tested before
  111454. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  111455. });
  111456. this._forceShadowUpdate = true;
  111457. }
  111458. }
  111459. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  111460. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  111461. }
  111462. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  111463. this._defaultRenderingPipelineShouldBuild = false;
  111464. this._defaultRenderingPipeline.prepare();
  111465. }
  111466. };
  111467. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  111468. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  111469. if (this._defaultRenderingPipeline) {
  111470. this._defaultRenderingPipeline.dispose();
  111471. this._defaultRenderingPipeline = null;
  111472. this.scene.autoClearDepthAndStencil = true;
  111473. this.scene.autoClear = true;
  111474. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  111475. }
  111476. return;
  111477. }
  111478. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  111479. if (pipelineConfig) {
  111480. if (!this._defaultRenderingPipeline) {
  111481. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  111482. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  111483. }
  111484. this.scene.autoClear = false;
  111485. this.scene.autoClearDepthAndStencil = false;
  111486. this._defaultRenderingPipelineShouldBuild = true;
  111487. var bloomEnabled = this._bloomEnabled;
  111488. if (typeof pipelineConfig !== 'boolean') {
  111489. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  111490. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  111491. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  111492. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  111493. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  111494. }
  111495. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  111496. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  111497. }
  111498. };
  111499. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  111500. get: function () {
  111501. return this._bloomEnabled;
  111502. },
  111503. set: function (value) {
  111504. if (this._bloomEnabled === value) {
  111505. return;
  111506. }
  111507. this._bloomEnabled = value;
  111508. this._rebuildPostprocesses();
  111509. if (this._defaultRenderingPipeline) {
  111510. this._defaultRenderingPipelineShouldBuild = false;
  111511. this._defaultRenderingPipeline.prepare();
  111512. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  111513. }
  111514. },
  111515. enumerable: true,
  111516. configurable: true
  111517. });
  111518. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  111519. get: function () {
  111520. return this._fxaaEnabled;
  111521. },
  111522. set: function (value) {
  111523. if (this._fxaaEnabled === value) {
  111524. return;
  111525. }
  111526. this._fxaaEnabled = value;
  111527. this._rebuildPostprocesses();
  111528. if (this._defaultRenderingPipeline) {
  111529. this._defaultRenderingPipelineShouldBuild = false;
  111530. this._defaultRenderingPipeline.prepare();
  111531. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  111532. }
  111533. },
  111534. enumerable: true,
  111535. configurable: true
  111536. });
  111537. /**
  111538. * internally configure the scene using the provided configuration.
  111539. * The scene will not be recreated, but just updated.
  111540. * @param sceneConfig the (new) scene configuration
  111541. */
  111542. SceneManager.prototype._configureScene = function (sceneConfig) {
  111543. // sanity check!
  111544. if (!this.scene) {
  111545. return;
  111546. }
  111547. var cc = sceneConfig.clearColor;
  111548. var oldcc = this.scene.clearColor;
  111549. if (cc) {
  111550. if (cc.r !== undefined) {
  111551. oldcc.r = cc.r;
  111552. }
  111553. if (cc.g !== undefined) {
  111554. oldcc.g = cc.g;
  111555. }
  111556. if (cc.b !== undefined) {
  111557. oldcc.b = cc.b;
  111558. }
  111559. if (cc.a !== undefined) {
  111560. oldcc.a = cc.a;
  111561. }
  111562. }
  111563. // image processing configuration - optional.
  111564. if (sceneConfig.imageProcessingConfiguration) {
  111565. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  111566. }
  111567. //animation properties override
  111568. if (sceneConfig.animationPropertiesOverride) {
  111569. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  111570. }
  111571. if (sceneConfig.environmentTexture) {
  111572. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  111573. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  111574. this.scene.environmentTexture.dispose();
  111575. }
  111576. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  111577. this.scene.environmentTexture = environmentTexture;
  111578. }
  111579. }
  111580. if (sceneConfig.debug === true) {
  111581. this.scene.debugLayer.show();
  111582. }
  111583. else if (sceneConfig.debug === false) {
  111584. if (this.scene.debugLayer.isVisible()) {
  111585. this.scene.debugLayer.hide();
  111586. }
  111587. }
  111588. if (sceneConfig.disableHdr) {
  111589. this._handleHardwareLimitations(false);
  111590. }
  111591. else {
  111592. this._handleHardwareLimitations(true);
  111593. }
  111594. if (sceneConfig.renderInBackground !== undefined) {
  111595. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  111596. }
  111597. var canvas = this._engine.getRenderingCanvas();
  111598. if (canvas) {
  111599. if (this.camera && sceneConfig.disableCameraControl) {
  111600. this.camera.detachControl(canvas);
  111601. }
  111602. else if (this.camera && sceneConfig.disableCameraControl === false) {
  111603. this.camera.attachControl(canvas);
  111604. }
  111605. }
  111606. // process mainColor changes:
  111607. if (sceneConfig.mainColor) {
  111608. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  111609. var mc = sceneConfig.mainColor;
  111610. if (mc.r !== undefined) {
  111611. this.mainColor.r = mc.r;
  111612. }
  111613. if (mc.g !== undefined) {
  111614. this.mainColor.g = mc.g;
  111615. }
  111616. if (mc.b !== undefined) {
  111617. this.mainColor.b = mc.b;
  111618. }
  111619. this.reflectionColor.copyFrom(this.mainColor);
  111620. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  111621. // reflection color
  111622. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  111623. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  111624. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  111625. this.reflectionColor.copyFrom(tmpColor3);
  111626. //update the environment, if exists
  111627. if (this.environmentHelper) {
  111628. if (this.environmentHelper.groundMaterial) {
  111629. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  111630. }
  111631. if (this.environmentHelper.skyboxMaterial) {
  111632. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  111633. }
  111634. }
  111635. }
  111636. if (sceneConfig.defaultMaterial) {
  111637. var conf = sceneConfig.defaultMaterial;
  111638. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  111639. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  111640. this.scene.defaultMaterial.dispose();
  111641. if (conf.materialType === 'standard') {
  111642. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  111643. }
  111644. else {
  111645. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  111646. }
  111647. }
  111648. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  111649. }
  111650. if (sceneConfig.flags) {
  111651. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  111652. }
  111653. this.onSceneConfiguredObservable.notifyObservers({
  111654. sceneManager: this,
  111655. object: this.scene,
  111656. newConfiguration: sceneConfig
  111657. });
  111658. };
  111659. /**
  111660. * Configure the scene optimizer.
  111661. * The existing scene optimizer will be disposed and a new one will be created.
  111662. * @param optimizerConfig the (new) optimizer configuration
  111663. */
  111664. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  111665. var _this = this;
  111666. if (typeof optimizerConfig === 'boolean') {
  111667. if (this.sceneOptimizer) {
  111668. this.sceneOptimizer.stop();
  111669. this.sceneOptimizer.dispose();
  111670. delete this.sceneOptimizer;
  111671. }
  111672. if (optimizerConfig) {
  111673. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  111674. this.sceneOptimizer.start();
  111675. }
  111676. }
  111677. else {
  111678. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  111679. // check for degradation
  111680. if (optimizerConfig.degradation) {
  111681. switch (optimizerConfig.degradation) {
  111682. case "low":
  111683. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  111684. break;
  111685. case "moderate":
  111686. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  111687. break;
  111688. case "hight":
  111689. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  111690. break;
  111691. }
  111692. }
  111693. if (this.sceneOptimizer) {
  111694. this.sceneOptimizer.stop();
  111695. this.sceneOptimizer.dispose();
  111696. }
  111697. if (optimizerConfig.custom) {
  111698. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  111699. if (customOptimizer_1) {
  111700. optimizerOptions.addCustomOptimization(function () {
  111701. return customOptimizer_1(_this);
  111702. }, function () {
  111703. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  111704. });
  111705. }
  111706. }
  111707. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  111708. this.sceneOptimizer.start();
  111709. }
  111710. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  111711. sceneManager: this,
  111712. object: this.sceneOptimizer,
  111713. newConfiguration: optimizerConfig
  111714. });
  111715. };
  111716. /**
  111717. * configure all models using the configuration.
  111718. * @param modelConfiguration the configuration to use to reconfigure the models
  111719. */
  111720. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  111721. this.models.forEach(model => {
  111722. model.updateConfiguration(modelConfiguration);
  111723. });
  111724. this.onModelsConfiguredObservable.notifyObservers({
  111725. sceneManager: this,
  111726. object: this.models,
  111727. newConfiguration: modelConfiguration
  111728. });
  111729. }*/
  111730. /**
  111731. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  111732. * @param cameraConfig the new camera configuration
  111733. * @param model optionally use the model to configure the camera.
  111734. */
  111735. SceneManager.prototype._configureCamera = function (cameraConfig) {
  111736. var _this = this;
  111737. if (cameraConfig === void 0) { cameraConfig = {}; }
  111738. if (!this.scene.activeCamera) {
  111739. var attachControl = true;
  111740. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  111741. attachControl = false;
  111742. }
  111743. this.scene.createDefaultCamera(true, true, attachControl);
  111744. this.camera = this.scene.activeCamera;
  111745. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  111746. }
  111747. if (cameraConfig.position) {
  111748. var newPosition = this.camera.position.clone();
  111749. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  111750. this.camera.setPosition(newPosition);
  111751. }
  111752. if (cameraConfig.target) {
  111753. var newTarget = this.camera.target.clone();
  111754. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  111755. this.camera.setTarget(newTarget);
  111756. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  111757. this._focusOnModel(this.models[0]);
  111758. }*/
  111759. if (cameraConfig.rotation) {
  111760. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  111761. }
  111762. if (cameraConfig.behaviors) {
  111763. for (var name_1 in cameraConfig.behaviors) {
  111764. if (cameraConfig.behaviors[name_1] !== undefined) {
  111765. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  111766. }
  111767. }
  111768. }
  111769. ;
  111770. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  111771. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  111772. });
  111773. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  111774. var sceneDiagonalLenght = sceneDiagonal.length();
  111775. if (isFinite(sceneDiagonalLenght))
  111776. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  111777. // sanity check!
  111778. if (this.scene.imageProcessingConfiguration) {
  111779. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  111780. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  111781. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  111782. }
  111783. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  111784. this.onCameraConfiguredObservable.notifyObservers({
  111785. sceneManager: this,
  111786. object: this.camera,
  111787. newConfiguration: cameraConfig
  111788. });
  111789. };
  111790. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  111791. var _this = this;
  111792. if (!skyboxConifguration && !groundConfiguration) {
  111793. if (this.environmentHelper) {
  111794. this.environmentHelper.dispose();
  111795. this.environmentHelper = undefined;
  111796. }
  111797. ;
  111798. }
  111799. else {
  111800. var options = {
  111801. createGround: !!groundConfiguration && this._groundEnabled,
  111802. createSkybox: !!skyboxConifguration,
  111803. setupImageProcessing: false,
  111804. };
  111805. // will that cause problems with model ground configuration?
  111806. /*if (model) {
  111807. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  111808. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  111809. const halfSizeVec = sizeVec.scale(0.5);
  111810. const center = boundingInfo.min.add(halfSizeVec);
  111811. options.groundYBias = -center.y;
  111812. }*/
  111813. if (groundConfiguration) {
  111814. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  111815. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  111816. if (groundSize) {
  111817. options.groundSize = groundSize;
  111818. }
  111819. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  111820. if (groundConfig_1.shadowLevel !== undefined) {
  111821. options.groundShadowLevel = groundConfig_1.shadowLevel;
  111822. }
  111823. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  111824. if (groundConfig_1.texture) {
  111825. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  111826. }
  111827. if (groundConfig_1.color) {
  111828. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  111829. }
  111830. if (groundConfig_1.opacity !== undefined) {
  111831. options.groundOpacity = groundConfig_1.opacity;
  111832. }
  111833. if (groundConfig_1.mirror) {
  111834. options.enableGroundMirror = true;
  111835. // to prevent undefines
  111836. if (typeof groundConfig_1.mirror === "object") {
  111837. if (groundConfig_1.mirror.amount !== undefined)
  111838. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  111839. if (groundConfig_1.mirror.sizeRatio !== undefined)
  111840. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  111841. if (groundConfig_1.mirror.blurKernel !== undefined)
  111842. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  111843. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  111844. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  111845. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  111846. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  111847. if (this._defaultPipelineTextureType !== undefined)
  111848. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  111849. }
  111850. }
  111851. }
  111852. var postInitSkyboxMaterial = false;
  111853. if (skyboxConifguration) {
  111854. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  111855. if (conf.material && conf.material.imageProcessingConfiguration) {
  111856. options.setupImageProcessing = false; // will be configured later manually.
  111857. }
  111858. var skyboxSize = conf.scale;
  111859. if (skyboxSize) {
  111860. options.skyboxSize = skyboxSize;
  111861. }
  111862. options.sizeAuto = !options.skyboxSize;
  111863. if (conf.color) {
  111864. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  111865. }
  111866. if (conf.cubeTexture && conf.cubeTexture.url) {
  111867. if (typeof conf.cubeTexture.url === "string") {
  111868. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  111869. }
  111870. else {
  111871. // init later!
  111872. postInitSkyboxMaterial = true;
  111873. }
  111874. }
  111875. if (conf.material) {
  111876. postInitSkyboxMaterial = true;
  111877. }
  111878. }
  111879. options.setupImageProcessing = false; // TMP
  111880. if (!this.environmentHelper) {
  111881. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  111882. }
  111883. else {
  111884. // unlikely, but there might be a new scene! we need to dispose.
  111885. // get the scene used by the envHelper
  111886. var scene = this.environmentHelper.rootMesh.getScene();
  111887. // is it a different scene? Oh no!
  111888. if (scene !== this.scene) {
  111889. this.environmentHelper.dispose();
  111890. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  111891. }
  111892. else {
  111893. // recreate the ground
  111894. if (this.environmentHelper.ground) {
  111895. this.environmentHelper.ground.dispose();
  111896. }
  111897. // recreate the skybox
  111898. if (this.environmentHelper.skybox) {
  111899. this.environmentHelper.skybox.dispose();
  111900. }
  111901. this.environmentHelper.updateOptions(options);
  111902. // update doesn't change the size of the skybox and ground, so we have to recreate!
  111903. //this.environmentHelper.dispose();
  111904. //this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  111905. }
  111906. }
  111907. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  111908. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  111909. }
  111910. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  111911. if (this.environmentHelper.groundMaterial && groundConfig) {
  111912. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  111913. if (groundConfig.material) {
  111914. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  111915. }
  111916. if (this.environmentHelper.groundMirror) {
  111917. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  111918. // TODO user camera exposure value to set the mirror clear color
  111919. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  111920. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  111921. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  111922. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  111923. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  111924. this.environmentHelper.groundMirror.clearColor.a = 1;
  111925. if (!this.groundMirrorEnabled) {
  111926. this.environmentHelper.groundMaterial.reflectionTexture = null;
  111927. }
  111928. }
  111929. }
  111930. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  111931. if (skyboxMaterial) {
  111932. skyboxMaterial._perceptualColor = this.mainColor;
  111933. if (postInitSkyboxMaterial) {
  111934. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  111935. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  111936. }
  111937. }
  111938. }
  111939. }
  111940. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  111941. _this._updateGroundMirrorRenderList(model);
  111942. });
  111943. this.onEnvironmentConfiguredObservable.notifyObservers({
  111944. sceneManager: this,
  111945. object: this.environmentHelper,
  111946. newConfiguration: {
  111947. skybox: skyboxConifguration,
  111948. ground: groundConfiguration
  111949. }
  111950. });
  111951. };
  111952. /**
  111953. * configure the lights.
  111954. *
  111955. * @param lightsConfiguration the (new) light(s) configuration
  111956. * @param model optionally use the model to configure the camera.
  111957. */
  111958. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  111959. var _this = this;
  111960. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  111961. // sanity check!
  111962. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  111963. if (!lightKeys.length) {
  111964. if (!this.scene.lights.length)
  111965. this.scene.createDefaultLight(true);
  111966. }
  111967. else {
  111968. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  111969. // compare to the global (!) configuration object and dispose unneeded:
  111970. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  111971. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  111972. lightsAvailable_1.forEach(function (lName) {
  111973. if (lightsToConfigure_1.indexOf(lName) === -1) {
  111974. _this.scene.getLightByName(lName).dispose();
  111975. }
  111976. });
  111977. }
  111978. lightKeys.forEach(function (name, idx) {
  111979. var lightConfig = { type: 0 };
  111980. if (typeof lightsConfiguration[name] === 'object') {
  111981. lightConfig = lightsConfiguration[name];
  111982. }
  111983. if (typeof lightsConfiguration[name] === 'number') {
  111984. lightConfig.type = lightsConfiguration[name];
  111985. }
  111986. lightConfig.name = name;
  111987. var light;
  111988. // light is not already available
  111989. if (lightsAvailable_1.indexOf(name) === -1) {
  111990. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  111991. if (!constructor)
  111992. return;
  111993. light = constructor();
  111994. }
  111995. else {
  111996. // available? get it from the scene
  111997. light = _this.scene.getLightByName(name);
  111998. if (typeof lightsConfiguration[name] === 'boolean') {
  111999. lightConfig.type = light.getTypeID();
  112000. }
  112001. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  112002. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  112003. light.dispose();
  112004. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  112005. if (!constructor)
  112006. return;
  112007. light = constructor();
  112008. }
  112009. }
  112010. // if config set the light to false, dispose it.
  112011. if (lightsConfiguration[name] === false) {
  112012. light.dispose();
  112013. return;
  112014. }
  112015. //enabled
  112016. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  112017. light.setEnabled(enabled);
  112018. helper_1.extendClassWithConfig(light, lightConfig);
  112019. //position. Some lights don't support shadows
  112020. if (light instanceof babylonjs_1.ShadowLight) {
  112021. // set default values
  112022. light.shadowMinZ = light.shadowMinZ || 0.2;
  112023. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  112024. if (lightConfig.target) {
  112025. if (light.setDirectionToTarget) {
  112026. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  112027. light.setDirectionToTarget(target);
  112028. }
  112029. }
  112030. else if (lightConfig.direction) {
  112031. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  112032. light.direction = direction;
  112033. }
  112034. var isShadowEnabled = false;
  112035. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  112036. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  112037. isShadowEnabled = true;
  112038. }
  112039. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  112040. var spotLight = light;
  112041. if (lightConfig.spotAngle !== undefined) {
  112042. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  112043. }
  112044. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  112045. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  112046. }
  112047. isShadowEnabled = true;
  112048. }
  112049. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  112050. if (lightConfig.shadowFieldOfView) {
  112051. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  112052. }
  112053. isShadowEnabled = true;
  112054. }
  112055. var shadowGenerator_1 = light.getShadowGenerator();
  112056. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  112057. var bufferSize = lightConfig.shadowBufferSize || 256;
  112058. if (!shadowGenerator_1) {
  112059. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  112060. }
  112061. var blurKernel = _this.getBlurKernel(light, bufferSize);
  112062. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  112063. shadowGenerator_1.blurKernel = blurKernel;
  112064. //override defaults
  112065. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  112066. // add the focues meshes to the shadow list
  112067. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  112068. _this._updateShadowRenderList(shadowGenerator_1, model);
  112069. });
  112070. //if (model) {
  112071. _this._updateShadowRenderList(shadowGenerator_1);
  112072. //}
  112073. }
  112074. else if (shadowGenerator_1) {
  112075. shadowGenerator_1.dispose();
  112076. }
  112077. }
  112078. });
  112079. // render priority
  112080. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  112081. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  112082. var configuration = globalLightsConfiguration_1[name];
  112083. var light = _this.scene.getLightByName(name);
  112084. // sanity check
  112085. if (!light)
  112086. return;
  112087. light.renderPriority = -idx;
  112088. });
  112089. }
  112090. this.onLightsConfiguredObservable.notifyObservers({
  112091. sceneManager: this,
  112092. object: this.scene.lights,
  112093. newConfiguration: lightsConfiguration
  112094. });
  112095. };
  112096. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  112097. var focusMeshes = model ? model.meshes : this.scene.meshes;
  112098. // add the focues meshes to the shadow list
  112099. var shadownMap = shadowGenerator.getShadowMap();
  112100. if (!shadownMap)
  112101. return;
  112102. if (resetList && shadownMap.renderList) {
  112103. shadownMap.renderList.length = 0;
  112104. }
  112105. else {
  112106. shadownMap.renderList = shadownMap.renderList || [];
  112107. }
  112108. for (var index = 0; index < focusMeshes.length; index++) {
  112109. var mesh = focusMeshes[index];
  112110. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  112111. shadownMap.renderList.push(mesh);
  112112. }
  112113. }
  112114. if (!this._shadowGroundPlane) {
  112115. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  112116. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  112117. shadowGroundPlane.useVertexColors = false;
  112118. //material isn't ever used in rendering, just used to set back face culling
  112119. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  112120. shadowGroundPlane.material.backFaceCulling = false;
  112121. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  112122. shadowGroundPlane.freezeWorldMatrix();
  112123. this._shadowGroundPlane = shadowGroundPlane;
  112124. this.scene.removeMesh(shadowGroundPlane);
  112125. }
  112126. }
  112127. else {
  112128. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  112129. this._shadowGroundPlane.dispose();
  112130. this._shadowGroundPlane = null;
  112131. }
  112132. }
  112133. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  112134. shadownMap.renderList.push(this._shadowGroundPlane);
  112135. }
  112136. };
  112137. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  112138. if (this.environmentHelper && this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  112139. var focusMeshes = model ? model.meshes : this.scene.meshes;
  112140. var renderList = this.environmentHelper.groundMirror.renderList;
  112141. if (resetList) {
  112142. renderList.length = 0;
  112143. }
  112144. for (var index = 0; index < focusMeshes.length; index++) {
  112145. var mesh = focusMeshes[index];
  112146. if (renderList.indexOf(mesh) === -1) {
  112147. renderList.push(mesh);
  112148. }
  112149. }
  112150. }
  112151. };
  112152. /**
  112153. * Gets the shadow map blur kernel according to the light configuration.
  112154. * @param light The light used to generate the shadows
  112155. * @param bufferSize The size of the shadow map
  112156. * @return the kernel blur size
  112157. */
  112158. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  112159. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  112160. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  112161. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  112162. }
  112163. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  112164. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  112165. }
  112166. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  112167. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  112168. }
  112169. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  112170. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  112171. return blurKernel;
  112172. };
  112173. /**
  112174. * Alters render settings to reduce features based on hardware feature limitations
  112175. * @param enableHDR Allows the viewer to run in HDR mode.
  112176. */
  112177. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  112178. if (enableHDR === void 0) { enableHDR = true; }
  112179. //flip rendering settings switches based on hardware support
  112180. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  112181. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  112182. //shadows are disabled if there's not enough varyings for a single shadow
  112183. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  112184. this._maxShadows = 0;
  112185. }
  112186. else {
  112187. this._maxShadows = 3;
  112188. }
  112189. //can we render to any >= 16-bit targets (required for HDR)
  112190. var caps = this._engine.getCaps();
  112191. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  112192. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  112193. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  112194. if (linearHalfFloatTargets) {
  112195. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  112196. this._shadowGeneratorBias = 0.002;
  112197. }
  112198. else if (linearFloatTargets) {
  112199. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  112200. this._shadowGeneratorBias = 0.001;
  112201. }
  112202. else {
  112203. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  112204. this._shadowGeneratorBias = 0.001;
  112205. }
  112206. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  112207. };
  112208. /**
  112209. * Dispoe the entire viewer including the scene and the engine
  112210. */
  112211. SceneManager.prototype.dispose = function () {
  112212. // this.onCameraConfiguredObservable.clear();
  112213. this.onEnvironmentConfiguredObservable.clear();
  112214. this.onLightsConfiguredObservable.clear();
  112215. this.onModelsConfiguredObservable.clear();
  112216. this.onSceneConfiguredObservable.clear();
  112217. this.onSceneInitObservable.clear();
  112218. this.onSceneOptimizerConfiguredObservable.clear();
  112219. if (this.sceneOptimizer) {
  112220. this.sceneOptimizer.stop();
  112221. this.sceneOptimizer.dispose();
  112222. }
  112223. if (this.environmentHelper) {
  112224. this.environmentHelper.dispose();
  112225. }
  112226. this.models.forEach(function (model) {
  112227. model.dispose();
  112228. });
  112229. if (this._defaultRenderingPipeline) {
  112230. this._defaultRenderingPipeline.dispose();
  112231. }
  112232. this.models.length = 0;
  112233. if (this.scene) {
  112234. this.scene.dispose();
  112235. }
  112236. };
  112237. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  112238. var behavior;
  112239. var type;
  112240. if (typeof behaviorConfig === 'object') {
  112241. type = behaviorConfig.type;
  112242. }
  112243. else if (typeof behaviorConfig === 'number') {
  112244. type = behaviorConfig;
  112245. }
  112246. else {
  112247. type = this._cameraBehaviorMapping[name];
  112248. }
  112249. if (type === undefined)
  112250. return;
  112251. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  112252. var enabled = true;
  112253. if (typeof behaviorConfig === 'boolean') {
  112254. enabled = behaviorConfig;
  112255. }
  112256. // constructing behavior
  112257. switch (type) {
  112258. case 0 /* AUTOROTATION */:
  112259. this.camera.useAutoRotationBehavior = enabled;
  112260. behavior = this.camera.autoRotationBehavior;
  112261. break;
  112262. case 1 /* BOUNCING */:
  112263. this.camera.useBouncingBehavior = enabled;
  112264. behavior = this.camera.bouncingBehavior;
  112265. break;
  112266. case 2 /* FRAMING */:
  112267. this.camera.useFramingBehavior = enabled;
  112268. behavior = this.camera.framingBehavior;
  112269. break;
  112270. default:
  112271. behavior = null;
  112272. break;
  112273. }
  112274. if (behavior) {
  112275. this._cameraBehaviorMapping[name] = type;
  112276. if (typeof behaviorConfig === "object") {
  112277. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  112278. }
  112279. }
  112280. // post attach configuration. Some functionalities require the attached camera.
  112281. switch (type) {
  112282. case 0 /* AUTOROTATION */:
  112283. break;
  112284. case 1 /* BOUNCING */:
  112285. break;
  112286. case 2 /* FRAMING */:
  112287. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  112288. if (config.zoomOnBoundingInfo) {
  112289. behavior.zoomOnMeshHierarchy(model.rootMesh);
  112290. }
  112291. });
  112292. break;
  112293. }
  112294. };
  112295. return SceneManager;
  112296. }());
  112297. exports.SceneManager = SceneManager;
  112298. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hc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7WUFDVixJQUFJLENBQUMsc0JBQXNCLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSxDQUFDO1lBRXpDLElBQUksT0FBTyxjQUFjLEtBQUssUUFBUSxFQUFFO2dCQUNwQyw4QkFBcUIsQ0FBQyxRQUFRLEVBQUUsY0FBYyxDQUFDLENBQUM7YUFDbkQ7U0FDSjtRQUVELCtFQUErRTtRQUMvRSxRQUFRLElBQUksRUFBRTtZQUNWO2dCQUNJLE1BQU07WUFDVjtnQkFDSSxNQUFNO1lBQ1Y7Z0JBQ0ksSUFBSSxDQUFDLG1CQUFtQixJQUFJLElBQUksQ0FBQyxtQkFBbUIsQ0FBQyx1QkFBdUIsQ0FBQyxHQUFHLENBQUMsVUFBQyxLQUFLO29CQUNuRixJQUFJLE1BQU0sQ0FBQyxrQkFBa0IsRUFBRTt3QkFDVCxRQUFTLENBQUMsbUJBQW1CLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxDQUFDO3FCQUNuRTtnQkFDTCxDQUFDLENBQUMsQ0FBQztnQkFDSCxNQUFNO1NBQ2I7SUFDTCxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBejNDRCxJQXkzQ0M7QUF6M0NZLG9DQUFZIn0=
  112299. /***/ }),
  112300. /* 23 */
  112301. /***/ (function(module, exports, __webpack_require__) {
  112302. "use strict";
  112303. Object.defineProperty(exports, "__esModule", { value: true });
  112304. /**
  112305. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  112306. * native GroupAnimation class.
  112307. */
  112308. var GroupModelAnimation = /** @class */ (function () {
  112309. /**
  112310. * Create a new GroupModelAnimation object using an AnimationGroup object
  112311. * @param _animationGroup The aniamtion group to base the class on
  112312. */
  112313. function GroupModelAnimation(_animationGroup) {
  112314. var _this = this;
  112315. this._animationGroup = _animationGroup;
  112316. this._state = 0 /* INIT */;
  112317. this._playMode = 1 /* LOOP */;
  112318. this._animationGroup.onAnimationEndObservable.add(function () {
  112319. _this.stop();
  112320. _this._state = 4 /* ENDED */;
  112321. });
  112322. }
  112323. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  112324. /**
  112325. * Get the animation's name
  112326. */
  112327. get: function () {
  112328. return this._animationGroup.name;
  112329. },
  112330. enumerable: true,
  112331. configurable: true
  112332. });
  112333. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  112334. /**
  112335. * Get the current animation's state
  112336. */
  112337. get: function () {
  112338. return this._state;
  112339. },
  112340. enumerable: true,
  112341. configurable: true
  112342. });
  112343. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  112344. /**
  112345. * Gets the speed ratio to use for all animations
  112346. */
  112347. get: function () {
  112348. return this._animationGroup.speedRatio;
  112349. },
  112350. /**
  112351. * Sets the speed ratio to use for all animations
  112352. */
  112353. set: function (value) {
  112354. this._animationGroup.speedRatio = value;
  112355. },
  112356. enumerable: true,
  112357. configurable: true
  112358. });
  112359. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  112360. /**
  112361. * Get the max numbers of frame available in the animation group
  112362. *
  112363. * In correlation to an arry, this would be ".length"
  112364. */
  112365. get: function () {
  112366. return this._animationGroup.to - this._animationGroup.from;
  112367. },
  112368. enumerable: true,
  112369. configurable: true
  112370. });
  112371. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  112372. /**
  112373. * Get the current frame playing right now.
  112374. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  112375. *
  112376. * In correlation to an array, this would be the current index
  112377. */
  112378. get: function () {
  112379. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  112380. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  112381. }
  112382. else {
  112383. return 0;
  112384. }
  112385. },
  112386. enumerable: true,
  112387. configurable: true
  112388. });
  112389. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  112390. /**
  112391. * Get the FPS value of this animation
  112392. */
  112393. get: function () {
  112394. // get the first currentFrame found
  112395. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  112396. var animatable = this._animationGroup.animatables[i];
  112397. var animations = animatable.getAnimations();
  112398. if (!animations || !animations.length) {
  112399. continue;
  112400. }
  112401. for (var idx = 0; idx < animations.length; ++idx) {
  112402. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  112403. return animations[idx].animation.framePerSecond;
  112404. }
  112405. }
  112406. }
  112407. return 0;
  112408. },
  112409. enumerable: true,
  112410. configurable: true
  112411. });
  112412. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  112413. /**
  112414. * What is the animation'S play mode (looping or played once)
  112415. */
  112416. get: function () {
  112417. return this._playMode;
  112418. },
  112419. /**
  112420. * Set the play mode.
  112421. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  112422. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  112423. */
  112424. set: function (value) {
  112425. if (value === this._playMode) {
  112426. return;
  112427. }
  112428. this._playMode = value;
  112429. if (this.state === 1 /* PLAYING */) {
  112430. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  112431. }
  112432. else {
  112433. this._animationGroup.reset();
  112434. this._state = 0 /* INIT */;
  112435. }
  112436. },
  112437. enumerable: true,
  112438. configurable: true
  112439. });
  112440. /**
  112441. * Reset the animation group
  112442. */
  112443. GroupModelAnimation.prototype.reset = function () {
  112444. this._animationGroup.reset();
  112445. };
  112446. /**
  112447. * Restart the animation group
  112448. */
  112449. GroupModelAnimation.prototype.restart = function () {
  112450. if (this.state === 2 /* PAUSED */)
  112451. this._animationGroup.restart();
  112452. else
  112453. this.start();
  112454. };
  112455. /**
  112456. *
  112457. * @param frameNumber Go to a specific frame in the animation
  112458. */
  112459. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  112460. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  112461. };
  112462. /**
  112463. * Start playing the animation.
  112464. */
  112465. GroupModelAnimation.prototype.start = function () {
  112466. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  112467. if (this._animationGroup.isStarted) {
  112468. this._state = 1 /* PLAYING */;
  112469. }
  112470. };
  112471. /**
  112472. * Pause the animation
  112473. */
  112474. GroupModelAnimation.prototype.pause = function () {
  112475. this._animationGroup.pause();
  112476. this._state = 2 /* PAUSED */;
  112477. };
  112478. /**
  112479. * Stop the animation.
  112480. * This will fail silently if the animation group is already stopped.
  112481. */
  112482. GroupModelAnimation.prototype.stop = function () {
  112483. this._animationGroup.stop();
  112484. if (!this._animationGroup.isStarted) {
  112485. this._state = 3 /* STOPPED */;
  112486. }
  112487. };
  112488. /**
  112489. * Dispose this animation object.
  112490. */
  112491. GroupModelAnimation.prototype.dispose = function () {
  112492. this._animationGroup.dispose();
  112493. };
  112494. return GroupModelAnimation;
  112495. }());
  112496. exports.GroupModelAnimation = GroupModelAnimation;
  112497. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixDQUFDLEdBQUcsQ0FBQztZQUM5QyxLQUFJLENBQUMsSUFBSSxFQUFFLENBQUM7WUFDWixLQUFJLENBQUMsTUFBTSxnQkFBdUIsQ0FBQztRQUN2QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7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UFJLElBQUksQ0FBQyxlQUFlLENBQUMsU0FBUyxFQUFFO1lBQ2hDLElBQUksQ0FBQyxNQUFNLGtCQUF5QixDQUFDO1NBQ3hDO0lBQ0wsQ0FBQztJQUVEOztPQUVHO0lBQ0gsbUNBQUssR0FBTDtRQUNJLElBQUksQ0FBQyxlQUFlLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDN0IsSUFBSSxDQUFDLE1BQU0saUJBQXdCLENBQUM7SUFDeEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGtDQUFJLEdBQVg7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  112498. /***/ }),
  112499. /* 24 */
  112500. /***/ (function(module, exports, __webpack_require__) {
  112501. "use strict";
  112502. Object.defineProperty(exports, "__esModule", { value: true });
  112503. var environmentSerializer_1 = __webpack_require__(25);
  112504. var babylonjs_1 = __webpack_require__(0);
  112505. var texture_1 = __webpack_require__(12);
  112506. /**
  112507. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  112508. * The APIs in all labs-related classes and configuration might change.
  112509. * Once stable, lab features will be moved to the publis API and configuration object.
  112510. */
  112511. var ViewerLabs = /** @class */ (function () {
  112512. function ViewerLabs(_scene) {
  112513. this._scene = _scene;
  112514. this.environment = {
  112515. //irradiance
  112516. irradiancePolynomialCoefficients: {
  112517. x: new babylonjs_1.Vector3(0, 0, 0),
  112518. y: new babylonjs_1.Vector3(0, 0, 0),
  112519. z: new babylonjs_1.Vector3(0, 0, 0),
  112520. xx: new babylonjs_1.Vector3(0, 0, 0),
  112521. yy: new babylonjs_1.Vector3(0, 0, 0),
  112522. zz: new babylonjs_1.Vector3(0, 0, 0),
  112523. yz: new babylonjs_1.Vector3(0, 0, 0),
  112524. zx: new babylonjs_1.Vector3(0, 0, 0),
  112525. xy: new babylonjs_1.Vector3(0, 0, 0)
  112526. },
  112527. textureIntensityScale: 1.0
  112528. };
  112529. }
  112530. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  112531. var _this = this;
  112532. //@! todo: should loadEnvironment cancel any currently loading environments?
  112533. if (data instanceof ArrayBuffer) {
  112534. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  112535. if (onSuccess)
  112536. onSuccess(this.environment);
  112537. }
  112538. else if (typeof data === 'string') {
  112539. var url = this.getAssetUrl(data);
  112540. this._scene._loadFile(url, function (arrayBuffer) {
  112541. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  112542. if (onSuccess)
  112543. onSuccess(_this.environment);
  112544. }, function (progressEvent) { if (onProgress)
  112545. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  112546. if (onError) {
  112547. onError(e);
  112548. }
  112549. });
  112550. }
  112551. else {
  112552. //data assumed to be PBREnvironment object
  112553. this.environment = data;
  112554. if (onSuccess)
  112555. onSuccess(data);
  112556. }
  112557. };
  112558. /**
  112559. * Applies an `EnvironmentMapConfiguration` to the scene
  112560. * @param environmentMapConfiguration Environment map configuration to apply
  112561. */
  112562. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  112563. if (!this.environment)
  112564. return;
  112565. //set orientation
  112566. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  112567. // Add env texture to the scene.
  112568. if (this.environment.specularTexture) {
  112569. // IE crashes when disposing the old texture and setting a new one
  112570. if (!this._scene.environmentTexture) {
  112571. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  112572. }
  112573. if (this._scene.environmentTexture) {
  112574. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  112575. this._scene.environmentTexture.invertZ = true;
  112576. this._scene.environmentTexture.lodLevelInAlpha = true;
  112577. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  112578. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  112579. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  112580. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  112581. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  112582. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  112583. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  112584. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  112585. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  112586. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  112587. this._scene.environmentTexture.sphericalPolynomial = poly;
  112588. //set orientation
  112589. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  112590. }
  112591. }
  112592. };
  112593. /**
  112594. * Get an environment asset url by using the configuration if the path is not absolute.
  112595. * @param url Asset url
  112596. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  112597. */
  112598. ViewerLabs.prototype.getAssetUrl = function (url) {
  112599. var returnUrl = url;
  112600. if (url && url.toLowerCase().indexOf("//") === -1) {
  112601. if (!this.assetsRootURL) {
  112602. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  112603. return url;
  112604. }
  112605. returnUrl = this.assetsRootURL + returnUrl;
  112606. }
  112607. return returnUrl;
  112608. };
  112609. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  112610. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  112611. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  112612. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  112613. axis.normalize();
  112614. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  112615. 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]);
  112616. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  112617. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  112618. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  112619. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  112620. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  112621. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  112622. shadowLight.setDirectionToTarget(target);
  112623. };
  112624. return ViewerLabs;
  112625. }());
  112626. exports.ViewerLabs = ViewerLabs;
  112627. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtR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QUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  112628. /***/ }),
  112629. /* 25 */
  112630. /***/ (function(module, exports, __webpack_require__) {
  112631. "use strict";
  112632. Object.defineProperty(exports, "__esModule", { value: true });
  112633. var babylonjs_1 = __webpack_require__(0);
  112634. var texture_1 = __webpack_require__(12);
  112635. /**
  112636. * A static class proving methods to aid parsing Spectre environment files
  112637. */
  112638. var EnvironmentDeserializer = /** @class */ (function () {
  112639. function EnvironmentDeserializer() {
  112640. }
  112641. /**
  112642. * Parses an arraybuffer into a new PBREnvironment object
  112643. * @param arrayBuffer The arraybuffer of the Spectre environment file
  112644. * @return a PBREnvironment object
  112645. */
  112646. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  112647. var environment = {
  112648. //irradiance
  112649. irradiancePolynomialCoefficients: {
  112650. x: new babylonjs_1.Vector3(0, 0, 0),
  112651. y: new babylonjs_1.Vector3(0, 0, 0),
  112652. z: new babylonjs_1.Vector3(0, 0, 0),
  112653. xx: new babylonjs_1.Vector3(0, 0, 0),
  112654. yy: new babylonjs_1.Vector3(0, 0, 0),
  112655. zz: new babylonjs_1.Vector3(0, 0, 0),
  112656. yz: new babylonjs_1.Vector3(0, 0, 0),
  112657. zx: new babylonjs_1.Vector3(0, 0, 0),
  112658. xy: new babylonjs_1.Vector3(0, 0, 0)
  112659. },
  112660. //specular
  112661. textureIntensityScale: 1.0,
  112662. };
  112663. //read .env
  112664. var littleEndian = false;
  112665. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  112666. var dataView = new DataView(arrayBuffer);
  112667. var pos = 0;
  112668. for (var i = 0; i < magicBytes.length; i++) {
  112669. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  112670. babylonjs_1.Tools.Error('Not a Spectre environment map');
  112671. }
  112672. }
  112673. var version = dataView.getUint16(pos, littleEndian);
  112674. pos += 2;
  112675. if (version !== 1) {
  112676. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  112677. }
  112678. //read json descriptor - collect characters up to null terminator
  112679. var descriptorString = '';
  112680. var charCode = 0x00;
  112681. while ((charCode = dataView.getUint8(pos++))) {
  112682. descriptorString += String.fromCharCode(charCode);
  112683. }
  112684. var descriptor = JSON.parse(descriptorString);
  112685. var payloadPos = pos;
  112686. //irradiance
  112687. switch (descriptor.irradiance.type) {
  112688. case 'irradiance_sh_coefficients_9':
  112689. //irradiance
  112690. var harmonics = descriptor.irradiance;
  112691. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  112692. //harmonics now represent radiance
  112693. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  112694. break;
  112695. default:
  112696. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  112697. }
  112698. //specular
  112699. switch (descriptor.specular.type) {
  112700. case 'cubemap_faces':
  112701. var specularDescriptor = descriptor.specular;
  112702. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  112703. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  112704. var mipmaps = specularDescriptor.mipmaps;
  112705. var imageType = specularDescriptor.imageType;
  112706. for (var l = 0; l < mipmaps.length; l++) {
  112707. var faceRanges = mipmaps[l];
  112708. specularTexture.source[l] = [];
  112709. for (var i = 0; i < 6; i++) {
  112710. var range = faceRanges[i];
  112711. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  112712. switch (imageType) {
  112713. case 'png':
  112714. //construct image element from bytes
  112715. var image = new Image();
  112716. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  112717. image.src = src;
  112718. specularTexture.source[l][i] = image;
  112719. break;
  112720. default:
  112721. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  112722. }
  112723. }
  112724. }
  112725. break;
  112726. default:
  112727. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  112728. }
  112729. return environment;
  112730. };
  112731. /**
  112732. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  112733. * L = (1/pi) * E * rho
  112734. *
  112735. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  112736. * @param harmonics Spherical harmonic coefficients (9)
  112737. */
  112738. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  112739. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  112740. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  112741. // (The pixel shader must apply albedo after texture fetches, etc).
  112742. };
  112743. /**
  112744. * Convert spherical harmonics to spherical polynomial coefficients
  112745. * @param harmonics Spherical harmonic coefficients (9)
  112746. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  112747. */
  112748. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  112749. var rPi = 1 / Math.PI;
  112750. //x
  112751. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  112752. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  112753. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  112754. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  112755. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  112756. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  112757. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  112758. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  112759. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  112760. //xx
  112761. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  112762. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  112763. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  112764. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  112765. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  112766. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  112767. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  112768. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  112769. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  112770. //yz
  112771. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  112772. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  112773. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  112774. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  112775. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  112776. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  112777. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  112778. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  112779. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  112780. };
  112781. /**
  112782. * Multiplies harmonic coefficients in place
  112783. * @param harmonics Spherical harmonic coefficients (9)
  112784. * @param scaleFactor Value to multiply by
  112785. */
  112786. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  112787. harmonics.l00[0] *= scaleFactor;
  112788. harmonics.l00[1] *= scaleFactor;
  112789. harmonics.l00[2] *= scaleFactor;
  112790. harmonics.l1_1[0] *= scaleFactor;
  112791. harmonics.l1_1[1] *= scaleFactor;
  112792. harmonics.l1_1[2] *= scaleFactor;
  112793. harmonics.l10[0] *= scaleFactor;
  112794. harmonics.l10[1] *= scaleFactor;
  112795. harmonics.l10[2] *= scaleFactor;
  112796. harmonics.l11[0] *= scaleFactor;
  112797. harmonics.l11[1] *= scaleFactor;
  112798. harmonics.l11[2] *= scaleFactor;
  112799. harmonics.l2_2[0] *= scaleFactor;
  112800. harmonics.l2_2[1] *= scaleFactor;
  112801. harmonics.l2_2[2] *= scaleFactor;
  112802. harmonics.l2_1[0] *= scaleFactor;
  112803. harmonics.l2_1[1] *= scaleFactor;
  112804. harmonics.l2_1[2] *= scaleFactor;
  112805. harmonics.l20[0] *= scaleFactor;
  112806. harmonics.l20[1] *= scaleFactor;
  112807. harmonics.l20[2] *= scaleFactor;
  112808. harmonics.l21[0] *= scaleFactor;
  112809. harmonics.l21[1] *= scaleFactor;
  112810. harmonics.l21[2] *= scaleFactor;
  112811. harmonics.l22[0] *= scaleFactor;
  112812. harmonics.l22[1] *= scaleFactor;
  112813. harmonics.l22[2] *= scaleFactor;
  112814. };
  112815. return EnvironmentDeserializer;
  112816. }());
  112817. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  112818. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4v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* 26 */
  112821. /***/ (function(module, exports, __webpack_require__) {
  112822. "use strict";
  112823. Object.defineProperty(exports, "__esModule", { value: true });
  112824. var extended_1 = __webpack_require__(27);
  112825. var cache = {};
  112826. /**
  112827. *
  112828. * @param name the name of the custom optimizer configuration
  112829. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  112830. */
  112831. function getCustomOptimizerByName(name, upgrade) {
  112832. if (!cache[name]) {
  112833. switch (name) {
  112834. case 'extended':
  112835. if (upgrade) {
  112836. return extended_1.extendedUpgrade;
  112837. }
  112838. else {
  112839. return extended_1.extendedDegrade;
  112840. }
  112841. }
  112842. }
  112843. return cache[name];
  112844. }
  112845. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  112846. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0=
  112847. /***/ }),
  112848. /* 27 */
  112849. /***/ (function(module, exports, __webpack_require__) {
  112850. "use strict";
  112851. Object.defineProperty(exports, "__esModule", { value: true });
  112852. var babylonjs_1 = __webpack_require__(0);
  112853. /**
  112854. * A custom upgrade-oriented function configuration for the scene optimizer.
  112855. *
  112856. * @param viewer the viewer to optimize
  112857. */
  112858. function extendedUpgrade(sceneManager) {
  112859. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  112860. // if (!this.Scene.BackgroundHelper) {
  112861. // this.Scene.EngineScene.autoClear = false;
  112862. // this.Scene.BackgroundHelper = true;
  112863. // Would require a dedicated clear color;
  112864. // return false;
  112865. // }
  112866. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  112867. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  112868. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  112869. return false;
  112870. }
  112871. if (!sceneManager.scene.postProcessesEnabled) {
  112872. sceneManager.scene.postProcessesEnabled = true;
  112873. return false;
  112874. }
  112875. if (!sceneManager.groundEnabled) {
  112876. sceneManager.groundEnabled = true;
  112877. return false;
  112878. }
  112879. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  112880. sceneManager.fxaaEnabled = true;
  112881. return false;
  112882. }
  112883. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  112884. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  112885. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  112886. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  112887. return false;
  112888. }
  112889. if (!sceneManager.processShadows) {
  112890. sceneManager.processShadows = true;
  112891. return false;
  112892. }
  112893. if (defaultPipeline && !sceneManager.bloomEnabled) {
  112894. sceneManager.bloomEnabled = true;
  112895. return false;
  112896. }
  112897. if (!sceneManager.groundMirrorEnabled) {
  112898. sceneManager.groundMirrorEnabled = true;
  112899. return false;
  112900. }
  112901. return true;
  112902. }
  112903. exports.extendedUpgrade = extendedUpgrade;
  112904. /**
  112905. * A custom degrade-oriented function configuration for the scene optimizer.
  112906. *
  112907. * @param viewer the viewer to optimize
  112908. */
  112909. function extendedDegrade(sceneManager) {
  112910. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  112911. if (sceneManager.groundMirrorEnabled) {
  112912. sceneManager.groundMirrorEnabled = false;
  112913. return false;
  112914. }
  112915. if (defaultPipeline && sceneManager.bloomEnabled) {
  112916. sceneManager.bloomEnabled = false;
  112917. return false;
  112918. }
  112919. if (sceneManager.processShadows) {
  112920. sceneManager.processShadows = false;
  112921. return false;
  112922. }
  112923. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  112924. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  112925. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  112926. return false;
  112927. }
  112928. if (defaultPipeline && sceneManager.fxaaEnabled) {
  112929. sceneManager.fxaaEnabled = false;
  112930. return false;
  112931. }
  112932. if (sceneManager.groundEnabled) {
  112933. sceneManager.groundEnabled = false;
  112934. return false;
  112935. }
  112936. if (sceneManager.scene.postProcessesEnabled) {
  112937. sceneManager.scene.postProcessesEnabled = false;
  112938. return false;
  112939. }
  112940. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  112941. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  112942. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  112943. return false;
  112944. }
  112945. // if (this.Scene.BackgroundHelper) {
  112946. // this.Scene.EngineScene.autoClear = true;
  112947. // this.Scene.BackgroundHelper = false;
  112948. // Would require a dedicated clear color;
  112949. // return false;
  112950. // }
  112951. return true;
  112952. }
  112953. exports.extendedDegrade = extendedDegrade;
  112954. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJ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BQ0QsSUFBSSxlQUFlLElBQUksWUFBWSxDQUFDLFdBQVcsRUFBRTtRQUM3QyxZQUFZLENBQUMsV0FBVyxHQUFHLEtBQUssQ0FBQztRQUNqQyxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLGFBQWEsRUFBRTtRQUM1QixZQUFZLENBQUMsYUFBYSxHQUFHLEtBQUssQ0FBQztRQUNuQyxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxvQkFBb0IsRUFBRTtRQUN6QyxZQUFZLENBQUMsS0FBSyxDQUFDLG9CQUFvQixHQUFHLEtBQUssQ0FBQztRQUNoRCxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyx1QkFBdUIsRUFBRSxHQUFHLElBQUksRUFBRTtRQUNqRSxJQUFJLE9BQU8sR0FBRyxrQkFBTSxDQUFDLEtBQUssQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  112955. /***/ }),
  112956. /* 28 */
  112957. /***/ (function(module, exports, __webpack_require__) {
  112958. "use strict";
  112959. Object.defineProperty(exports, "__esModule", { value: true });
  112960. var mappers_1 = __webpack_require__(3);
  112961. var types_1 = __webpack_require__(29);
  112962. var configurationCompatibility_1 = __webpack_require__(53);
  112963. var _1 = __webpack_require__(1);
  112964. var babylonjs_1 = __webpack_require__(0);
  112965. /**
  112966. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  112967. * parse the object and return a conform ViewerConfiguration.
  112968. * It is a private member of the scene.
  112969. */
  112970. var ConfigurationLoader = /** @class */ (function () {
  112971. function ConfigurationLoader(_enableCache) {
  112972. if (_enableCache === void 0) { _enableCache = false; }
  112973. this._enableCache = _enableCache;
  112974. this._configurationCache = {};
  112975. this._loadRequests = [];
  112976. }
  112977. /**
  112978. * load a configuration object that is defined in the initial configuration provided.
  112979. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  112980. *
  112981. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  112982. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  112983. * @returns A promise that delivers the extended viewer configuration, when done.
  112984. */
  112985. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  112986. var _this = this;
  112987. if (initConfig === void 0) { initConfig = {}; }
  112988. var loadedConfig = _1.deepmerge({}, initConfig);
  112989. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  112990. if (loadedConfig.configuration) {
  112991. var mapperType_1 = "json";
  112992. return Promise.resolve().then(function () {
  112993. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  112994. // a file to load
  112995. var url = '';
  112996. if (typeof loadedConfig.configuration === "string") {
  112997. url = loadedConfig.configuration;
  112998. }
  112999. // if configuration is an object
  113000. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  113001. url = loadedConfig.configuration.url;
  113002. var type = loadedConfig.configuration.mapper;
  113003. // empty string?
  113004. if (!type) {
  113005. // load mapper type from filename / url
  113006. type = loadedConfig.configuration.url.split('.').pop();
  113007. }
  113008. mapperType_1 = type || mapperType_1;
  113009. }
  113010. return _this._loadFile(url);
  113011. }
  113012. else {
  113013. if (typeof loadedConfig.configuration === "object") {
  113014. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  113015. return loadedConfig.configuration.payload || {};
  113016. }
  113017. return {};
  113018. }
  113019. }).then(function (data) {
  113020. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  113021. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  113022. var merged = _1.deepmerge(extendedConfiguration, parsed);
  113023. configurationCompatibility_1.processConfigurationCompatibility(merged);
  113024. if (callback)
  113025. callback(merged);
  113026. return merged;
  113027. });
  113028. }
  113029. else {
  113030. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  113031. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  113032. if (callback)
  113033. callback(loadedConfig);
  113034. return Promise.resolve(loadedConfig);
  113035. }
  113036. };
  113037. /**
  113038. * Dispose the configuration loader. This will cancel file requests, if active.
  113039. */
  113040. ConfigurationLoader.prototype.dispose = function () {
  113041. this._loadRequests.forEach(function (request) {
  113042. request.abort();
  113043. });
  113044. this._loadRequests.length = 0;
  113045. };
  113046. ConfigurationLoader.prototype._loadFile = function (url) {
  113047. var _this = this;
  113048. var cacheReference = this._configurationCache;
  113049. if (this._enableCache && cacheReference[url]) {
  113050. return Promise.resolve(cacheReference[url]);
  113051. }
  113052. return new Promise(function (resolve, reject) {
  113053. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  113054. var idx = _this._loadRequests.indexOf(fileRequest);
  113055. if (idx !== -1)
  113056. _this._loadRequests.splice(idx, 1);
  113057. if (_this._enableCache)
  113058. cacheReference[url] = result;
  113059. resolve(result);
  113060. }, undefined, undefined, false, function (request, error) {
  113061. var idx = _this._loadRequests.indexOf(fileRequest);
  113062. if (idx !== -1)
  113063. _this._loadRequests.splice(idx, 1);
  113064. reject(error);
  113065. });
  113066. _this._loadRequests.push(fileRequest);
  113067. });
  113068. };
  113069. return ConfigurationLoader;
  113070. }());
  113071. exports.ConfigurationLoader = ConfigurationLoader;
  113072. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ3VyYXRpb24vbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQTBDO0FBRTFDLGlDQUErQztBQUMvQywyRUFBaUY7QUFFakYsK0JBQXVDO0FBQ3ZDLHVDQUFnRDtBQUVoRDs7OztHQUlHO0FBQ0g7SUFNSSw2QkFBb0IsWUFBNkI7UUFBN0IsNkJBQUEsRUFBQSxvQkFBNkI7UUFBN0IsaUJBQVksR0FBWixZQUFZLENBQWlCO1FBQzdDLElBQUksQ0FBQyxtQkFBbUIsR0FBRyxFQUFFLENBQUM7UUFDOUIsSUFBSSxDQUFDLGFBQWEsR0FBRyxFQUFFLENBQUM7SUFDNUIsQ0FBQztJQUVEOzs7Ozs7O09BT0c7SUFDSSwrQ0FBaUIsR0FBeEIsVUFBeUIsVUFBb0MsRUFBRSxRQUFnRDtRQUEvRyxpQkFvREM7UUFwRHdCLDJCQUFBLEVBQUEsZUFBb0M7UUFFekQsSUFBSSxZQUFZLEdBQXdCLFlBQVMsQ0FBQyxFQUFFLEVBQUUsVUFBVSxDQUFDLENBQUM7UUFFbEUsSUFBSSxxQkFBcUIsR0FBRyw0QkFBb0IsQ0FBQyxZQUFZLENBQUMsT0FBTyxJQUFJLEVBQUUsQ0FBQyxDQUFDO1FBRTdFLElBQUksWUFBWSxDQUFDLGFBQWEsRUFBRTtZQUU1QixJQUFJLFlBQVUsR0FBRyxNQUFNLENBQUM7WUFDeEIsT0FBTyxPQUFPLENBQUMsT0FBTyxFQUFFLENBQUMsSUFBSSxDQUFDO2dCQUMxQixJQUFJLE9BQU8sWUFBWSxDQUFDLGFBQWEsS0FB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Q0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLEdBQUcsRUFBRSxDQUFDLENBQUMsQ0FBQztnQkFDdEMsTUFBTSxDQUFDLEtBQUssQ0FBQyxDQUFDO1lBQ2xCLENBQUMsQ0FBQyxDQUFDO1lBQ0gsS0FBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUM7UUFDekMsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUwsMEJBQUM7QUFBRCxDQUFDLEFBMUdELElBMEdDO0FBMUdZLGtEQUFtQiJ9
  113073. /***/ }),
  113074. /* 29 */
  113075. /***/ (function(module, exports, __webpack_require__) {
  113076. "use strict";
  113077. Object.defineProperty(exports, "__esModule", { value: true });
  113078. var minimal_1 = __webpack_require__(30);
  113079. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  113080. var default_1 = __webpack_require__(49);
  113081. exports.defaultConfiguration = default_1.defaultConfiguration;
  113082. var extended_1 = __webpack_require__(50);
  113083. var shadowLight_1 = __webpack_require__(51);
  113084. var environmentMap_1 = __webpack_require__(52);
  113085. var _1 = __webpack_require__(1);
  113086. /**
  113087. * Get the configuration type you need to use as the base for your viewer.
  113088. * The types can either be a single string, or comma separated types that will extend each other. for example:
  113089. *
  113090. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  113091. *
  113092. * @param types a comma-separated string of the type(s) or configuration to load.
  113093. */
  113094. var getConfigurationType = function (types) {
  113095. var config = {};
  113096. var typesSeparated = types.split(",");
  113097. typesSeparated.forEach(function (type) {
  113098. switch (type.trim()) {
  113099. case 'environmentMap':
  113100. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  113101. break;
  113102. case 'shadowDirectionalLight':
  113103. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  113104. break;
  113105. case 'shadowSpotLight':
  113106. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  113107. break;
  113108. case 'extended':
  113109. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  113110. break;
  113111. case 'minimal':
  113112. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  113113. break;
  113114. case 'none':
  113115. break;
  113116. case 'default':
  113117. default:
  113118. config = _1.deepmerge(config, default_1.defaultConfiguration);
  113119. break;
  113120. }
  113121. if (config.extends) {
  113122. config = _1.deepmerge(config, getConfigurationType(config.extends));
  113123. }
  113124. });
  113125. return config;
  113126. };
  113127. exports.getConfigurationType = getConfigurationType;
  113128. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHFDQUFpRDtBQW9ESSwrQkFwRDVDLDhCQUFvQixDQW9ENEM7QUFuRHpFLHFDQUFpRDtBQW1EbEIsK0JBbkR0Qiw4QkFBb0IsQ0FtRHNCO0FBbERuRCx1Q0FBbUQ7QUFFbkQsNkNBQW1HO0FBQ25HLG1EQUErRDtBQUMvRCxrQ0FBMEM7QUFFMUM7Ozs7Ozs7R0FPRztBQUNILElBQUksb0JBQW9CLEdBQUcsVUFBVSxLQUFhO0lBQzlDLElBQUksTUFBTSxHQUF3QixFQUFFLENBQUM7SUFDckMsSUFBSSxjQUFjLEdBQUcsS0FBSyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN0QyxjQUFjLENBQUMsT0FBTyxDQUFDLFVBQUEsSUFBSTtRQUN2QixRQUFRLElBQUksQ0FBQyxJQUFJLEVBQUUsRUFBRTtZQUNqQixLQUFLLGdCQUFnQjtnQkFDakIsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsNENBQTJCLENBQUMsQ0FBQztnQkFDeEQsTUFBTTtZQUNWLEtBQUssd0JBQXdCO2dCQUN6QixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxpREFBbUMsQ0FBQyxDQUFDO2dCQUNoRSxNQUFNO1lBQ1YsS0FBSyxpQkFBaUI7Z0JBQ2xCLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDJDQUE2QixDQUFDLENBQUM7Z0JBQzFELE1BQU07WUFDVixLQUFLLFVBQVU7Z0JBQ1gsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsZ0NBQXFCLENBQUMsQ0FBQztnQkFDbEQsTUFBTTtZQUNWLEtBQUssU0FBUztnQkFDVixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSw4QkFBb0IsQ0FBQyxDQUFDO2dCQUNqRCxNQUFNO1lBQ1YsS0FBSyxNQUFNO2dCQUNQLE1BQU07WUFDVixLQUFLLFNBQVMsQ0FBQztZQUNmO2dCQUNJLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDhCQUFvQixDQUFDLENBQUM7Z0JBQ2pELE1BQU07U0FDYjtRQUVELElBQUksTUFBTSxDQUFDLE9BQU8sRUFBRTtZQUNoQixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxvQkFBb0IsQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztTQUNwRTtJQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTyxNQUFNLENBQUM7QUFFbEIsQ0FBQyxDQUFBO0FBRVEsb0RBQW9CIn0=
  113129. /***/ }),
  113130. /* 30 */
  113131. /***/ (function(module, exports, __webpack_require__) {
  113132. "use strict";
  113133. Object.defineProperty(exports, "__esModule", { value: true });
  113134. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  113135. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  113136. /**
  113137. * The minimal configuration needed to make the viewer work.
  113138. * Some functionalities might not work correctly (like fill-screen)
  113139. */
  113140. exports.minimalConfiguration = {
  113141. version: "0.1",
  113142. templates: {
  113143. main: {
  113144. html: babylonjs_viewer_assets_1.defaultTemplate
  113145. },
  113146. fillContainer: {
  113147. html: babylonjs_viewer_assets_1.fillContainer,
  113148. params: {
  113149. disable: false
  113150. }
  113151. },
  113152. loadingScreen: {
  113153. html: babylonjs_viewer_assets_1.loadingScreen,
  113154. params: {
  113155. backgroundColor: "#000000",
  113156. loadingImage: babylonjs_viewer_assets_2.loading
  113157. }
  113158. },
  113159. viewer: {
  113160. html: babylonjs_viewer_assets_1.defaultViewer,
  113161. },
  113162. overlay: {
  113163. html: babylonjs_viewer_assets_1.overlay,
  113164. params: {
  113165. closeImage: babylonjs_viewer_assets_2.close,
  113166. closeText: 'Close'
  113167. }
  113168. },
  113169. error: {
  113170. html: babylonjs_viewer_assets_1.error
  113171. }
  113172. },
  113173. engine: {
  113174. antialiasing: true
  113175. }
  113176. };
  113177. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  113178. /***/ }),
  113179. /* 31 */
  113180. /***/ (function(module, exports, __webpack_require__) {
  113181. "use strict";
  113182. Object.defineProperty(exports, "__esModule", { value: true });
  113183. exports.babylonFont = __webpack_require__(32);
  113184. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  113185. /***/ }),
  113186. /* 32 */
  113187. /***/ (function(module, exports) {
  113188. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABMwAA8AAAAAIYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp+FVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAAB7AAAAvq1MrYZjdnQgAAAEJAAAACAAAAAqCdkJr2ZwZ20AAAREAA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YS00SdTObl4YrCC1Q0Xh0bAoRQn0yNFMQcsztMM8OmTLAc0Ig1wTqT7ENWsL/gmd/dYw72gqWwGvhQfh3+EP4a/gbPz+Ev4XfsMeNsi11km2wb0B5TLAE9zSw8Y7Dl7AaxlbQKkChABYvhZgf4c9j3QTZhGdxZOknYJWg/gjUFzetgBxFSpAV5ucl2wSsyWNJFS7SbsAq0MNL7xGC9N4wxZpfZpSe4OqY+zz3i0bBysMaIBDyOok9BOiX+hyDDDPEmI91FuU/oXEH2nXYC+xTOWFNFmcb/oWpYIwfSq2wI/5r+MfA9aR97P0PADbFMiKcEhgakY2LDbIcLvVuKuYQqKeoBn1lg3x5QTpwq0cBeUe3aSrQV67RRpilrAxqYh2QDOKekV1KvGpK0M8ZBZuCutU08i/RnQdwldRZzdnSHViOKo+tEThmhVRdXa2GpC+YpyXiWw+BfdbWkcwo2CZwHVK92Xlu/g5mfJzNQNIs11SmBdXHNap8paieQTUVzly6sPdrkhM6B/nnYcUJHvi6L2NsY/m9t5+wpMU1AZmiOHXUumc3qogw670/Hda03A5hJm4sjf91bgPxtrilIaspc01v5rNkTh6ZKUl+0X9usWlzRm1WRJUbbdbPjQc2c3uR/ntH2q1b4zszZuzdE+Srj/GC8I6p029v5F1nQBHfnP+HU/1rLQ99k+iofugfv0avRZvR+9G70NqxXDjEVYH8H9B5R3Yo2yuD74JuQUTd3QNNAvJiN+BtTGIWpeNpjYGYAg/9+DOUMWAAAKSoByAB42tvAoM2wiZGTSZtxExeI3M7Vmhtqq8rAob2dOzXYQU8GxOKJ8LDQkASxeJ3NteWFQSw+HRUZER4Qi19OQpiPA8QS4OPhZGcBsQTBAMQS2jChIMAAyGLYzgg3mgluNDPcaBa40axwo9nkJKFGs8ON5oAbzQk3epMwI7v2BgYF19pMCRcAxAEoGgAAAA=="
  113189. /***/ }),
  113190. /* 33 */
  113191. /***/ (function(module, exports, __webpack_require__) {
  113192. "use strict";
  113193. Object.defineProperty(exports, "__esModule", { value: true });
  113194. exports.babylonLogo = __webpack_require__(34);
  113195. exports.close = __webpack_require__(35);
  113196. exports.fullscreen = __webpack_require__(36);
  113197. exports.helpCircle = __webpack_require__(37);
  113198. exports.loading = __webpack_require__(38);
  113199. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  113200. /***/ }),
  113201. /* 34 */
  113202. /***/ (function(module, exports) {
  113203. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAAmb5bkNMnSKAAAgD74HyMAAAAAmJwqJVyfJqmbP4+a/9m3JIskH40JAADo0m9OZgMAAACM2ukTr6MX/OtEbQAAoFNiNgAAAMB41FkH6yrJ2R7+d4raAABAJ8RsAAAAgOFZPd+6znpl+MmB/2+K2gAAQKvEbAAAAIB+q/LjmvDjDv//EbUBAIBWiNkAAAAA/bFaD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KBL6ySnYugtK2wAAAAAekuZDQBAlyYpS98TUfTGLskyyUWssAEAAADoMWU2AABdmyb5Joaj26ScEV8muRUHAAAAAH33SgQAAHRsneSTGI5il2SR5LeUHypoosgGAAAAYCAsswEAOJQmybkYDsIKGwAAAIDBU2YDAHAokySrJKei6MwipcReiwIAAACAoVNmAwBwSG9SitYTUbRmm1JgN7HCBgAAAKAiymwAAA7tLMlXMbzYIqXAXokCAAAAgBopswEAOIaPSf4Uw5NZYQMAAAAwGspsAACOpUlyLoZHuUopsVeiAAAAAGAslNkAABzLJKWcPRXFg7YphX+T5EYcAAAAAIyNMhsAgGOaphTaJ6L47iqlwF6KAgAAAIAxU2YDAHBs75J8GXkGVtgAAAAA8C/KbAAA+uAiyecRPvd1yruwrbABAAAA4F+U2QAA9MUyye8jeM5dygJ7HitsAAAAAPghZTYAAH0xSXl/9mmlz3ed/SlxAAAAAOAXlNkAAPTJNKXQPqnkeaywAQAAAOCZlNkAAPTNLMnlwJ9hk1JgNz5OAAAAAHgeZTYAAH00T/JhYL/mXcp7v+dJ1j5CAAAAAHgZZTYAAH21SvJ2AL/O+xX2Msmtjw0AAAAA2qHMBgCgryYpC+fXPfy1WWEDAAAAQMeU2QAA9Nk0ZaF90pNfzzb7d2FbYQMAAABAh5TZAAD03SzJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  113204. /***/ }),
  113205. /* 35 */
  113206. /***/ (function(module, exports) {
  113207. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  113208. /***/ }),
  113209. /* 36 */
  113210. /***/ (function(module, exports) {
  113211. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  113212. /***/ }),
  113213. /* 37 */
  113214. /***/ (function(module, exports) {
  113215. 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=="
  113216. /***/ }),
  113217. /* 38 */
  113218. /***/ (function(module, exports) {
  113219. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/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MAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  113220. /***/ }),
  113221. /* 39 */
  113222. /***/ (function(module, exports, __webpack_require__) {
  113223. "use strict";
  113224. Object.defineProperty(exports, "__esModule", { value: true });
  113225. exports.defaultTemplate = __webpack_require__(40);
  113226. exports.defaultViewer = __webpack_require__(41);
  113227. exports.error = __webpack_require__(42);
  113228. exports.fillContainer = __webpack_require__(43);
  113229. exports.help = __webpack_require__(44);
  113230. exports.loadingScreen = __webpack_require__(45);
  113231. exports.navbar = __webpack_require__(46);
  113232. exports.overlay = __webpack_require__(47);
  113233. exports.share = __webpack_require__(48);
  113234. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  113235. /***/ }),
  113236. /* 40 */
  113237. /***/ (function(module, exports) {
  113238. 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>";
  113239. /***/ }),
  113240. /* 41 */
  113241. /***/ (function(module, exports) {
  113242. 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>";
  113243. /***/ }),
  113244. /* 42 */
  113245. /***/ (function(module, exports) {
  113246. module.exports = "Error loading the model";
  113247. /***/ }),
  113248. /* 43 */
  113249. /***/ (function(module, exports) {
  113250. 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>";
  113251. /***/ }),
  113252. /* 44 */
  113253. /***/ (function(module, exports) {
  113254. module.exports = "HELP";
  113255. /***/ }),
  113256. /* 45 */
  113257. /***/ (function(module, exports) {
  113258. 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}}>";
  113259. /***/ }),
  113260. /* 46 */
  113261. /***/ (function(module, exports) {
  113262. module.exports = "<style>nav-bar{position:absolute;height:48px;width:100%;bottom:10px;display:flex;justify-content:center}nav-bar .nav-container{display:flex;flex-direction:row;margin:0 10px;height:100%;width:100%;justify-content:center}nav-bar .animation-control{background-color:rgba(91,93,107,.75);display:flex;flex-direction:row;height:100%;width:100%;max-width:1280px;justify-content:center}nav-bar .flex-container{display:flex;flex-direction:row;justify-content:center;height:100%;width:100%}nav-bar button{background:0 0;border:none;color:#fff;margin:0;padding:0;height:100%;min-width:48px;cursor:pointer}nav-bar button:active,nav-bar button:focus,nav-bar button:hover{background:0 0;border:none;outline:0}nav-bar button:hover{background-color:rgba(22,24,26,.2)}nav-bar .control-text{font-family:\"Segoe UI\";font-size:12px;font-weight:400;pointer-events:none}nav-bar .icon,nav-bar img{pointer-events:none}.logo-button{display:flex;align-items:center;flex-direction:row;justify-content:center;background-color:rgba(91,93,107,.75);height:48px;min-width:48px;margin-right:4px}.logo-button img{height:20px;width:20px}.types{display:flex;flex-direction:column;width:48px}.speed .flex-container,.types .flex-container{align-items:center}.menu-options{position:absolute;bottom:48px;width:48px;background-color:rgba(22,24,26,.9)}.animation-label,.help,.logo-button,.speed,.types-icon{display:none}.types-icon:after{font-size:16px;content:\"\\F6BE\"}.up-icon:after{line-height:16px;font-size:12px;content:\"\\E70E\"}.play-icon:after{font-size:16px;content:\"\\E768\"}.pause-icon:after{font-size:16px;content:\"\\E769\"}.fullscreen-icon:after{font-size:16px;content:\"\\E740\"}.help-icon:after{font-size:16px;content:\"\\EF4E\"}.hd-icon:after{font-size:16px;content:\"\\F765\"}.sd-icon:after{font-size:16px;content:\"\\F766\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-circle{width:12px;height:12px;border:2px solid #fff;border-radius:50%;background-color:#5b5d6b;cursor:pointer;position:relative;bottom:10px;pointer-events:none}.default-control{display:flex;flex-direction:row;height:100%;background-color:rgba(91,93,107,.75)}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button:hover{background-color:transparent;color:#fff}.menu-options .animation-number{margin:0 18px 0 6px}.menu-options .speed-text{margin-right:18px}.menu-options{visibility:hidden}.open .menu-options{visibility:visible}.types .menu-options{width:144px}.types .menu-options button{padding:0 8px;justify-content:left}.types .menu-options button>*{display:flex;margin:8px}.types .menu-options button span.animation-number{display:none}.fullscreen{display:none}@media screen and (min-width:540px){.help,.speed,.types-icon{display:inline-block}.logo-button{display:flex}.types{width:84px}.progress-bar-container{margin:0 12px}.speed{width:64px}.speed .menu-options{width:64px}.fullscreen{display:block}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px;text-overflow:ellipsis;overflow:hidden}nav-bar button.animation-buttons{padding:0 8px;justify-content:left}.icon.up-icon{margin-left:8px}nav-bar button.animation-buttons>div{display:flex;pointer-events:none}.animation-number{display:none}.progress-bar-container{margin:0 12px}.types{width:144px}}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;outline:0;margin:0 12px;height:30px;background-color:transparent}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:#fff}.progress-wrapper::-moz-range-progress{background-color:#fff;height:2px}.progress-wrapper::-moz-range-thumb{width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1)}.progress-wrapper::-moz-range-track{background:#fff;height:2px}.progress-wrapper::-ms-track{height:2px;background:0 0;border-color:transparent;border-width:10px 0;color:transparent}.progress-wrapper::-ms-fill-lower{background:#fff;border-radius:5px}.progress-wrapper::-ms-fill-upper{background:#fff;border-radius:5px}.progress-wrapper::-ms-thumb{width:16px;height:16px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:0}span{display:inline-block}</style> {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} <style>nav-bar .nav-container{justify-content:flex-end}</style> {{else}} <style>nav-bar .nav-container{justify-content:space-between}</style> {{/if}} {{/if}} {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=\"nav-container 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}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control> <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 hideHdButton}} <button class=\"hd-button hd-button\" title={{text.hdButton}}> {{#if hdEnabled}} <span class=\"icon sd-icon\"></span> {{else}} <span class=\"icon hd-icon\"></span> {{/if}} </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>";
  113263. /***/ }),
  113264. /* 47 */
  113265. /***/ (function(module, exports) {
  113266. 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>";
  113267. /***/ }),
  113268. /* 48 */
  113269. /***/ (function(module, exports) {
  113270. module.exports = "SHARE";
  113271. /***/ }),
  113272. /* 49 */
  113273. /***/ (function(module, exports, __webpack_require__) {
  113274. "use strict";
  113275. Object.defineProperty(exports, "__esModule", { value: true });
  113276. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  113277. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  113278. var images = __webpack_require__(2);
  113279. /**
  113280. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  113281. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  113282. */
  113283. exports.defaultConfiguration = {
  113284. version: "3.2.0-alpha4",
  113285. templates: {
  113286. main: {
  113287. html: babylonjs_viewer_assets_1.defaultTemplate,
  113288. params: {
  113289. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  113290. noEscape: true
  113291. }
  113292. },
  113293. fillContainer: {
  113294. html: babylonjs_viewer_assets_1.fillContainer,
  113295. params: {
  113296. disable: false
  113297. }
  113298. },
  113299. loadingScreen: {
  113300. html: babylonjs_viewer_assets_1.loadingScreen,
  113301. params: {
  113302. backgroundColor: "#000000",
  113303. loadingImage: images.loading
  113304. }
  113305. },
  113306. viewer: {
  113307. html: babylonjs_viewer_assets_1.defaultViewer,
  113308. params: {
  113309. enableDragAndDrop: false
  113310. }
  113311. },
  113312. navBar: {
  113313. html: babylonjs_viewer_assets_1.navbar,
  113314. params: {
  113315. speedList: {
  113316. "0.5x": "0.5",
  113317. "1.0x": "1.0",
  113318. "1.5x": "1.5",
  113319. "2.0x": "2.0",
  113320. },
  113321. logoImage: images.babylonLogo,
  113322. logoText: 'BabylonJS',
  113323. logoLink: 'https://babylonjs.com',
  113324. hideHelp: true,
  113325. hideHdButton: true,
  113326. disableOnFullscreen: false,
  113327. text: {
  113328. hdButton: "Toggle HD",
  113329. fullscreenButton: "Fullscreen",
  113330. helpButton: "Help"
  113331. }
  113332. },
  113333. events: {
  113334. pointerdown: {
  113335. '.navbar-control': true,
  113336. '.help-button': true
  113337. },
  113338. input: {
  113339. '.progress-wrapper': true
  113340. },
  113341. pointerup: {
  113342. '.progress-wrapper': true
  113343. }
  113344. }
  113345. },
  113346. overlay: {
  113347. html: babylonjs_viewer_assets_1.overlay,
  113348. params: {
  113349. closeImage: images.close,
  113350. closeText: 'Close'
  113351. }
  113352. },
  113353. help: {
  113354. html: babylonjs_viewer_assets_1.help
  113355. },
  113356. share: {
  113357. html: babylonjs_viewer_assets_1.share
  113358. },
  113359. error: {
  113360. html: babylonjs_viewer_assets_1.error
  113361. }
  113362. },
  113363. camera: {
  113364. behaviors: {
  113365. autoRotate: {
  113366. type: 0
  113367. },
  113368. framing: {
  113369. type: 2,
  113370. zoomOnBoundingInfo: true,
  113371. zoomStopsAnimation: false
  113372. },
  113373. bouncing: {
  113374. type: 1
  113375. }
  113376. }
  113377. },
  113378. skybox: {},
  113379. ground: {
  113380. receiveShadows: true
  113381. },
  113382. engine: {
  113383. antialiasing: true
  113384. },
  113385. scene: {}
  113386. };
  113387. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUUseUNBQWU7WUFDckIsTUFBTSxFQUFFO2dCQUNKLFdBQVcsRUFBRSxxQ0FBVztnQkFDeEIsUUFBUSxFQUFFLElBQUk7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osT0FBTyxFQUFFLEtBQUs7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osZUFBZSxFQUFF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VBQVUsRUFBRSxNQUFNLENBQUMsS0FBSztnQkFDeEIsU0FBUyxFQUFFLE9BQU87YUFDckI7U0FDSjtRQUNELElBQUksRUFBRTtZQUNGLElBQUksRUFBRSw4QkFBSTtTQUNiO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7UUFDRCxLQUFLLEVBQUU7WUFDSCxJQUFJLEVBQUUsK0JBQUs7U0FDZDtLQUVKO0lBQ0QsTUFBTSxFQUFFO1FBQ0osU0FBUyxFQUFFO1lBQ1AsVUFBVSxFQUFFO2dCQUNSLElBQUksRUFBRSxDQUFDO2FBQ1Y7WUFDRCxPQUFPLEVBQUU7Z0JBQ0wsSUFBSSxFQUFFLENBQUM7Z0JBQ1Asa0JBQWtCLEVBQUUsSUFBSTtnQkFDeEIsa0JBQWtCLEVBQUUsS0FBSzthQUM1QjtZQUNELFFBQVEsRUFBRTtnQkFDTixJQUFJLEVBQUUsQ0FBQzthQUNWO1NBQ0o7S0FDSjtJQUNELE1BQU0sRUFBRSxFQUNQO0lBQ0QsTUFBTSxFQUFFO1FBQ0osY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxNQUFNLEVBQUU7UUFDSixZQUFZLEVBQUUsSUFBSTtLQUNyQjtJQUNELEtBQUssRUFBRSxFQUNOO0NBQ0osQ0FBQSJ9
  113388. /***/ }),
  113389. /* 50 */
  113390. /***/ (function(module, exports, __webpack_require__) {
  113391. "use strict";
  113392. Object.defineProperty(exports, "__esModule", { value: true });
  113393. var babylonjs_1 = __webpack_require__(0);
  113394. /**
  113395. * The viewer's "extended" configuration.
  113396. * This configuration defines specific obejcts and parameters that we think make any model look good.
  113397. */
  113398. exports.extendedConfiguration = {
  113399. version: "3.2.0",
  113400. extends: "default",
  113401. camera: {
  113402. exposure: 3.034578,
  113403. fov: 0.7853981633974483,
  113404. contrast: 1.6,
  113405. toneMappingEnabled: true,
  113406. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  113407. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  113408. behaviors: {
  113409. framing: {
  113410. type: 2,
  113411. mode: 0,
  113412. positionScale: 0.5,
  113413. defaultElevation: 0.2617993877991494,
  113414. elevationReturnWaitTime: 3000,
  113415. elevationReturnTime: 2000,
  113416. framingTime: 500,
  113417. zoomStopsAnimation: false,
  113418. radiusScale: 0.866
  113419. },
  113420. autoRotate: {
  113421. type: 0,
  113422. idleRotationWaitTime: 4000,
  113423. idleRotationSpeed: 0.17453292519943295,
  113424. idleRotationSpinupTime: 2500,
  113425. zoomStopsAnimation: false
  113426. },
  113427. bouncing: {
  113428. type: 1,
  113429. lowerRadiusTransitionRange: 0.05,
  113430. upperRadiusTransitionRange: -0.2
  113431. }
  113432. },
  113433. upperRadiusLimit: 5,
  113434. lowerRadiusLimit: 0.5,
  113435. frameOnModelLoad: true,
  113436. framingElevation: 0.2617993877991494,
  113437. framingRotation: 1.5707963267948966,
  113438. radius: 2,
  113439. alpha: 1.5708,
  113440. beta: Math.PI * 0.5 - 0.2618,
  113441. wheelPrecision: 300,
  113442. minZ: 0.1,
  113443. maxZ: 50,
  113444. fovMode: 0,
  113445. pinchPrecision: 1500,
  113446. panningSensibility: 3000
  113447. },
  113448. lights: {
  113449. light0: {
  113450. type: 0,
  113451. frustumEdgeFalloff: 0,
  113452. intensity: 7,
  113453. intensityMode: 0,
  113454. radius: 0.6,
  113455. range: 0.6,
  113456. spotAngle: 60,
  113457. diffuse: {
  113458. r: 1,
  113459. g: 1,
  113460. b: 1
  113461. },
  113462. position: {
  113463. x: -2,
  113464. y: 2.5,
  113465. z: 2
  113466. },
  113467. target: {
  113468. x: 0,
  113469. y: 0,
  113470. z: 0
  113471. },
  113472. enabled: true,
  113473. shadowEnabled: true,
  113474. shadowBufferSize: 512,
  113475. shadowMinZ: 1,
  113476. shadowMaxZ: 10,
  113477. shadowFieldOfView: 60,
  113478. shadowFrustumSize: 2,
  113479. shadowConfig: {
  113480. useBlurCloseExponentialShadowMap: true,
  113481. useKernelBlur: true,
  113482. blurScale: 1.0,
  113483. bias: 0.001,
  113484. depthScale: 50 * (10 - 1),
  113485. frustumEdgeFalloff: 0
  113486. }
  113487. },
  113488. light1: {
  113489. type: 0,
  113490. frustumEdgeFalloff: 0,
  113491. intensity: 7,
  113492. intensityMode: 0,
  113493. radius: 0.4,
  113494. range: 0.4,
  113495. spotAngle: 57,
  113496. diffuse: {
  113497. r: 1,
  113498. g: 1,
  113499. b: 1
  113500. },
  113501. position: {
  113502. x: 4,
  113503. y: 3,
  113504. z: -0.5
  113505. },
  113506. target: {
  113507. x: 0,
  113508. y: 0,
  113509. z: 0
  113510. },
  113511. enabled: true,
  113512. shadowEnabled: false,
  113513. shadowBufferSize: 512,
  113514. shadowMinZ: 0.2,
  113515. shadowMaxZ: 10,
  113516. shadowFieldOfView: 28,
  113517. shadowFrustumSize: 2
  113518. },
  113519. light2: {
  113520. type: 0,
  113521. frustumEdgeFalloff: 0,
  113522. intensity: 1,
  113523. intensityMode: 0,
  113524. radius: 0.5,
  113525. range: 0.5,
  113526. spotAngle: 42.85,
  113527. diffuse: {
  113528. r: 0.8,
  113529. g: 0.8,
  113530. b: 0.8
  113531. },
  113532. position: {
  113533. x: -1,
  113534. y: 3,
  113535. z: -3
  113536. },
  113537. target: {
  113538. x: 0,
  113539. y: 0,
  113540. z: 0
  113541. },
  113542. enabled: true,
  113543. shadowEnabled: false,
  113544. shadowBufferSize: 512,
  113545. shadowMinZ: 0.2,
  113546. shadowMaxZ: 10,
  113547. shadowFieldOfView: 45,
  113548. shadowFrustumSize: 2
  113549. }
  113550. },
  113551. ground: {
  113552. shadowLevel: 0.9,
  113553. texture: "Ground_2.0-1024.png",
  113554. material: {
  113555. primaryColorHighlightLevel: 0.035,
  113556. primaryColorShadowLevel: 0,
  113557. enableNoise: true,
  113558. useRGBColor: false,
  113559. maxSimultaneousLights: 1,
  113560. diffuseTexture: {
  113561. gammaSpace: true
  113562. }
  113563. },
  113564. opacity: 1,
  113565. mirror: false,
  113566. receiveShadows: true,
  113567. size: 5
  113568. },
  113569. skybox: {
  113570. scale: 11,
  113571. cubeTexture: {
  113572. url: "Skybox_2.0-256.dds"
  113573. },
  113574. material: {
  113575. primaryColorHighlightLevel: 0.03,
  113576. primaryColorShadowLevel: 0.03,
  113577. enableNoise: true,
  113578. useRGBColor: false,
  113579. reflectionTexture: {
  113580. gammaSpace: true
  113581. }
  113582. }
  113583. },
  113584. engine: {
  113585. renderInBackground: true
  113586. },
  113587. scene: {
  113588. flags: {
  113589. shadowsEnabled: true,
  113590. particlesEnabled: false,
  113591. collisionsEnabled: false,
  113592. lightsEnabled: true,
  113593. texturesEnabled: true,
  113594. lensFlaresEnabled: false,
  113595. proceduralTexturesEnabled: false,
  113596. renderTargetsEnabled: true,
  113597. spritesEnabled: false,
  113598. skeletonsEnabled: true,
  113599. audioEnabled: false,
  113600. },
  113601. defaultMaterial: {
  113602. materialType: 'pbr',
  113603. reflectivityColor: {
  113604. r: 0.1,
  113605. g: 0.1,
  113606. b: 0.1
  113607. },
  113608. microSurface: 0.6
  113609. },
  113610. clearColor: {
  113611. r: 0.9,
  113612. g: 0.9,
  113613. b: 0.9,
  113614. a: 1.0
  113615. },
  113616. imageProcessingConfiguration: {
  113617. vignetteCentreX: 0,
  113618. vignetteCentreY: 0,
  113619. vignetteColor: {
  113620. r: 0.086,
  113621. g: 0.184,
  113622. b: 0.259,
  113623. a: 1
  113624. },
  113625. vignetteWeight: 0.855,
  113626. vignetteStretch: 0.5,
  113627. vignetteBlendMode: 0,
  113628. vignetteCameraFov: 0.7853981633974483,
  113629. isEnabled: true,
  113630. colorCurves: {
  113631. shadowsHue: 0,
  113632. shadowsDensity: 0,
  113633. shadowsSaturation: 0,
  113634. shadowsExposure: 0,
  113635. midtonesHue: 0,
  113636. midtonesDensity: 0,
  113637. midtonesExposure: 0,
  113638. midtonesSaturation: 0,
  113639. highlightsHue: 0,
  113640. highlightsDensity: 0,
  113641. highlightsExposure: 0,
  113642. highlightsSaturation: 0
  113643. }
  113644. },
  113645. mainColor: {
  113646. r: 0.8823529411764706,
  113647. g: 0.8823529411764706,
  113648. b: 0.8823529411764706
  113649. }
  113650. },
  113651. loaderPlugins: {
  113652. extendedMaterial: true,
  113653. applyMaterialConfig: true,
  113654. msftLod: true,
  113655. telemetry: true
  113656. },
  113657. model: {
  113658. rotationOffsetAxis: {
  113659. x: 0,
  113660. y: -1,
  113661. z: 0
  113662. },
  113663. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  113664. material: {
  113665. directEnabled: true,
  113666. directIntensity: 0.884,
  113667. emissiveIntensity: 1.04,
  113668. environmentIntensity: 0.6
  113669. },
  113670. entryAnimation: {
  113671. scaling: {
  113672. x: 0,
  113673. y: 0,
  113674. z: 0
  113675. },
  113676. time: 0.5,
  113677. easingFunction: 4,
  113678. easingMode: 1
  113679. },
  113680. exitAnimation: {
  113681. scaling: {
  113682. x: 0,
  113683. y: 0,
  113684. z: 0
  113685. },
  113686. time: 0.5,
  113687. easingFunction: 4,
  113688. easingMode: 1
  113689. },
  113690. normalize: true,
  113691. castShadow: true,
  113692. receiveShadows: true
  113693. },
  113694. lab: {
  113695. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  113696. environmentMap: {
  113697. texture: "EnvMap_2.0-256.env",
  113698. rotationY: 3,
  113699. tintLevel: 0.4
  113700. },
  113701. defaultRenderingPipelines: {
  113702. bloomEnabled: true,
  113703. bloomThreshold: 1.0,
  113704. fxaaEnabled: true,
  113705. bloomWeight: 0.05
  113706. }
  113707. }
  113708. };
  113709. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVD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ztnQkFDSixDQUFDLEVBQUUsQ0FBQzthQUNQO1lBQ0QsSUFBSSxFQUFFLEdBQUc7WUFDVCxjQUFjLEVBQUUsQ0FBQztZQUNqQixVQUFVLEVBQUUsQ0FBQztTQUNoQjtRQUNELFNBQVMsRUFBRSxJQUFJO1FBQ2YsVUFBVSxFQUFFLElBQUk7UUFDaEIsY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxHQUFHLEVBQUU7UUFDRCxhQUFhLEVBQUUsa0RBQWtEO1FBQ2pFLGNBQWMsRUFBRTtZQUNaLE9BQU8sRUFBRSxvQkFBb0I7WUFDN0IsU0FBUyxFQUFFLENBQUM7WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  113710. /***/ }),
  113711. /* 51 */
  113712. /***/ (function(module, exports, __webpack_require__) {
  113713. "use strict";
  113714. Object.defineProperty(exports, "__esModule", { value: true });
  113715. /**
  113716. * Defines a default directional shadow light for normalized objects (!)
  113717. */
  113718. exports.shadowDirectionalLightConfiguration = {
  113719. model: {
  113720. receiveShadows: true,
  113721. castShadow: true
  113722. },
  113723. ground: {
  113724. receiveShadows: true
  113725. },
  113726. lights: {
  113727. shadowDirectionalLight: {
  113728. type: 1,
  113729. shadowEnabled: true,
  113730. target: { x: 0, y: 0, z: 0.5 },
  113731. position: { x: 1.49, y: 2.39, z: -1.33 },
  113732. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  113733. intensity: 4.887,
  113734. intensityMode: 0,
  113735. shadowBufferSize: 1024,
  113736. shadowFrustumSize: 6.0,
  113737. shadowFieldOfView: 50.977,
  113738. shadowMinZ: 0.1,
  113739. shadowMaxZ: 10.0,
  113740. shadowConfig: {
  113741. blurKernel: 32,
  113742. useBlurCloseExponentialShadowMap: true
  113743. }
  113744. }
  113745. }
  113746. };
  113747. /**
  113748. * Defines a default shadow-enabled spot light for normalized objects.
  113749. */
  113750. exports.shadowSpotlLightConfiguration = {
  113751. model: {
  113752. receiveShadows: true,
  113753. castShadow: true
  113754. },
  113755. ground: {
  113756. receiveShadows: true
  113757. },
  113758. lights: {
  113759. shadowSpotLight: {
  113760. type: 2,
  113761. intensity: 2,
  113762. shadowEnabled: true,
  113763. target: { x: 0, y: 0, z: 0.5 },
  113764. position: { x: 0, y: 3.5, z: 3.7 },
  113765. angle: 1,
  113766. shadowOrthoScale: 0.5,
  113767. shadowBufferSize: 1024,
  113768. shadowMinZ: 0.1,
  113769. shadowMaxZ: 50.0,
  113770. shadowConfig: {
  113771. frustumEdgeFalloff: 0.5,
  113772. blurKernel: 32,
  113773. useBlurExponentialShadowMap: true
  113774. }
  113775. }
  113776. }
  113777. };
  113778. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQ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VBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsR0FBRyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDbEMsS0FBSyxFQUFFLENBQUM7WUFDUixnQkFBZ0IsRUFBRSxHQUFHO1lBQ3JCLGdCQUFnQixFQUFFLElBQUk7WUFDdEIsVUFBVSxFQUFFLEdBQUc7WUFDZixVQUFVLEVBQUUsSUFBSTtZQUNoQixZQUFZLEVBQUU7Z0JBQ1Ysa0JBQWtCLEVBQUUsR0FBRztnQkFDdkIsVUFBVSxFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0=
  113779. /***/ }),
  113780. /* 52 */
  113781. /***/ (function(module, exports, __webpack_require__) {
  113782. "use strict";
  113783. Object.defineProperty(exports, "__esModule", { value: true });
  113784. /**
  113785. * Lab-oriented default .env support
  113786. */
  113787. exports.environmentMapConfiguration = {
  113788. lab: {
  113789. assetsRootURL: '/assets/environment/',
  113790. environmentMap: {
  113791. texture: 'EnvMap_2.0-256.env',
  113792. rotationY: 0,
  113793. tintLevel: 0.4
  113794. }
  113795. }
  113796. };
  113797. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  113798. /***/ }),
  113799. /* 53 */
  113800. /***/ (function(module, exports, __webpack_require__) {
  113801. "use strict";
  113802. Object.defineProperty(exports, "__esModule", { value: true });
  113803. var configuration_1 = __webpack_require__(11);
  113804. /**
  113805. * This function will make sure the configuration file is taking deprecated fields into account
  113806. * and is setting them to the correct keys and values.
  113807. *
  113808. * @param configuration The configuration to process. Mutable!
  113809. */
  113810. function processConfigurationCompatibility(configuration) {
  113811. if (configuration.camera) {
  113812. // camera contrast -> image processing contrast
  113813. if (configuration.camera.contrast !== undefined) {
  113814. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  113815. }
  113816. // camera exposure -> image processing exposure
  113817. if (configuration.camera.exposure !== undefined) {
  113818. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  113819. }
  113820. }
  113821. if (configuration.scene) {
  113822. //glow
  113823. if (configuration.scene.glow) {
  113824. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  113825. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  113826. if (enabledProcessing !== false) {
  113827. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  113828. }
  113829. }
  113830. }
  113831. }
  113832. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  113833. function setKeyInObject(object, keys, value, shouldOverwrite) {
  113834. var keySplit = keys.split(".");
  113835. if (keySplit.length === 0)
  113836. return;
  113837. var lastKey = keySplit.pop();
  113838. if (!lastKey)
  113839. return;
  113840. var curObj = object;
  113841. keySplit.forEach(function (key) {
  113842. curObj[key] = curObj[key] || {};
  113843. curObj = curObj[key];
  113844. });
  113845. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  113846. return;
  113847. curObj[lastKey] = value;
  113848. }
  113849. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9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LENBQUM7YUFDdkY7U0FDSjtLQUNKO0FBQ0wsQ0FBQztBQTFCRCw4RUEwQkM7QUFFRCx3QkFBd0IsTUFBVyxFQUFFLElBQVksRUFBRSxLQUFVLEVBQUUsZUFBeUI7SUFDcEYsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUMvQixJQUFJLFFBQVEsQ0FBQyxNQUFNLEtBQUssQ0FBQztRQUFFLE9BQU87SUFDbEMsSUFBSSxPQUFPLEdBQUcsUUFBUSxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBQzdCLElBQUksQ0FBQyxPQUFPO1FBQUUsT0FBTztJQUNyQixJQUFJLE1BQU0sR0FBRyxNQUFNLENBQUM7SUFDcEIsUUFBUSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  113850. /***/ }),
  113851. /* 54 */
  113852. /***/ (function(module, exports, __webpack_require__) {
  113853. "use strict";
  113854. Object.defineProperty(exports, "__esModule", { value: true });
  113855. var telemetryLoaderPlugin_1 = __webpack_require__(55);
  113856. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  113857. var msftLodLoaderPlugin_1 = __webpack_require__(56);
  113858. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  113859. var applyMaterialConfig_1 = __webpack_require__(57);
  113860. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  113861. var extendedMaterialLoaderPlugin_1 = __webpack_require__(58);
  113862. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  113863. var babylonjs_1 = __webpack_require__(0);
  113864. var pluginCache = {};
  113865. /**
  113866. * Get a loader plugin according to its name.
  113867. * The plugin will be cached and will be reused if called for again.
  113868. *
  113869. * @param name the name of the plugin
  113870. */
  113871. function getLoaderPluginByName(name) {
  113872. if (!pluginCache[name]) {
  113873. switch (name) {
  113874. case 'telemetry':
  113875. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  113876. break;
  113877. case 'msftLod':
  113878. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  113879. break;
  113880. case 'applyMaterialConfig':
  113881. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  113882. break;
  113883. case 'extendedMaterial':
  113884. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  113885. break;
  113886. }
  113887. }
  113888. return pluginCache[name];
  113889. }
  113890. exports.getLoaderPluginByName = getLoaderPluginByName;
  113891. /**
  113892. *
  113893. */
  113894. function addLoaderPlugin(name, plugin) {
  113895. if (pluginCache[name]) {
  113896. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  113897. }
  113898. pluginCache[name] = plugin;
  113899. }
  113900. exports.addLoaderPlugin = addLoaderPlugin;
  113901. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQ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wQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  113902. /***/ }),
  113903. /* 55 */
  113904. /***/ (function(module, exports, __webpack_require__) {
  113905. "use strict";
  113906. Object.defineProperty(exports, "__esModule", { value: true });
  113907. var telemetryManager_1 = __webpack_require__(6);
  113908. var babylonjs_1 = __webpack_require__(0);
  113909. var TelemetryLoaderPlugin = /** @class */ (function () {
  113910. function TelemetryLoaderPlugin() {
  113911. }
  113912. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  113913. this._model = model;
  113914. this._loadStart = babylonjs_1.Tools.Now;
  113915. };
  113916. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  113917. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  113918. model: model,
  113919. loadTime: babylonjs_1.Tools.Now - this._loadStart
  113920. });
  113921. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  113922. };
  113923. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  113924. this._loadEnd = babylonjs_1.Tools.Now;
  113925. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  113926. model: this._model,
  113927. loadTime: this._loadEnd - this._loadStart
  113928. });
  113929. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  113930. };
  113931. TelemetryLoaderPlugin.prototype.onComplete = function () {
  113932. this._loadEnd = babylonjs_1.Tools.Now;
  113933. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  113934. model: this._model,
  113935. loadTime: this._loadEnd - this._loadStart
  113936. });
  113937. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  113938. };
  113939. return TelemetryLoaderPlugin;
  113940. }());
  113941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lBQVksRUFBRSxJQUFJLENBQUMsTUFBTSxDQUFDLFdBQVcsRUFBRSxFQUFFO1lBQ2hFLEtBQUssRUFBRSxJQUFJLENBQUMsTUFBTTtZQUNsQixRQUFRLEVBQUUsSUFBSSxDQUFDLFFBQVEsR0FBRyxJQUFJLENBQUMsVUFBVTtTQUM1QyxDQUFDLENBQUM7UUFFSCxtQ0FBZ0IsQ0FBQyxnQkFBZ0IsQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxTQUFTLEVBQUUsRUFBRSxJQUFJLENBQUMsTUFBTSxDQUFDLFdBQVcsRUFBRSxDQUFDLENBQUM7SUFDbkcsQ0FBQztJQUVNLDBDQUFVLEdBQWpCO1FBQ0ksSUFBSSxDQUFDLFFBQVEsR0FBRyxpQkFBSyxDQUFDLEdBQUcsQ0FBQztRQUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  113943. /***/ }),
  113944. /* 56 */
  113945. /***/ (function(module, exports, __webpack_require__) {
  113946. "use strict";
  113947. Object.defineProperty(exports, "__esModule", { value: true });
  113948. /**
  113949. * A loder plugin to use MSFT_lod extension correctly (glTF)
  113950. */
  113951. var MSFTLodLoaderPlugin = /** @class */ (function () {
  113952. function MSFTLodLoaderPlugin() {
  113953. }
  113954. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  113955. this._model = model;
  113956. };
  113957. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  113958. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  113959. var MSFT_lod = extension;
  113960. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  113961. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  113962. }
  113963. };
  113964. return MSFTLodLoaderPlugin;
  113965. }());
  113966. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  113967. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  113968. /***/ }),
  113969. /* 57 */
  113970. /***/ (function(module, exports, __webpack_require__) {
  113971. "use strict";
  113972. Object.defineProperty(exports, "__esModule", { value: true });
  113973. /**
  113974. * Force-apply material configuration right after a material was loaded.
  113975. */
  113976. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  113977. function ApplyMaterialConfigPlugin() {
  113978. }
  113979. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  113980. this._model = model;
  113981. };
  113982. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  113983. this._model && this._model._applyModelMaterialConfiguration(material);
  113984. };
  113985. return ApplyMaterialConfigPlugin;
  113986. }());
  113987. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  113988. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  113989. /***/ }),
  113990. /* 58 */
  113991. /***/ (function(module, exports, __webpack_require__) {
  113992. "use strict";
  113993. Object.defineProperty(exports, "__esModule", { value: true });
  113994. var babylonjs_1 = __webpack_require__(0);
  113995. /**
  113996. * A (PBR) material will be extended using this function.
  113997. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  113998. */
  113999. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  114000. function ExtendedMaterialLoaderPlugin() {
  114001. }
  114002. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  114003. var material = baseMaterial;
  114004. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  114005. };
  114006. return ExtendedMaterialLoaderPlugin;
  114007. }());
  114008. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  114009. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsdUNBQTRJO0FBRTVJOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  114010. /***/ }),
  114011. /* 59 */
  114012. /***/ (function(module, exports, __webpack_require__) {
  114013. "use strict";
  114014. Object.defineProperty(exports, "__esModule", { value: true });
  114015. var babylonjs_1 = __webpack_require__(0);
  114016. var ObservablesManager = /** @class */ (function () {
  114017. function ObservablesManager() {
  114018. this.onSceneInitObservable = new babylonjs_1.Observable();
  114019. this.onEngineInitObservable = new babylonjs_1.Observable();
  114020. this.onModelLoadedObservable = new babylonjs_1.Observable();
  114021. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  114022. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  114023. this.onModelAddedObservable = new babylonjs_1.Observable();
  114024. this.onModelRemovedObservable = new babylonjs_1.Observable();
  114025. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  114026. this.onLoaderInitObservable = new babylonjs_1.Observable();
  114027. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  114028. }
  114029. ObservablesManager.prototype.dispose = function () {
  114030. this.onSceneInitObservable.clear();
  114031. this.onEngineInitObservable.clear();
  114032. this.onModelLoadedObservable.clear();
  114033. this.onModelLoadProgressObservable.clear();
  114034. this.onModelLoadErrorObservable.clear();
  114035. this.onModelAddedObservable.clear();
  114036. this.onModelRemovedObservable.clear();
  114037. this.onViewerInitDoneObservable.clear();
  114038. this.onLoaderInitObservable.clear();
  114039. this.onFrameRenderedObservable.clear();
  114040. };
  114041. return ObservablesManager;
  114042. }());
  114043. exports.ObservablesManager = ObservablesManager;
  114044. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIs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0FBQztRQUMzQyxJQUFJLENBQUMsMEJBQTBCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUN0QyxJQUFJLENBQUMsMEJBQTBCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBRUwseUJBQUM7QUFBRCxDQUFDLEFBekVELElBeUVDO0FBekVZLGdEQUFrQiJ9
  114045. /***/ }),
  114046. /* 60 */
  114047. /***/ (function(module, exports, __webpack_require__) {
  114048. "use strict";
  114049. Object.defineProperty(exports, "__esModule", { value: true });
  114050. var babylonjs_1 = __webpack_require__(0);
  114051. var ConfigurationContainer = /** @class */ (function () {
  114052. function ConfigurationContainer() {
  114053. this.mainColor = babylonjs_1.Color3.White();
  114054. this.reflectionColor = babylonjs_1.Color3.White();
  114055. }
  114056. return ConfigurationContainer;
  114057. }());
  114058. exports.ConfigurationContainer = ConfigurationContainer;
  114059. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBMEM7QUFFMUM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUVwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHdEQUFzQiJ9
  114060. /***/ }),
  114061. /* 61 */
  114062. /***/ (function(module, exports, __webpack_require__) {
  114063. "use strict";
  114064. Object.defineProperty(exports, "__esModule", { value: true });
  114065. var babylonjs_1 = __webpack_require__(0);
  114066. var helper_1 = __webpack_require__(1);
  114067. var Handlebars = __webpack_require__(62);
  114068. var eventManager_1 = __webpack_require__(63);
  114069. var _1 = __webpack_require__(1);
  114070. /**
  114071. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  114072. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  114073. */
  114074. var TemplateManager = /** @class */ (function () {
  114075. function TemplateManager(containerElement) {
  114076. this.containerElement = containerElement;
  114077. this.templates = {};
  114078. this.onTemplateInit = new babylonjs_1.Observable();
  114079. this.onTemplateLoaded = new babylonjs_1.Observable();
  114080. this.onTemplateStateChange = new babylonjs_1.Observable();
  114081. this.onAllLoaded = new babylonjs_1.Observable();
  114082. this.onEventTriggered = new babylonjs_1.Observable();
  114083. this.eventManager = new eventManager_1.EventManager(this);
  114084. }
  114085. /**
  114086. * Initialize the template(s) for the viewer. Called bay the Viewer class
  114087. * @param templates the templates to be used to initialize the main template
  114088. */
  114089. TemplateManager.prototype.initTemplate = function (templates) {
  114090. var _this = this;
  114091. var internalInit = function (dependencyMap, name, parentTemplate) {
  114092. //init template
  114093. var template = _this.templates[name];
  114094. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  114095. return internalInit(dependencyMap[childName], childName, template);
  114096. });
  114097. // register the observers
  114098. //template.onLoaded.add(() => {
  114099. var addToParent = function () {
  114100. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  114101. template.appendTo(containingElement);
  114102. _this._checkLoadedState();
  114103. };
  114104. if (parentTemplate && !parentTemplate.parent) {
  114105. parentTemplate.onAppended.add(function () {
  114106. addToParent();
  114107. });
  114108. }
  114109. else {
  114110. addToParent();
  114111. }
  114112. //});
  114113. return template;
  114114. };
  114115. //build the html tree
  114116. return this._buildHTMLTree(templates).then(function (htmlTree) {
  114117. if (_this.templates['main']) {
  114118. internalInit(htmlTree, 'main');
  114119. }
  114120. else {
  114121. _this._checkLoadedState();
  114122. }
  114123. return;
  114124. });
  114125. };
  114126. /**
  114127. *
  114128. * This function will create a simple map with child-dependencies of the template html tree.
  114129. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  114130. * It is expected that the main template will be called main!
  114131. *
  114132. * @param templates
  114133. */
  114134. TemplateManager.prototype._buildHTMLTree = function (templates) {
  114135. var _this = this;
  114136. var promises = Object.keys(templates).map(function (name) {
  114137. // if the template was overridden
  114138. if (!templates[name])
  114139. return Promise.resolve(false);
  114140. // else - we have a template, let's do our job!
  114141. var template = new Template(name, templates[name]);
  114142. template.onLoaded.add(function () {
  114143. _this.onTemplateLoaded.notifyObservers(template);
  114144. });
  114145. template.onStateChange.add(function () {
  114146. _this.onTemplateStateChange.notifyObservers(template);
  114147. });
  114148. _this.onTemplateInit.notifyObservers(template);
  114149. // make sure the global onEventTriggered is called as well
  114150. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  114151. _this.templates[name] = template;
  114152. return template.initPromise;
  114153. });
  114154. return Promise.all(promises).then(function () {
  114155. var templateStructure = {};
  114156. // now iterate through all templates and check for children:
  114157. var buildTree = function (parentObject, name) {
  114158. _this.templates[name].isInHtmlTree = true;
  114159. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  114160. childNodes.forEach(function (element) {
  114161. parentObject[element] = {};
  114162. buildTree(parentObject[element], element);
  114163. });
  114164. };
  114165. if (_this.templates['main']) {
  114166. buildTree(templateStructure, "main");
  114167. }
  114168. return templateStructure;
  114169. });
  114170. };
  114171. /**
  114172. * Get the canvas in the template tree.
  114173. * There must be one and only one canvas inthe template.
  114174. */
  114175. TemplateManager.prototype.getCanvas = function () {
  114176. return this.containerElement.querySelector('canvas');
  114177. };
  114178. /**
  114179. * Get a specific template from the template tree
  114180. * @param name the name of the template to load
  114181. */
  114182. TemplateManager.prototype.getTemplate = function (name) {
  114183. return this.templates[name];
  114184. };
  114185. TemplateManager.prototype._checkLoadedState = function () {
  114186. var _this = this;
  114187. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  114188. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  114189. });
  114190. if (done) {
  114191. this.onAllLoaded.notifyObservers(this);
  114192. }
  114193. };
  114194. /**
  114195. * Dispose the template manager
  114196. */
  114197. TemplateManager.prototype.dispose = function () {
  114198. var _this = this;
  114199. // dispose all templates
  114200. Object.keys(this.templates).forEach(function (template) {
  114201. _this.templates[template].dispose();
  114202. });
  114203. this.templates = {};
  114204. this.eventManager.dispose();
  114205. this.onTemplateInit.clear();
  114206. this.onAllLoaded.clear();
  114207. this.onEventTriggered.clear();
  114208. this.onTemplateLoaded.clear();
  114209. this.onTemplateStateChange.clear();
  114210. };
  114211. return TemplateManager;
  114212. }());
  114213. exports.TemplateManager = TemplateManager;
  114214. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  114215. Handlebars.registerHelper('eachInMap', function (map, block) {
  114216. var out = '';
  114217. Object.keys(map).map(function (prop) {
  114218. var data = map[prop];
  114219. if (typeof data === 'object') {
  114220. data.id = data.id || prop;
  114221. out += block.fn(data);
  114222. }
  114223. else {
  114224. out += block.fn({ id: prop, value: data });
  114225. }
  114226. });
  114227. return out;
  114228. });
  114229. Handlebars.registerHelper('add', function (a, b) {
  114230. var out = a + b;
  114231. return out;
  114232. });
  114233. Handlebars.registerHelper('eq', function (a, b) {
  114234. var out = (a == b);
  114235. return out;
  114236. });
  114237. Handlebars.registerHelper('or', function (a, b) {
  114238. var out = a || b;
  114239. return out;
  114240. });
  114241. Handlebars.registerHelper('not', function (a) {
  114242. var out = !a;
  114243. return out;
  114244. });
  114245. Handlebars.registerHelper('count', function (map) {
  114246. return map.length;
  114247. });
  114248. Handlebars.registerHelper('gt', function (a, b) {
  114249. var out = a > b;
  114250. return out;
  114251. });
  114252. /**
  114253. * This class represents a single template in the viewer's template tree.
  114254. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  114255. * A template is injected using the template manager in the correct position.
  114256. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  114257. *
  114258. * For further information please refer to the documentation page, https://doc.babylonjs.com
  114259. */
  114260. var Template = /** @class */ (function () {
  114261. function Template(name, _configuration) {
  114262. var _this = this;
  114263. this.name = name;
  114264. this._configuration = _configuration;
  114265. this.onLoaded = new babylonjs_1.Observable();
  114266. this.onAppended = new babylonjs_1.Observable();
  114267. this.onStateChange = new babylonjs_1.Observable();
  114268. this.onEventTriggered = new babylonjs_1.Observable();
  114269. this.loadRequests = [];
  114270. this.isLoaded = false;
  114271. this.isShown = false;
  114272. this.isInHtmlTree = false;
  114273. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  114274. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  114275. if (htmlTemplate) {
  114276. _this._htmlTemplate = htmlTemplate;
  114277. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  114278. var config = _this._configuration.params || {};
  114279. _this._rawHtml = compiledTemplate(config);
  114280. try {
  114281. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  114282. }
  114283. catch (e) {
  114284. var test = document.createElement(_this.name);
  114285. test.innerHTML = _this._rawHtml;
  114286. _this._fragment = test;
  114287. }
  114288. _this.isLoaded = true;
  114289. _this.isShown = true;
  114290. _this.onLoaded.notifyObservers(_this);
  114291. }
  114292. return _this;
  114293. });
  114294. }
  114295. /**
  114296. * Some templates have parameters (like background color for example).
  114297. * The parameters are provided to Handlebars which in turn generates the template.
  114298. * This function will update the template with the new parameters
  114299. *
  114300. * Note that when updating parameters the events will be registered again (after being cleared).
  114301. *
  114302. * @param params the new template parameters
  114303. */
  114304. Template.prototype.updateParams = function (params, append) {
  114305. if (append === void 0) { append = true; }
  114306. if (append) {
  114307. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  114308. }
  114309. else {
  114310. this._configuration.params = params;
  114311. }
  114312. // update the template
  114313. if (this.isLoaded) {
  114314. // this.dispose();
  114315. }
  114316. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  114317. var config = this._configuration.params || {};
  114318. this._rawHtml = compiledTemplate(config);
  114319. try {
  114320. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  114321. }
  114322. catch (e) {
  114323. var test = document.createElement(this.name);
  114324. test.innerHTML = this._rawHtml;
  114325. this._fragment = test;
  114326. }
  114327. if (this.parent) {
  114328. this.appendTo(this.parent, true);
  114329. }
  114330. };
  114331. Object.defineProperty(Template.prototype, "configuration", {
  114332. /**
  114333. * Get the template'S configuration
  114334. */
  114335. get: function () {
  114336. return this._configuration;
  114337. },
  114338. enumerable: true,
  114339. configurable: true
  114340. });
  114341. /**
  114342. * A template can be a parent element for other templates or HTML elements.
  114343. * This function will deliver all child HTML elements of this template.
  114344. */
  114345. Template.prototype.getChildElements = function () {
  114346. var childrenArray = [];
  114347. //Edge and IE don't support frage,ent.children
  114348. var children = this._fragment && this._fragment.children;
  114349. if (!this._fragment) {
  114350. var fragment = this.parent.querySelector(this.name);
  114351. if (fragment) {
  114352. children = fragment.querySelectorAll('*');
  114353. }
  114354. }
  114355. if (!children) {
  114356. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  114357. children = this._fragment.querySelectorAll('*');
  114358. }
  114359. for (var i = 0; i < children.length; ++i) {
  114360. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  114361. }
  114362. return childrenArray;
  114363. };
  114364. /**
  114365. * Appending the template to a parent HTML element.
  114366. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  114367. * @param parent the parent to which the template is added
  114368. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  114369. */
  114370. Template.prototype.appendTo = function (parent, forceRemove) {
  114371. var _this = this;
  114372. if (this.parent) {
  114373. if (forceRemove && this._addedFragment) {
  114374. /*let fragement = this.parent.querySelector(this.name)
  114375. if (fragement)
  114376. this.parent.removeChild(fragement);*/
  114377. this.parent.innerHTML = '';
  114378. }
  114379. else {
  114380. return;
  114381. }
  114382. }
  114383. this.parent = parent;
  114384. if (this._configuration.id) {
  114385. this.parent.id = this._configuration.id;
  114386. }
  114387. if (this._fragment) {
  114388. this.parent.appendChild(this._fragment);
  114389. this._addedFragment = this._fragment;
  114390. }
  114391. else {
  114392. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  114393. }
  114394. // appended only one frame after.
  114395. setTimeout(function () {
  114396. _this._registerEvents();
  114397. _this.onAppended.notifyObservers(_this);
  114398. });
  114399. };
  114400. /**
  114401. * Show the template using the provided visibilityFunction, or natively using display: flex.
  114402. * The provided function returns a promise that should be fullfilled when the element is shown.
  114403. * Since it is a promise async operations are more than possible.
  114404. * See the default viewer for an opacity example.
  114405. * @param visibilityFunction The function to execute to show the template.
  114406. */
  114407. Template.prototype.show = function (visibilityFunction) {
  114408. var _this = this;
  114409. if (this._isHiding)
  114410. return Promise.resolve(this);
  114411. return Promise.resolve().then(function () {
  114412. _this._isShowing = true;
  114413. if (visibilityFunction) {
  114414. return visibilityFunction(_this);
  114415. }
  114416. else {
  114417. // flex? box? should this be configurable easier than the visibilityFunction?
  114418. _this.parent.style.display = 'flex';
  114419. // support old browsers with no flex:
  114420. if (_this.parent.style.display !== 'flex') {
  114421. _this.parent.style.display = '';
  114422. }
  114423. return _this;
  114424. }
  114425. }).then(function () {
  114426. _this.isShown = true;
  114427. _this._isShowing = false;
  114428. _this.onStateChange.notifyObservers(_this);
  114429. return _this;
  114430. });
  114431. };
  114432. /**
  114433. * Hide the template using the provided visibilityFunction, or natively using display: none.
  114434. * The provided function returns a promise that should be fullfilled when the element is hidden.
  114435. * Since it is a promise async operations are more than possible.
  114436. * See the default viewer for an opacity example.
  114437. * @param visibilityFunction The function to execute to show the template.
  114438. */
  114439. Template.prototype.hide = function (visibilityFunction) {
  114440. var _this = this;
  114441. if (this._isShowing)
  114442. return Promise.resolve(this);
  114443. return Promise.resolve().then(function () {
  114444. _this._isHiding = true;
  114445. if (visibilityFunction) {
  114446. return visibilityFunction(_this);
  114447. }
  114448. else {
  114449. // flex? box? should this be configurable easier than the visibilityFunction?
  114450. _this.parent.style.display = 'none';
  114451. return _this;
  114452. }
  114453. }).then(function () {
  114454. _this.isShown = false;
  114455. _this._isHiding = false;
  114456. _this.onStateChange.notifyObservers(_this);
  114457. return _this;
  114458. });
  114459. };
  114460. /**
  114461. * Dispose this template
  114462. */
  114463. Template.prototype.dispose = function () {
  114464. this.onAppended.clear();
  114465. this.onEventTriggered.clear();
  114466. this.onLoaded.clear();
  114467. this.onStateChange.clear();
  114468. this.isLoaded = false;
  114469. // remove from parent
  114470. try {
  114471. this.parent.removeChild(this._fragment);
  114472. }
  114473. catch (e) {
  114474. //noop
  114475. }
  114476. this.loadRequests.forEach(function (request) {
  114477. request.abort();
  114478. });
  114479. if (this._registeredEvents) {
  114480. this._registeredEvents.forEach(function (evt) {
  114481. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  114482. });
  114483. }
  114484. delete this._fragment;
  114485. };
  114486. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  114487. var _this = this;
  114488. if (!templateConfig) {
  114489. return Promise.reject('No templateConfig provided');
  114490. }
  114491. else if (templateConfig.html !== undefined) {
  114492. return Promise.resolve(templateConfig.html);
  114493. }
  114494. else {
  114495. var location_1 = this._getTemplateLocation(templateConfig);
  114496. if (helper_1.isUrl(location_1)) {
  114497. return new Promise(function (resolve, reject) {
  114498. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  114499. resolve(data);
  114500. }, undefined, undefined, false, function (request, error) {
  114501. reject(error);
  114502. });
  114503. _this.loadRequests.push(fileRequest);
  114504. });
  114505. }
  114506. else {
  114507. location_1 = location_1.replace('#', '');
  114508. var element = document.getElementById(location_1);
  114509. if (element) {
  114510. return Promise.resolve(element.innerHTML);
  114511. }
  114512. else {
  114513. return Promise.reject('Template ID not found');
  114514. }
  114515. }
  114516. }
  114517. };
  114518. Template.prototype._registerEvents = function () {
  114519. var _this = this;
  114520. this._registeredEvents = this._registeredEvents || [];
  114521. if (this._registeredEvents.length) {
  114522. // first remove the registered events
  114523. this._registeredEvents.forEach(function (evt) {
  114524. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  114525. });
  114526. }
  114527. if (this._configuration.events) {
  114528. var _loop_1 = function (eventName) {
  114529. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  114530. var functionToFire_1 = function (selector, event) {
  114531. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  114532. };
  114533. // if boolean, set the parent as the event listener
  114534. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  114535. var selector = this_1.parent.id;
  114536. if (selector) {
  114537. selector = '#' + selector;
  114538. }
  114539. else {
  114540. selector = this_1.parent.tagName;
  114541. }
  114542. var binding = functionToFire_1.bind(this_1, selector);
  114543. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  114544. this_1._registeredEvents.push({
  114545. htmlElement: this_1.parent,
  114546. eventName: eventName,
  114547. function: binding
  114548. });
  114549. }
  114550. else if (typeof this_1._configuration.events[eventName] === 'object') {
  114551. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  114552. // strict null checl is working incorrectly, must override:
  114553. var event_1 = this_1._configuration.events[eventName] || {};
  114554. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  114555. var htmlElement = _this.parent.querySelector(selector);
  114556. if (!htmlElement) {
  114557. // backcompat, fallback to id
  114558. if (selector && selector.indexOf('#') !== 0) {
  114559. selector = '#' + selector;
  114560. }
  114561. try {
  114562. htmlElement = _this.parent.querySelector(selector);
  114563. }
  114564. catch (e) { }
  114565. }
  114566. if (htmlElement) {
  114567. var binding = functionToFire_1.bind(_this, selector);
  114568. htmlElement.addEventListener(eventName, binding, false);
  114569. _this._registeredEvents.push({
  114570. htmlElement: htmlElement,
  114571. eventName: eventName,
  114572. function: binding
  114573. });
  114574. }
  114575. });
  114576. }
  114577. }
  114578. };
  114579. var this_1 = this;
  114580. for (var eventName in this._configuration.events) {
  114581. _loop_1(eventName);
  114582. }
  114583. }
  114584. };
  114585. Template.prototype._getTemplateLocation = function (templateConfig) {
  114586. if (!templateConfig || typeof templateConfig === 'string') {
  114587. return templateConfig;
  114588. }
  114589. else {
  114590. return templateConfig.location;
  114591. }
  114592. };
  114593. return Template;
  114594. }());
  114595. exports.Template = Template;
  114596. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJL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FRLEVBQUUsT0FBTztpQ0FDcEIsQ0FBQyxDQUFDOzZCQUNOO3dCQUNMLENBQUMsQ0FBQyxDQUFDO3FCQUNOO2lCQUNKO1lBQ0wsQ0FBQzs7WUFoREQsS0FBSyxJQUFJLFNBQVMsSUFBSSxJQUFJLENBQUMsY0FBYyxDQUFDLE1BQU07d0JBQXZDLFNBQVM7YUFnRGpCO1NBQ0o7SUFDTCxDQUFDO0lBRU8sdUNBQW9CLEdBQTVCLFVBQTZCLGNBQWM7UUFDdkMsSUFBSSxDQUFDLGNBQWMsSUFBSSxPQUFPLGNBQWMsS0FBSyxRQUFRLEVBQUU7WUFDdkQsT0FBTyxjQUFjLENBQUM7U0FDekI7YUFBTTtZQUNILE9BQU8sY0FBYyxDQUFDLFFBQVEsQ0FBQztTQUNsQztJQUNMLENBQUM7SUFDTCxlQUFDO0FBQUQsQ0FBQyxBQXJYRCxJQXFYQztBQXJYWSw0QkFBUSJ9
  114597. /***/ }),
  114598. /* 62 */
  114599. /***/ (function(module, exports, __webpack_require__) {
  114600. /**!
  114601. @license
  114602. handlebars v4.0.11
  114603. Copyright (C) 2011-2017 by Yehuda Katz
  114604. Permission is hereby granted, free of charge, to any person obtaining a copy
  114605. of this software and associated documentation files (the "Software"), to deal
  114606. in the Software without restriction, including without limitation the rights
  114607. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  114608. copies of the Software, and to permit persons to whom the Software is
  114609. furnished to do so, subject to the following conditions:
  114610. The above copyright notice and this permission notice shall be included in
  114611. all copies or substantial portions of the Software.
  114612. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  114613. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  114614. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  114615. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  114616. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  114617. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  114618. THE SOFTWARE.
  114619. */
  114620. (function webpackUniversalModuleDefinition(root, factory) {
  114621. if(true)
  114622. module.exports = factory();
  114623. else if(typeof define === 'function' && define.amd)
  114624. define([], factory);
  114625. else if(typeof exports === 'object')
  114626. exports["Handlebars"] = factory();
  114627. else
  114628. root["Handlebars"] = factory();
  114629. })(this, function() {
  114630. return /******/ (function(modules) { // webpackBootstrap
  114631. /******/ // The module cache
  114632. /******/ var installedModules = {};
  114633. /******/ // The require function
  114634. /******/ function __webpack_require__(moduleId) {
  114635. /******/ // Check if module is in cache
  114636. /******/ if(installedModules[moduleId])
  114637. /******/ return installedModules[moduleId].exports;
  114638. /******/ // Create a new module (and put it into the cache)
  114639. /******/ var module = installedModules[moduleId] = {
  114640. /******/ exports: {},
  114641. /******/ id: moduleId,
  114642. /******/ loaded: false
  114643. /******/ };
  114644. /******/ // Execute the module function
  114645. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  114646. /******/ // Flag the module as loaded
  114647. /******/ module.loaded = true;
  114648. /******/ // Return the exports of the module
  114649. /******/ return module.exports;
  114650. /******/ }
  114651. /******/ // expose the modules object (__webpack_modules__)
  114652. /******/ __webpack_require__.m = modules;
  114653. /******/ // expose the module cache
  114654. /******/ __webpack_require__.c = installedModules;
  114655. /******/ // __webpack_public_path__
  114656. /******/ __webpack_require__.p = "";
  114657. /******/ // Load entry module and return exports
  114658. /******/ return __webpack_require__(0);
  114659. /******/ })
  114660. /************************************************************************/
  114661. /******/ ([
  114662. /* 0 */
  114663. /***/ (function(module, exports, __webpack_require__) {
  114664. 'use strict';
  114665. var _interopRequireDefault = __webpack_require__(1)['default'];
  114666. exports.__esModule = true;
  114667. var _handlebarsRuntime = __webpack_require__(2);
  114668. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  114669. // Compiler imports
  114670. var _handlebarsCompilerAst = __webpack_require__(35);
  114671. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  114672. var _handlebarsCompilerBase = __webpack_require__(36);
  114673. var _handlebarsCompilerCompiler = __webpack_require__(41);
  114674. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  114675. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  114676. var _handlebarsCompilerVisitor = __webpack_require__(39);
  114677. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  114678. var _handlebarsNoConflict = __webpack_require__(34);
  114679. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  114680. var _create = _handlebarsRuntime2['default'].create;
  114681. function create() {
  114682. var hb = _create();
  114683. hb.compile = function (input, options) {
  114684. return _handlebarsCompilerCompiler.compile(input, options, hb);
  114685. };
  114686. hb.precompile = function (input, options) {
  114687. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  114688. };
  114689. hb.AST = _handlebarsCompilerAst2['default'];
  114690. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  114691. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  114692. hb.Parser = _handlebarsCompilerBase.parser;
  114693. hb.parse = _handlebarsCompilerBase.parse;
  114694. return hb;
  114695. }
  114696. var inst = create();
  114697. inst.create = create;
  114698. _handlebarsNoConflict2['default'](inst);
  114699. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  114700. inst['default'] = inst;
  114701. exports['default'] = inst;
  114702. module.exports = exports['default'];
  114703. /***/ }),
  114704. /* 1 */
  114705. /***/ (function(module, exports) {
  114706. "use strict";
  114707. exports["default"] = function (obj) {
  114708. return obj && obj.__esModule ? obj : {
  114709. "default": obj
  114710. };
  114711. };
  114712. exports.__esModule = true;
  114713. /***/ }),
  114714. /* 2 */
  114715. /***/ (function(module, exports, __webpack_require__) {
  114716. 'use strict';
  114717. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114718. var _interopRequireDefault = __webpack_require__(1)['default'];
  114719. exports.__esModule = true;
  114720. var _handlebarsBase = __webpack_require__(4);
  114721. var base = _interopRequireWildcard(_handlebarsBase);
  114722. // Each of these augment the Handlebars object. No need to setup here.
  114723. // (This is done to easily share code between commonjs and browse envs)
  114724. var _handlebarsSafeString = __webpack_require__(21);
  114725. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  114726. var _handlebarsException = __webpack_require__(6);
  114727. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  114728. var _handlebarsUtils = __webpack_require__(5);
  114729. var Utils = _interopRequireWildcard(_handlebarsUtils);
  114730. var _handlebarsRuntime = __webpack_require__(22);
  114731. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  114732. var _handlebarsNoConflict = __webpack_require__(34);
  114733. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  114734. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  114735. function create() {
  114736. var hb = new base.HandlebarsEnvironment();
  114737. Utils.extend(hb, base);
  114738. hb.SafeString = _handlebarsSafeString2['default'];
  114739. hb.Exception = _handlebarsException2['default'];
  114740. hb.Utils = Utils;
  114741. hb.escapeExpression = Utils.escapeExpression;
  114742. hb.VM = runtime;
  114743. hb.template = function (spec) {
  114744. return runtime.template(spec, hb);
  114745. };
  114746. return hb;
  114747. }
  114748. var inst = create();
  114749. inst.create = create;
  114750. _handlebarsNoConflict2['default'](inst);
  114751. inst['default'] = inst;
  114752. exports['default'] = inst;
  114753. module.exports = exports['default'];
  114754. /***/ }),
  114755. /* 3 */
  114756. /***/ (function(module, exports) {
  114757. "use strict";
  114758. exports["default"] = function (obj) {
  114759. if (obj && obj.__esModule) {
  114760. return obj;
  114761. } else {
  114762. var newObj = {};
  114763. if (obj != null) {
  114764. for (var key in obj) {
  114765. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  114766. }
  114767. }
  114768. newObj["default"] = obj;
  114769. return newObj;
  114770. }
  114771. };
  114772. exports.__esModule = true;
  114773. /***/ }),
  114774. /* 4 */
  114775. /***/ (function(module, exports, __webpack_require__) {
  114776. 'use strict';
  114777. var _interopRequireDefault = __webpack_require__(1)['default'];
  114778. exports.__esModule = true;
  114779. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  114780. var _utils = __webpack_require__(5);
  114781. var _exception = __webpack_require__(6);
  114782. var _exception2 = _interopRequireDefault(_exception);
  114783. var _helpers = __webpack_require__(10);
  114784. var _decorators = __webpack_require__(18);
  114785. var _logger = __webpack_require__(20);
  114786. var _logger2 = _interopRequireDefault(_logger);
  114787. var VERSION = '4.0.11';
  114788. exports.VERSION = VERSION;
  114789. var COMPILER_REVISION = 7;
  114790. exports.COMPILER_REVISION = COMPILER_REVISION;
  114791. var REVISION_CHANGES = {
  114792. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  114793. 2: '== 1.0.0-rc.3',
  114794. 3: '== 1.0.0-rc.4',
  114795. 4: '== 1.x.x',
  114796. 5: '== 2.0.0-alpha.x',
  114797. 6: '>= 2.0.0-beta.1',
  114798. 7: '>= 4.0.0'
  114799. };
  114800. exports.REVISION_CHANGES = REVISION_CHANGES;
  114801. var objectType = '[object Object]';
  114802. function HandlebarsEnvironment(helpers, partials, decorators) {
  114803. this.helpers = helpers || {};
  114804. this.partials = partials || {};
  114805. this.decorators = decorators || {};
  114806. _helpers.registerDefaultHelpers(this);
  114807. _decorators.registerDefaultDecorators(this);
  114808. }
  114809. HandlebarsEnvironment.prototype = {
  114810. constructor: HandlebarsEnvironment,
  114811. logger: _logger2['default'],
  114812. log: _logger2['default'].log,
  114813. registerHelper: function registerHelper(name, fn) {
  114814. if (_utils.toString.call(name) === objectType) {
  114815. if (fn) {
  114816. throw new _exception2['default']('Arg not supported with multiple helpers');
  114817. }
  114818. _utils.extend(this.helpers, name);
  114819. } else {
  114820. this.helpers[name] = fn;
  114821. }
  114822. },
  114823. unregisterHelper: function unregisterHelper(name) {
  114824. delete this.helpers[name];
  114825. },
  114826. registerPartial: function registerPartial(name, partial) {
  114827. if (_utils.toString.call(name) === objectType) {
  114828. _utils.extend(this.partials, name);
  114829. } else {
  114830. if (typeof partial === 'undefined') {
  114831. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  114832. }
  114833. this.partials[name] = partial;
  114834. }
  114835. },
  114836. unregisterPartial: function unregisterPartial(name) {
  114837. delete this.partials[name];
  114838. },
  114839. registerDecorator: function registerDecorator(name, fn) {
  114840. if (_utils.toString.call(name) === objectType) {
  114841. if (fn) {
  114842. throw new _exception2['default']('Arg not supported with multiple decorators');
  114843. }
  114844. _utils.extend(this.decorators, name);
  114845. } else {
  114846. this.decorators[name] = fn;
  114847. }
  114848. },
  114849. unregisterDecorator: function unregisterDecorator(name) {
  114850. delete this.decorators[name];
  114851. }
  114852. };
  114853. var log = _logger2['default'].log;
  114854. exports.log = log;
  114855. exports.createFrame = _utils.createFrame;
  114856. exports.logger = _logger2['default'];
  114857. /***/ }),
  114858. /* 5 */
  114859. /***/ (function(module, exports) {
  114860. 'use strict';
  114861. exports.__esModule = true;
  114862. exports.extend = extend;
  114863. exports.indexOf = indexOf;
  114864. exports.escapeExpression = escapeExpression;
  114865. exports.isEmpty = isEmpty;
  114866. exports.createFrame = createFrame;
  114867. exports.blockParams = blockParams;
  114868. exports.appendContextPath = appendContextPath;
  114869. var escape = {
  114870. '&': '&amp;',
  114871. '<': '&lt;',
  114872. '>': '&gt;',
  114873. '"': '&quot;',
  114874. "'": '&#x27;',
  114875. '`': '&#x60;',
  114876. '=': '&#x3D;'
  114877. };
  114878. var badChars = /[&<>"'`=]/g,
  114879. possible = /[&<>"'`=]/;
  114880. function escapeChar(chr) {
  114881. return escape[chr];
  114882. }
  114883. function extend(obj /* , ...source */) {
  114884. for (var i = 1; i < arguments.length; i++) {
  114885. for (var key in arguments[i]) {
  114886. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  114887. obj[key] = arguments[i][key];
  114888. }
  114889. }
  114890. }
  114891. return obj;
  114892. }
  114893. var toString = Object.prototype.toString;
  114894. exports.toString = toString;
  114895. // Sourced from lodash
  114896. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  114897. /* eslint-disable func-style */
  114898. var isFunction = function isFunction(value) {
  114899. return typeof value === 'function';
  114900. };
  114901. // fallback for older versions of Chrome and Safari
  114902. /* istanbul ignore next */
  114903. if (isFunction(/x/)) {
  114904. exports.isFunction = isFunction = function (value) {
  114905. return typeof value === 'function' && toString.call(value) === '[object Function]';
  114906. };
  114907. }
  114908. exports.isFunction = isFunction;
  114909. /* eslint-enable func-style */
  114910. /* istanbul ignore next */
  114911. var isArray = Array.isArray || function (value) {
  114912. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  114913. };
  114914. exports.isArray = isArray;
  114915. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  114916. function indexOf(array, value) {
  114917. for (var i = 0, len = array.length; i < len; i++) {
  114918. if (array[i] === value) {
  114919. return i;
  114920. }
  114921. }
  114922. return -1;
  114923. }
  114924. function escapeExpression(string) {
  114925. if (typeof string !== 'string') {
  114926. // don't escape SafeStrings, since they're already safe
  114927. if (string && string.toHTML) {
  114928. return string.toHTML();
  114929. } else if (string == null) {
  114930. return '';
  114931. } else if (!string) {
  114932. return string + '';
  114933. }
  114934. // Force a string conversion as this will be done by the append regardless and
  114935. // the regex test will do this transparently behind the scenes, causing issues if
  114936. // an object's to string has escaped characters in it.
  114937. string = '' + string;
  114938. }
  114939. if (!possible.test(string)) {
  114940. return string;
  114941. }
  114942. return string.replace(badChars, escapeChar);
  114943. }
  114944. function isEmpty(value) {
  114945. if (!value && value !== 0) {
  114946. return true;
  114947. } else if (isArray(value) && value.length === 0) {
  114948. return true;
  114949. } else {
  114950. return false;
  114951. }
  114952. }
  114953. function createFrame(object) {
  114954. var frame = extend({}, object);
  114955. frame._parent = object;
  114956. return frame;
  114957. }
  114958. function blockParams(params, ids) {
  114959. params.path = ids;
  114960. return params;
  114961. }
  114962. function appendContextPath(contextPath, id) {
  114963. return (contextPath ? contextPath + '.' : '') + id;
  114964. }
  114965. /***/ }),
  114966. /* 6 */
  114967. /***/ (function(module, exports, __webpack_require__) {
  114968. 'use strict';
  114969. var _Object$defineProperty = __webpack_require__(7)['default'];
  114970. exports.__esModule = true;
  114971. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  114972. function Exception(message, node) {
  114973. var loc = node && node.loc,
  114974. line = undefined,
  114975. column = undefined;
  114976. if (loc) {
  114977. line = loc.start.line;
  114978. column = loc.start.column;
  114979. message += ' - ' + line + ':' + column;
  114980. }
  114981. var tmp = Error.prototype.constructor.call(this, message);
  114982. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  114983. for (var idx = 0; idx < errorProps.length; idx++) {
  114984. this[errorProps[idx]] = tmp[errorProps[idx]];
  114985. }
  114986. /* istanbul ignore else */
  114987. if (Error.captureStackTrace) {
  114988. Error.captureStackTrace(this, Exception);
  114989. }
  114990. try {
  114991. if (loc) {
  114992. this.lineNumber = line;
  114993. // Work around issue under safari where we can't directly set the column value
  114994. /* istanbul ignore next */
  114995. if (_Object$defineProperty) {
  114996. Object.defineProperty(this, 'column', {
  114997. value: column,
  114998. enumerable: true
  114999. });
  115000. } else {
  115001. this.column = column;
  115002. }
  115003. }
  115004. } catch (nop) {
  115005. /* Ignore if the browser is very particular */
  115006. }
  115007. }
  115008. Exception.prototype = new Error();
  115009. exports['default'] = Exception;
  115010. module.exports = exports['default'];
  115011. /***/ }),
  115012. /* 7 */
  115013. /***/ (function(module, exports, __webpack_require__) {
  115014. module.exports = { "default": __webpack_require__(8), __esModule: true };
  115015. /***/ }),
  115016. /* 8 */
  115017. /***/ (function(module, exports, __webpack_require__) {
  115018. var $ = __webpack_require__(9);
  115019. module.exports = function defineProperty(it, key, desc){
  115020. return $.setDesc(it, key, desc);
  115021. };
  115022. /***/ }),
  115023. /* 9 */
  115024. /***/ (function(module, exports) {
  115025. var $Object = Object;
  115026. module.exports = {
  115027. create: $Object.create,
  115028. getProto: $Object.getPrototypeOf,
  115029. isEnum: {}.propertyIsEnumerable,
  115030. getDesc: $Object.getOwnPropertyDescriptor,
  115031. setDesc: $Object.defineProperty,
  115032. setDescs: $Object.defineProperties,
  115033. getKeys: $Object.keys,
  115034. getNames: $Object.getOwnPropertyNames,
  115035. getSymbols: $Object.getOwnPropertySymbols,
  115036. each: [].forEach
  115037. };
  115038. /***/ }),
  115039. /* 10 */
  115040. /***/ (function(module, exports, __webpack_require__) {
  115041. 'use strict';
  115042. var _interopRequireDefault = __webpack_require__(1)['default'];
  115043. exports.__esModule = true;
  115044. exports.registerDefaultHelpers = registerDefaultHelpers;
  115045. var _helpersBlockHelperMissing = __webpack_require__(11);
  115046. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  115047. var _helpersEach = __webpack_require__(12);
  115048. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  115049. var _helpersHelperMissing = __webpack_require__(13);
  115050. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  115051. var _helpersIf = __webpack_require__(14);
  115052. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  115053. var _helpersLog = __webpack_require__(15);
  115054. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  115055. var _helpersLookup = __webpack_require__(16);
  115056. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  115057. var _helpersWith = __webpack_require__(17);
  115058. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  115059. function registerDefaultHelpers(instance) {
  115060. _helpersBlockHelperMissing2['default'](instance);
  115061. _helpersEach2['default'](instance);
  115062. _helpersHelperMissing2['default'](instance);
  115063. _helpersIf2['default'](instance);
  115064. _helpersLog2['default'](instance);
  115065. _helpersLookup2['default'](instance);
  115066. _helpersWith2['default'](instance);
  115067. }
  115068. /***/ }),
  115069. /* 11 */
  115070. /***/ (function(module, exports, __webpack_require__) {
  115071. 'use strict';
  115072. exports.__esModule = true;
  115073. var _utils = __webpack_require__(5);
  115074. exports['default'] = function (instance) {
  115075. instance.registerHelper('blockHelperMissing', function (context, options) {
  115076. var inverse = options.inverse,
  115077. fn = options.fn;
  115078. if (context === true) {
  115079. return fn(this);
  115080. } else if (context === false || context == null) {
  115081. return inverse(this);
  115082. } else if (_utils.isArray(context)) {
  115083. if (context.length > 0) {
  115084. if (options.ids) {
  115085. options.ids = [options.name];
  115086. }
  115087. return instance.helpers.each(context, options);
  115088. } else {
  115089. return inverse(this);
  115090. }
  115091. } else {
  115092. if (options.data && options.ids) {
  115093. var data = _utils.createFrame(options.data);
  115094. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  115095. options = { data: data };
  115096. }
  115097. return fn(context, options);
  115098. }
  115099. });
  115100. };
  115101. module.exports = exports['default'];
  115102. /***/ }),
  115103. /* 12 */
  115104. /***/ (function(module, exports, __webpack_require__) {
  115105. 'use strict';
  115106. var _interopRequireDefault = __webpack_require__(1)['default'];
  115107. exports.__esModule = true;
  115108. var _utils = __webpack_require__(5);
  115109. var _exception = __webpack_require__(6);
  115110. var _exception2 = _interopRequireDefault(_exception);
  115111. exports['default'] = function (instance) {
  115112. instance.registerHelper('each', function (context, options) {
  115113. if (!options) {
  115114. throw new _exception2['default']('Must pass iterator to #each');
  115115. }
  115116. var fn = options.fn,
  115117. inverse = options.inverse,
  115118. i = 0,
  115119. ret = '',
  115120. data = undefined,
  115121. contextPath = undefined;
  115122. if (options.data && options.ids) {
  115123. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  115124. }
  115125. if (_utils.isFunction(context)) {
  115126. context = context.call(this);
  115127. }
  115128. if (options.data) {
  115129. data = _utils.createFrame(options.data);
  115130. }
  115131. function execIteration(field, index, last) {
  115132. if (data) {
  115133. data.key = field;
  115134. data.index = index;
  115135. data.first = index === 0;
  115136. data.last = !!last;
  115137. if (contextPath) {
  115138. data.contextPath = contextPath + field;
  115139. }
  115140. }
  115141. ret = ret + fn(context[field], {
  115142. data: data,
  115143. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  115144. });
  115145. }
  115146. if (context && typeof context === 'object') {
  115147. if (_utils.isArray(context)) {
  115148. for (var j = context.length; i < j; i++) {
  115149. if (i in context) {
  115150. execIteration(i, i, i === context.length - 1);
  115151. }
  115152. }
  115153. } else {
  115154. var priorKey = undefined;
  115155. for (var key in context) {
  115156. if (context.hasOwnProperty(key)) {
  115157. // We're running the iterations one step out of sync so we can detect
  115158. // the last iteration without have to scan the object twice and create
  115159. // an itermediate keys array.
  115160. if (priorKey !== undefined) {
  115161. execIteration(priorKey, i - 1);
  115162. }
  115163. priorKey = key;
  115164. i++;
  115165. }
  115166. }
  115167. if (priorKey !== undefined) {
  115168. execIteration(priorKey, i - 1, true);
  115169. }
  115170. }
  115171. }
  115172. if (i === 0) {
  115173. ret = inverse(this);
  115174. }
  115175. return ret;
  115176. });
  115177. };
  115178. module.exports = exports['default'];
  115179. /***/ }),
  115180. /* 13 */
  115181. /***/ (function(module, exports, __webpack_require__) {
  115182. 'use strict';
  115183. var _interopRequireDefault = __webpack_require__(1)['default'];
  115184. exports.__esModule = true;
  115185. var _exception = __webpack_require__(6);
  115186. var _exception2 = _interopRequireDefault(_exception);
  115187. exports['default'] = function (instance) {
  115188. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  115189. if (arguments.length === 1) {
  115190. // A missing field in a {{foo}} construct.
  115191. return undefined;
  115192. } else {
  115193. // Someone is actually trying to call something, blow up.
  115194. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  115195. }
  115196. });
  115197. };
  115198. module.exports = exports['default'];
  115199. /***/ }),
  115200. /* 14 */
  115201. /***/ (function(module, exports, __webpack_require__) {
  115202. 'use strict';
  115203. exports.__esModule = true;
  115204. var _utils = __webpack_require__(5);
  115205. exports['default'] = function (instance) {
  115206. instance.registerHelper('if', function (conditional, options) {
  115207. if (_utils.isFunction(conditional)) {
  115208. conditional = conditional.call(this);
  115209. }
  115210. // Default behavior is to render the positive path if the value is truthy and not empty.
  115211. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  115212. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  115213. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  115214. return options.inverse(this);
  115215. } else {
  115216. return options.fn(this);
  115217. }
  115218. });
  115219. instance.registerHelper('unless', function (conditional, options) {
  115220. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  115221. });
  115222. };
  115223. module.exports = exports['default'];
  115224. /***/ }),
  115225. /* 15 */
  115226. /***/ (function(module, exports) {
  115227. 'use strict';
  115228. exports.__esModule = true;
  115229. exports['default'] = function (instance) {
  115230. instance.registerHelper('log', function () /* message, options */{
  115231. var args = [undefined],
  115232. options = arguments[arguments.length - 1];
  115233. for (var i = 0; i < arguments.length - 1; i++) {
  115234. args.push(arguments[i]);
  115235. }
  115236. var level = 1;
  115237. if (options.hash.level != null) {
  115238. level = options.hash.level;
  115239. } else if (options.data && options.data.level != null) {
  115240. level = options.data.level;
  115241. }
  115242. args[0] = level;
  115243. instance.log.apply(instance, args);
  115244. });
  115245. };
  115246. module.exports = exports['default'];
  115247. /***/ }),
  115248. /* 16 */
  115249. /***/ (function(module, exports) {
  115250. 'use strict';
  115251. exports.__esModule = true;
  115252. exports['default'] = function (instance) {
  115253. instance.registerHelper('lookup', function (obj, field) {
  115254. return obj && obj[field];
  115255. });
  115256. };
  115257. module.exports = exports['default'];
  115258. /***/ }),
  115259. /* 17 */
  115260. /***/ (function(module, exports, __webpack_require__) {
  115261. 'use strict';
  115262. exports.__esModule = true;
  115263. var _utils = __webpack_require__(5);
  115264. exports['default'] = function (instance) {
  115265. instance.registerHelper('with', function (context, options) {
  115266. if (_utils.isFunction(context)) {
  115267. context = context.call(this);
  115268. }
  115269. var fn = options.fn;
  115270. if (!_utils.isEmpty(context)) {
  115271. var data = options.data;
  115272. if (options.data && options.ids) {
  115273. data = _utils.createFrame(options.data);
  115274. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  115275. }
  115276. return fn(context, {
  115277. data: data,
  115278. blockParams: _utils.blockParams([context], [data && data.contextPath])
  115279. });
  115280. } else {
  115281. return options.inverse(this);
  115282. }
  115283. });
  115284. };
  115285. module.exports = exports['default'];
  115286. /***/ }),
  115287. /* 18 */
  115288. /***/ (function(module, exports, __webpack_require__) {
  115289. 'use strict';
  115290. var _interopRequireDefault = __webpack_require__(1)['default'];
  115291. exports.__esModule = true;
  115292. exports.registerDefaultDecorators = registerDefaultDecorators;
  115293. var _decoratorsInline = __webpack_require__(19);
  115294. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  115295. function registerDefaultDecorators(instance) {
  115296. _decoratorsInline2['default'](instance);
  115297. }
  115298. /***/ }),
  115299. /* 19 */
  115300. /***/ (function(module, exports, __webpack_require__) {
  115301. 'use strict';
  115302. exports.__esModule = true;
  115303. var _utils = __webpack_require__(5);
  115304. exports['default'] = function (instance) {
  115305. instance.registerDecorator('inline', function (fn, props, container, options) {
  115306. var ret = fn;
  115307. if (!props.partials) {
  115308. props.partials = {};
  115309. ret = function (context, options) {
  115310. // Create a new partials stack frame prior to exec.
  115311. var original = container.partials;
  115312. container.partials = _utils.extend({}, original, props.partials);
  115313. var ret = fn(context, options);
  115314. container.partials = original;
  115315. return ret;
  115316. };
  115317. }
  115318. props.partials[options.args[0]] = options.fn;
  115319. return ret;
  115320. });
  115321. };
  115322. module.exports = exports['default'];
  115323. /***/ }),
  115324. /* 20 */
  115325. /***/ (function(module, exports, __webpack_require__) {
  115326. 'use strict';
  115327. exports.__esModule = true;
  115328. var _utils = __webpack_require__(5);
  115329. var logger = {
  115330. methodMap: ['debug', 'info', 'warn', 'error'],
  115331. level: 'info',
  115332. // Maps a given level value to the `methodMap` indexes above.
  115333. lookupLevel: function lookupLevel(level) {
  115334. if (typeof level === 'string') {
  115335. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  115336. if (levelMap >= 0) {
  115337. level = levelMap;
  115338. } else {
  115339. level = parseInt(level, 10);
  115340. }
  115341. }
  115342. return level;
  115343. },
  115344. // Can be overridden in the host environment
  115345. log: function log(level) {
  115346. level = logger.lookupLevel(level);
  115347. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  115348. var method = logger.methodMap[level];
  115349. if (!console[method]) {
  115350. // eslint-disable-line no-console
  115351. method = 'log';
  115352. }
  115353. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  115354. message[_key - 1] = arguments[_key];
  115355. }
  115356. console[method].apply(console, message); // eslint-disable-line no-console
  115357. }
  115358. }
  115359. };
  115360. exports['default'] = logger;
  115361. module.exports = exports['default'];
  115362. /***/ }),
  115363. /* 21 */
  115364. /***/ (function(module, exports) {
  115365. // Build out our basic SafeString type
  115366. 'use strict';
  115367. exports.__esModule = true;
  115368. function SafeString(string) {
  115369. this.string = string;
  115370. }
  115371. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  115372. return '' + this.string;
  115373. };
  115374. exports['default'] = SafeString;
  115375. module.exports = exports['default'];
  115376. /***/ }),
  115377. /* 22 */
  115378. /***/ (function(module, exports, __webpack_require__) {
  115379. 'use strict';
  115380. var _Object$seal = __webpack_require__(23)['default'];
  115381. var _interopRequireWildcard = __webpack_require__(3)['default'];
  115382. var _interopRequireDefault = __webpack_require__(1)['default'];
  115383. exports.__esModule = true;
  115384. exports.checkRevision = checkRevision;
  115385. exports.template = template;
  115386. exports.wrapProgram = wrapProgram;
  115387. exports.resolvePartial = resolvePartial;
  115388. exports.invokePartial = invokePartial;
  115389. exports.noop = noop;
  115390. var _utils = __webpack_require__(5);
  115391. var Utils = _interopRequireWildcard(_utils);
  115392. var _exception = __webpack_require__(6);
  115393. var _exception2 = _interopRequireDefault(_exception);
  115394. var _base = __webpack_require__(4);
  115395. function checkRevision(compilerInfo) {
  115396. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  115397. currentRevision = _base.COMPILER_REVISION;
  115398. if (compilerRevision !== currentRevision) {
  115399. if (compilerRevision < currentRevision) {
  115400. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  115401. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  115402. 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 + ').');
  115403. } else {
  115404. // Use the embedded version info since the runtime doesn't know about this revision yet
  115405. 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] + ').');
  115406. }
  115407. }
  115408. }
  115409. function template(templateSpec, env) {
  115410. /* istanbul ignore next */
  115411. if (!env) {
  115412. throw new _exception2['default']('No environment passed to template');
  115413. }
  115414. if (!templateSpec || !templateSpec.main) {
  115415. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  115416. }
  115417. templateSpec.main.decorator = templateSpec.main_d;
  115418. // Note: Using env.VM references rather than local var references throughout this section to allow
  115419. // for external users to override these as psuedo-supported APIs.
  115420. env.VM.checkRevision(templateSpec.compiler);
  115421. function invokePartialWrapper(partial, context, options) {
  115422. if (options.hash) {
  115423. context = Utils.extend({}, context, options.hash);
  115424. if (options.ids) {
  115425. options.ids[0] = true;
  115426. }
  115427. }
  115428. partial = env.VM.resolvePartial.call(this, partial, context, options);
  115429. var result = env.VM.invokePartial.call(this, partial, context, options);
  115430. if (result == null && env.compile) {
  115431. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  115432. result = options.partials[options.name](context, options);
  115433. }
  115434. if (result != null) {
  115435. if (options.indent) {
  115436. var lines = result.split('\n');
  115437. for (var i = 0, l = lines.length; i < l; i++) {
  115438. if (!lines[i] && i + 1 === l) {
  115439. break;
  115440. }
  115441. lines[i] = options.indent + lines[i];
  115442. }
  115443. result = lines.join('\n');
  115444. }
  115445. return result;
  115446. } else {
  115447. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  115448. }
  115449. }
  115450. // Just add water
  115451. var container = {
  115452. strict: function strict(obj, name) {
  115453. if (!(name in obj)) {
  115454. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  115455. }
  115456. return obj[name];
  115457. },
  115458. lookup: function lookup(depths, name) {
  115459. var len = depths.length;
  115460. for (var i = 0; i < len; i++) {
  115461. if (depths[i] && depths[i][name] != null) {
  115462. return depths[i][name];
  115463. }
  115464. }
  115465. },
  115466. lambda: function lambda(current, context) {
  115467. return typeof current === 'function' ? current.call(context) : current;
  115468. },
  115469. escapeExpression: Utils.escapeExpression,
  115470. invokePartial: invokePartialWrapper,
  115471. fn: function fn(i) {
  115472. var ret = templateSpec[i];
  115473. ret.decorator = templateSpec[i + '_d'];
  115474. return ret;
  115475. },
  115476. programs: [],
  115477. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  115478. var programWrapper = this.programs[i],
  115479. fn = this.fn(i);
  115480. if (data || depths || blockParams || declaredBlockParams) {
  115481. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  115482. } else if (!programWrapper) {
  115483. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  115484. }
  115485. return programWrapper;
  115486. },
  115487. data: function data(value, depth) {
  115488. while (value && depth--) {
  115489. value = value._parent;
  115490. }
  115491. return value;
  115492. },
  115493. merge: function merge(param, common) {
  115494. var obj = param || common;
  115495. if (param && common && param !== common) {
  115496. obj = Utils.extend({}, common, param);
  115497. }
  115498. return obj;
  115499. },
  115500. // An empty object to use as replacement for null-contexts
  115501. nullContext: _Object$seal({}),
  115502. noop: env.VM.noop,
  115503. compilerInfo: templateSpec.compiler
  115504. };
  115505. function ret(context) {
  115506. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115507. var data = options.data;
  115508. ret._setup(options);
  115509. if (!options.partial && templateSpec.useData) {
  115510. data = initData(context, data);
  115511. }
  115512. var depths = undefined,
  115513. blockParams = templateSpec.useBlockParams ? [] : undefined;
  115514. if (templateSpec.useDepths) {
  115515. if (options.depths) {
  115516. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  115517. } else {
  115518. depths = [context];
  115519. }
  115520. }
  115521. function main(context /*, options*/) {
  115522. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  115523. }
  115524. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  115525. return main(context, options);
  115526. }
  115527. ret.isTop = true;
  115528. ret._setup = function (options) {
  115529. if (!options.partial) {
  115530. container.helpers = container.merge(options.helpers, env.helpers);
  115531. if (templateSpec.usePartial) {
  115532. container.partials = container.merge(options.partials, env.partials);
  115533. }
  115534. if (templateSpec.usePartial || templateSpec.useDecorators) {
  115535. container.decorators = container.merge(options.decorators, env.decorators);
  115536. }
  115537. } else {
  115538. container.helpers = options.helpers;
  115539. container.partials = options.partials;
  115540. container.decorators = options.decorators;
  115541. }
  115542. };
  115543. ret._child = function (i, data, blockParams, depths) {
  115544. if (templateSpec.useBlockParams && !blockParams) {
  115545. throw new _exception2['default']('must pass block params');
  115546. }
  115547. if (templateSpec.useDepths && !depths) {
  115548. throw new _exception2['default']('must pass parent depths');
  115549. }
  115550. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  115551. };
  115552. return ret;
  115553. }
  115554. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  115555. function prog(context) {
  115556. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115557. var currentDepths = depths;
  115558. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  115559. currentDepths = [context].concat(depths);
  115560. }
  115561. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  115562. }
  115563. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  115564. prog.program = i;
  115565. prog.depth = depths ? depths.length : 0;
  115566. prog.blockParams = declaredBlockParams || 0;
  115567. return prog;
  115568. }
  115569. function resolvePartial(partial, context, options) {
  115570. if (!partial) {
  115571. if (options.name === '@partial-block') {
  115572. partial = options.data['partial-block'];
  115573. } else {
  115574. partial = options.partials[options.name];
  115575. }
  115576. } else if (!partial.call && !options.name) {
  115577. // This is a dynamic partial that returned a string
  115578. options.name = partial;
  115579. partial = options.partials[partial];
  115580. }
  115581. return partial;
  115582. }
  115583. function invokePartial(partial, context, options) {
  115584. // Use the current closure context to save the partial-block if this partial
  115585. var currentPartialBlock = options.data && options.data['partial-block'];
  115586. options.partial = true;
  115587. if (options.ids) {
  115588. options.data.contextPath = options.ids[0] || options.data.contextPath;
  115589. }
  115590. var partialBlock = undefined;
  115591. if (options.fn && options.fn !== noop) {
  115592. (function () {
  115593. options.data = _base.createFrame(options.data);
  115594. // Wrapper function to get access to currentPartialBlock from the closure
  115595. var fn = options.fn;
  115596. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  115597. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115598. // Restore the partial-block from the closure for the execution of the block
  115599. // i.e. the part inside the block of the partial call.
  115600. options.data = _base.createFrame(options.data);
  115601. options.data['partial-block'] = currentPartialBlock;
  115602. return fn(context, options);
  115603. };
  115604. if (fn.partials) {
  115605. options.partials = Utils.extend({}, options.partials, fn.partials);
  115606. }
  115607. })();
  115608. }
  115609. if (partial === undefined && partialBlock) {
  115610. partial = partialBlock;
  115611. }
  115612. if (partial === undefined) {
  115613. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  115614. } else if (partial instanceof Function) {
  115615. return partial(context, options);
  115616. }
  115617. }
  115618. function noop() {
  115619. return '';
  115620. }
  115621. function initData(context, data) {
  115622. if (!data || !('root' in data)) {
  115623. data = data ? _base.createFrame(data) : {};
  115624. data.root = context;
  115625. }
  115626. return data;
  115627. }
  115628. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  115629. if (fn.decorator) {
  115630. var props = {};
  115631. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  115632. Utils.extend(prog, props);
  115633. }
  115634. return prog;
  115635. }
  115636. /***/ }),
  115637. /* 23 */
  115638. /***/ (function(module, exports, __webpack_require__) {
  115639. module.exports = { "default": __webpack_require__(24), __esModule: true };
  115640. /***/ }),
  115641. /* 24 */
  115642. /***/ (function(module, exports, __webpack_require__) {
  115643. __webpack_require__(25);
  115644. module.exports = __webpack_require__(30).Object.seal;
  115645. /***/ }),
  115646. /* 25 */
  115647. /***/ (function(module, exports, __webpack_require__) {
  115648. // 19.1.2.17 Object.seal(O)
  115649. var isObject = __webpack_require__(26);
  115650. __webpack_require__(27)('seal', function($seal){
  115651. return function seal(it){
  115652. return $seal && isObject(it) ? $seal(it) : it;
  115653. };
  115654. });
  115655. /***/ }),
  115656. /* 26 */
  115657. /***/ (function(module, exports) {
  115658. module.exports = function(it){
  115659. return typeof it === 'object' ? it !== null : typeof it === 'function';
  115660. };
  115661. /***/ }),
  115662. /* 27 */
  115663. /***/ (function(module, exports, __webpack_require__) {
  115664. // most Object methods by ES6 should accept primitives
  115665. var $export = __webpack_require__(28)
  115666. , core = __webpack_require__(30)
  115667. , fails = __webpack_require__(33);
  115668. module.exports = function(KEY, exec){
  115669. var fn = (core.Object || {})[KEY] || Object[KEY]
  115670. , exp = {};
  115671. exp[KEY] = exec(fn);
  115672. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  115673. };
  115674. /***/ }),
  115675. /* 28 */
  115676. /***/ (function(module, exports, __webpack_require__) {
  115677. var global = __webpack_require__(29)
  115678. , core = __webpack_require__(30)
  115679. , ctx = __webpack_require__(31)
  115680. , PROTOTYPE = 'prototype';
  115681. var $export = function(type, name, source){
  115682. var IS_FORCED = type & $export.F
  115683. , IS_GLOBAL = type & $export.G
  115684. , IS_STATIC = type & $export.S
  115685. , IS_PROTO = type & $export.P
  115686. , IS_BIND = type & $export.B
  115687. , IS_WRAP = type & $export.W
  115688. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  115689. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  115690. , key, own, out;
  115691. if(IS_GLOBAL)source = name;
  115692. for(key in source){
  115693. // contains in native
  115694. own = !IS_FORCED && target && key in target;
  115695. if(own && key in exports)continue;
  115696. // export native or passed
  115697. out = own ? target[key] : source[key];
  115698. // prevent global pollution for namespaces
  115699. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  115700. // bind timers to global for call from export context
  115701. : IS_BIND && own ? ctx(out, global)
  115702. // wrap global constructors for prevent change them in library
  115703. : IS_WRAP && target[key] == out ? (function(C){
  115704. var F = function(param){
  115705. return this instanceof C ? new C(param) : C(param);
  115706. };
  115707. F[PROTOTYPE] = C[PROTOTYPE];
  115708. return F;
  115709. // make static versions for prototype methods
  115710. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  115711. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  115712. }
  115713. };
  115714. // type bitmap
  115715. $export.F = 1; // forced
  115716. $export.G = 2; // global
  115717. $export.S = 4; // static
  115718. $export.P = 8; // proto
  115719. $export.B = 16; // bind
  115720. $export.W = 32; // wrap
  115721. module.exports = $export;
  115722. /***/ }),
  115723. /* 29 */
  115724. /***/ (function(module, exports) {
  115725. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  115726. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  115727. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  115728. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  115729. /***/ }),
  115730. /* 30 */
  115731. /***/ (function(module, exports) {
  115732. var core = module.exports = {version: '1.2.6'};
  115733. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  115734. /***/ }),
  115735. /* 31 */
  115736. /***/ (function(module, exports, __webpack_require__) {
  115737. // optional / simple context binding
  115738. var aFunction = __webpack_require__(32);
  115739. module.exports = function(fn, that, length){
  115740. aFunction(fn);
  115741. if(that === undefined)return fn;
  115742. switch(length){
  115743. case 1: return function(a){
  115744. return fn.call(that, a);
  115745. };
  115746. case 2: return function(a, b){
  115747. return fn.call(that, a, b);
  115748. };
  115749. case 3: return function(a, b, c){
  115750. return fn.call(that, a, b, c);
  115751. };
  115752. }
  115753. return function(/* ...args */){
  115754. return fn.apply(that, arguments);
  115755. };
  115756. };
  115757. /***/ }),
  115758. /* 32 */
  115759. /***/ (function(module, exports) {
  115760. module.exports = function(it){
  115761. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  115762. return it;
  115763. };
  115764. /***/ }),
  115765. /* 33 */
  115766. /***/ (function(module, exports) {
  115767. module.exports = function(exec){
  115768. try {
  115769. return !!exec();
  115770. } catch(e){
  115771. return true;
  115772. }
  115773. };
  115774. /***/ }),
  115775. /* 34 */
  115776. /***/ (function(module, exports) {
  115777. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  115778. 'use strict';
  115779. exports.__esModule = true;
  115780. exports['default'] = function (Handlebars) {
  115781. /* istanbul ignore next */
  115782. var root = typeof global !== 'undefined' ? global : window,
  115783. $Handlebars = root.Handlebars;
  115784. /* istanbul ignore next */
  115785. Handlebars.noConflict = function () {
  115786. if (root.Handlebars === Handlebars) {
  115787. root.Handlebars = $Handlebars;
  115788. }
  115789. return Handlebars;
  115790. };
  115791. };
  115792. module.exports = exports['default'];
  115793. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  115794. /***/ }),
  115795. /* 35 */
  115796. /***/ (function(module, exports) {
  115797. 'use strict';
  115798. exports.__esModule = true;
  115799. var AST = {
  115800. // Public API used to evaluate derived attributes regarding AST nodes
  115801. helpers: {
  115802. // a mustache is definitely a helper if:
  115803. // * it is an eligible helper, and
  115804. // * it has at least one parameter or hash segment
  115805. helperExpression: function helperExpression(node) {
  115806. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  115807. },
  115808. scopedId: function scopedId(path) {
  115809. return (/^\.|this\b/.test(path.original)
  115810. );
  115811. },
  115812. // an ID is simple if it only has one part, and that part is not
  115813. // `..` or `this`.
  115814. simpleId: function simpleId(path) {
  115815. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  115816. }
  115817. }
  115818. };
  115819. // Must be exported as an object rather than the root of the module as the jison lexer
  115820. // must modify the object to operate properly.
  115821. exports['default'] = AST;
  115822. module.exports = exports['default'];
  115823. /***/ }),
  115824. /* 36 */
  115825. /***/ (function(module, exports, __webpack_require__) {
  115826. 'use strict';
  115827. var _interopRequireDefault = __webpack_require__(1)['default'];
  115828. var _interopRequireWildcard = __webpack_require__(3)['default'];
  115829. exports.__esModule = true;
  115830. exports.parse = parse;
  115831. var _parser = __webpack_require__(37);
  115832. var _parser2 = _interopRequireDefault(_parser);
  115833. var _whitespaceControl = __webpack_require__(38);
  115834. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  115835. var _helpers = __webpack_require__(40);
  115836. var Helpers = _interopRequireWildcard(_helpers);
  115837. var _utils = __webpack_require__(5);
  115838. exports.parser = _parser2['default'];
  115839. var yy = {};
  115840. _utils.extend(yy, Helpers);
  115841. function parse(input, options) {
  115842. // Just return if an already-compiled AST was passed in.
  115843. if (input.type === 'Program') {
  115844. return input;
  115845. }
  115846. _parser2['default'].yy = yy;
  115847. // Altering the shared object here, but this is ok as parser is a sync operation
  115848. yy.locInfo = function (locInfo) {
  115849. return new yy.SourceLocation(options && options.srcName, locInfo);
  115850. };
  115851. var strip = new _whitespaceControl2['default'](options);
  115852. return strip.accept(_parser2['default'].parse(input));
  115853. }
  115854. /***/ }),
  115855. /* 37 */
  115856. /***/ (function(module, exports) {
  115857. // File ignored in coverage tests via setting in .istanbul.yml
  115858. /* Jison generated parser */
  115859. "use strict";
  115860. exports.__esModule = true;
  115861. var handlebars = (function () {
  115862. var parser = { trace: function trace() {},
  115863. yy: {},
  115864. 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 },
  115865. 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" },
  115866. 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]],
  115867. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  115868. /**/) {
  115869. var $0 = $$.length - 1;
  115870. switch (yystate) {
  115871. case 1:
  115872. return $$[$0 - 1];
  115873. break;
  115874. case 2:
  115875. this.$ = yy.prepareProgram($$[$0]);
  115876. break;
  115877. case 3:
  115878. this.$ = $$[$0];
  115879. break;
  115880. case 4:
  115881. this.$ = $$[$0];
  115882. break;
  115883. case 5:
  115884. this.$ = $$[$0];
  115885. break;
  115886. case 6:
  115887. this.$ = $$[$0];
  115888. break;
  115889. case 7:
  115890. this.$ = $$[$0];
  115891. break;
  115892. case 8:
  115893. this.$ = $$[$0];
  115894. break;
  115895. case 9:
  115896. this.$ = {
  115897. type: 'CommentStatement',
  115898. value: yy.stripComment($$[$0]),
  115899. strip: yy.stripFlags($$[$0], $$[$0]),
  115900. loc: yy.locInfo(this._$)
  115901. };
  115902. break;
  115903. case 10:
  115904. this.$ = {
  115905. type: 'ContentStatement',
  115906. original: $$[$0],
  115907. value: $$[$0],
  115908. loc: yy.locInfo(this._$)
  115909. };
  115910. break;
  115911. case 11:
  115912. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  115913. break;
  115914. case 12:
  115915. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  115916. break;
  115917. case 13:
  115918. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  115919. break;
  115920. case 14:
  115921. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  115922. break;
  115923. case 15:
  115924. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  115925. break;
  115926. case 16:
  115927. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  115928. break;
  115929. case 17:
  115930. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  115931. break;
  115932. case 18:
  115933. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  115934. break;
  115935. case 19:
  115936. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  115937. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  115938. program.chained = true;
  115939. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  115940. break;
  115941. case 20:
  115942. this.$ = $$[$0];
  115943. break;
  115944. case 21:
  115945. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  115946. break;
  115947. case 22:
  115948. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  115949. break;
  115950. case 23:
  115951. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  115952. break;
  115953. case 24:
  115954. this.$ = {
  115955. type: 'PartialStatement',
  115956. name: $$[$0 - 3],
  115957. params: $$[$0 - 2],
  115958. hash: $$[$0 - 1],
  115959. indent: '',
  115960. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  115961. loc: yy.locInfo(this._$)
  115962. };
  115963. break;
  115964. case 25:
  115965. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  115966. break;
  115967. case 26:
  115968. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  115969. break;
  115970. case 27:
  115971. this.$ = $$[$0];
  115972. break;
  115973. case 28:
  115974. this.$ = $$[$0];
  115975. break;
  115976. case 29:
  115977. this.$ = {
  115978. type: 'SubExpression',
  115979. path: $$[$0 - 3],
  115980. params: $$[$0 - 2],
  115981. hash: $$[$0 - 1],
  115982. loc: yy.locInfo(this._$)
  115983. };
  115984. break;
  115985. case 30:
  115986. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  115987. break;
  115988. case 31:
  115989. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  115990. break;
  115991. case 32:
  115992. this.$ = yy.id($$[$0 - 1]);
  115993. break;
  115994. case 33:
  115995. this.$ = $$[$0];
  115996. break;
  115997. case 34:
  115998. this.$ = $$[$0];
  115999. break;
  116000. case 35:
  116001. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  116002. break;
  116003. case 36:
  116004. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  116005. break;
  116006. case 37:
  116007. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  116008. break;
  116009. case 38:
  116010. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  116011. break;
  116012. case 39:
  116013. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  116014. break;
  116015. case 40:
  116016. this.$ = $$[$0];
  116017. break;
  116018. case 41:
  116019. this.$ = $$[$0];
  116020. break;
  116021. case 42:
  116022. this.$ = yy.preparePath(true, $$[$0], this._$);
  116023. break;
  116024. case 43:
  116025. this.$ = yy.preparePath(false, $$[$0], this._$);
  116026. break;
  116027. case 44:
  116028. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  116029. break;
  116030. case 45:
  116031. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  116032. break;
  116033. case 46:
  116034. this.$ = [];
  116035. break;
  116036. case 47:
  116037. $$[$0 - 1].push($$[$0]);
  116038. break;
  116039. case 48:
  116040. this.$ = [$$[$0]];
  116041. break;
  116042. case 49:
  116043. $$[$0 - 1].push($$[$0]);
  116044. break;
  116045. case 50:
  116046. this.$ = [];
  116047. break;
  116048. case 51:
  116049. $$[$0 - 1].push($$[$0]);
  116050. break;
  116051. case 58:
  116052. this.$ = [];
  116053. break;
  116054. case 59:
  116055. $$[$0 - 1].push($$[$0]);
  116056. break;
  116057. case 64:
  116058. this.$ = [];
  116059. break;
  116060. case 65:
  116061. $$[$0 - 1].push($$[$0]);
  116062. break;
  116063. case 70:
  116064. this.$ = [];
  116065. break;
  116066. case 71:
  116067. $$[$0 - 1].push($$[$0]);
  116068. break;
  116069. case 78:
  116070. this.$ = [];
  116071. break;
  116072. case 79:
  116073. $$[$0 - 1].push($$[$0]);
  116074. break;
  116075. case 82:
  116076. this.$ = [];
  116077. break;
  116078. case 83:
  116079. $$[$0 - 1].push($$[$0]);
  116080. break;
  116081. case 86:
  116082. this.$ = [];
  116083. break;
  116084. case 87:
  116085. $$[$0 - 1].push($$[$0]);
  116086. break;
  116087. case 90:
  116088. this.$ = [];
  116089. break;
  116090. case 91:
  116091. $$[$0 - 1].push($$[$0]);
  116092. break;
  116093. case 94:
  116094. this.$ = [];
  116095. break;
  116096. case 95:
  116097. $$[$0 - 1].push($$[$0]);
  116098. break;
  116099. case 98:
  116100. this.$ = [$$[$0]];
  116101. break;
  116102. case 99:
  116103. $$[$0 - 1].push($$[$0]);
  116104. break;
  116105. case 100:
  116106. this.$ = [$$[$0]];
  116107. break;
  116108. case 101:
  116109. $$[$0 - 1].push($$[$0]);
  116110. break;
  116111. }
  116112. },
  116113. 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] }],
  116114. 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] },
  116115. parseError: function parseError(str, hash) {
  116116. throw new Error(str);
  116117. },
  116118. parse: function parse(input) {
  116119. var self = this,
  116120. stack = [0],
  116121. vstack = [null],
  116122. lstack = [],
  116123. table = this.table,
  116124. yytext = "",
  116125. yylineno = 0,
  116126. yyleng = 0,
  116127. recovering = 0,
  116128. TERROR = 2,
  116129. EOF = 1;
  116130. this.lexer.setInput(input);
  116131. this.lexer.yy = this.yy;
  116132. this.yy.lexer = this.lexer;
  116133. this.yy.parser = this;
  116134. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  116135. var yyloc = this.lexer.yylloc;
  116136. lstack.push(yyloc);
  116137. var ranges = this.lexer.options && this.lexer.options.ranges;
  116138. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  116139. function popStack(n) {
  116140. stack.length = stack.length - 2 * n;
  116141. vstack.length = vstack.length - n;
  116142. lstack.length = lstack.length - n;
  116143. }
  116144. function lex() {
  116145. var token;
  116146. token = self.lexer.lex() || 1;
  116147. if (typeof token !== "number") {
  116148. token = self.symbols_[token] || token;
  116149. }
  116150. return token;
  116151. }
  116152. var symbol,
  116153. preErrorSymbol,
  116154. state,
  116155. action,
  116156. a,
  116157. r,
  116158. yyval = {},
  116159. p,
  116160. len,
  116161. newState,
  116162. expected;
  116163. while (true) {
  116164. state = stack[stack.length - 1];
  116165. if (this.defaultActions[state]) {
  116166. action = this.defaultActions[state];
  116167. } else {
  116168. if (symbol === null || typeof symbol == "undefined") {
  116169. symbol = lex();
  116170. }
  116171. action = table[state] && table[state][symbol];
  116172. }
  116173. if (typeof action === "undefined" || !action.length || !action[0]) {
  116174. var errStr = "";
  116175. if (!recovering) {
  116176. expected = [];
  116177. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  116178. expected.push("'" + this.terminals_[p] + "'");
  116179. }
  116180. if (this.lexer.showPosition) {
  116181. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  116182. } else {
  116183. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  116184. }
  116185. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  116186. }
  116187. }
  116188. if (action[0] instanceof Array && action.length > 1) {
  116189. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  116190. }
  116191. switch (action[0]) {
  116192. case 1:
  116193. stack.push(symbol);
  116194. vstack.push(this.lexer.yytext);
  116195. lstack.push(this.lexer.yylloc);
  116196. stack.push(action[1]);
  116197. symbol = null;
  116198. if (!preErrorSymbol) {
  116199. yyleng = this.lexer.yyleng;
  116200. yytext = this.lexer.yytext;
  116201. yylineno = this.lexer.yylineno;
  116202. yyloc = this.lexer.yylloc;
  116203. if (recovering > 0) recovering--;
  116204. } else {
  116205. symbol = preErrorSymbol;
  116206. preErrorSymbol = null;
  116207. }
  116208. break;
  116209. case 2:
  116210. len = this.productions_[action[1]][1];
  116211. yyval.$ = vstack[vstack.length - len];
  116212. 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 };
  116213. if (ranges) {
  116214. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  116215. }
  116216. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  116217. if (typeof r !== "undefined") {
  116218. return r;
  116219. }
  116220. if (len) {
  116221. stack = stack.slice(0, -1 * len * 2);
  116222. vstack = vstack.slice(0, -1 * len);
  116223. lstack = lstack.slice(0, -1 * len);
  116224. }
  116225. stack.push(this.productions_[action[1]][0]);
  116226. vstack.push(yyval.$);
  116227. lstack.push(yyval._$);
  116228. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  116229. stack.push(newState);
  116230. break;
  116231. case 3:
  116232. return true;
  116233. }
  116234. }
  116235. return true;
  116236. }
  116237. };
  116238. /* Jison generated lexer */
  116239. var lexer = (function () {
  116240. var lexer = { EOF: 1,
  116241. parseError: function parseError(str, hash) {
  116242. if (this.yy.parser) {
  116243. this.yy.parser.parseError(str, hash);
  116244. } else {
  116245. throw new Error(str);
  116246. }
  116247. },
  116248. setInput: function setInput(input) {
  116249. this._input = input;
  116250. this._more = this._less = this.done = false;
  116251. this.yylineno = this.yyleng = 0;
  116252. this.yytext = this.matched = this.match = '';
  116253. this.conditionStack = ['INITIAL'];
  116254. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  116255. if (this.options.ranges) this.yylloc.range = [0, 0];
  116256. this.offset = 0;
  116257. return this;
  116258. },
  116259. input: function input() {
  116260. var ch = this._input[0];
  116261. this.yytext += ch;
  116262. this.yyleng++;
  116263. this.offset++;
  116264. this.match += ch;
  116265. this.matched += ch;
  116266. var lines = ch.match(/(?:\r\n?|\n).*/g);
  116267. if (lines) {
  116268. this.yylineno++;
  116269. this.yylloc.last_line++;
  116270. } else {
  116271. this.yylloc.last_column++;
  116272. }
  116273. if (this.options.ranges) this.yylloc.range[1]++;
  116274. this._input = this._input.slice(1);
  116275. return ch;
  116276. },
  116277. unput: function unput(ch) {
  116278. var len = ch.length;
  116279. var lines = ch.split(/(?:\r\n?|\n)/g);
  116280. this._input = ch + this._input;
  116281. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  116282. //this.yyleng -= len;
  116283. this.offset -= len;
  116284. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  116285. this.match = this.match.substr(0, this.match.length - 1);
  116286. this.matched = this.matched.substr(0, this.matched.length - 1);
  116287. if (lines.length - 1) this.yylineno -= lines.length - 1;
  116288. var r = this.yylloc.range;
  116289. this.yylloc = { first_line: this.yylloc.first_line,
  116290. last_line: this.yylineno + 1,
  116291. first_column: this.yylloc.first_column,
  116292. 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
  116293. };
  116294. if (this.options.ranges) {
  116295. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  116296. }
  116297. return this;
  116298. },
  116299. more: function more() {
  116300. this._more = true;
  116301. return this;
  116302. },
  116303. less: function less(n) {
  116304. this.unput(this.match.slice(n));
  116305. },
  116306. pastInput: function pastInput() {
  116307. var past = this.matched.substr(0, this.matched.length - this.match.length);
  116308. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  116309. },
  116310. upcomingInput: function upcomingInput() {
  116311. var next = this.match;
  116312. if (next.length < 20) {
  116313. next += this._input.substr(0, 20 - next.length);
  116314. }
  116315. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  116316. },
  116317. showPosition: function showPosition() {
  116318. var pre = this.pastInput();
  116319. var c = new Array(pre.length + 1).join("-");
  116320. return pre + this.upcomingInput() + "\n" + c + "^";
  116321. },
  116322. next: function next() {
  116323. if (this.done) {
  116324. return this.EOF;
  116325. }
  116326. if (!this._input) this.done = true;
  116327. var token, match, tempMatch, index, col, lines;
  116328. if (!this._more) {
  116329. this.yytext = '';
  116330. this.match = '';
  116331. }
  116332. var rules = this._currentRules();
  116333. for (var i = 0; i < rules.length; i++) {
  116334. tempMatch = this._input.match(this.rules[rules[i]]);
  116335. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  116336. match = tempMatch;
  116337. index = i;
  116338. if (!this.options.flex) break;
  116339. }
  116340. }
  116341. if (match) {
  116342. lines = match[0].match(/(?:\r\n?|\n).*/g);
  116343. if (lines) this.yylineno += lines.length;
  116344. this.yylloc = { first_line: this.yylloc.last_line,
  116345. last_line: this.yylineno + 1,
  116346. first_column: this.yylloc.last_column,
  116347. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  116348. this.yytext += match[0];
  116349. this.match += match[0];
  116350. this.matches = match;
  116351. this.yyleng = this.yytext.length;
  116352. if (this.options.ranges) {
  116353. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  116354. }
  116355. this._more = false;
  116356. this._input = this._input.slice(match[0].length);
  116357. this.matched += match[0];
  116358. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  116359. if (this.done && this._input) this.done = false;
  116360. if (token) return token;else return;
  116361. }
  116362. if (this._input === "") {
  116363. return this.EOF;
  116364. } else {
  116365. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  116366. }
  116367. },
  116368. lex: function lex() {
  116369. var r = this.next();
  116370. if (typeof r !== 'undefined') {
  116371. return r;
  116372. } else {
  116373. return this.lex();
  116374. }
  116375. },
  116376. begin: function begin(condition) {
  116377. this.conditionStack.push(condition);
  116378. },
  116379. popState: function popState() {
  116380. return this.conditionStack.pop();
  116381. },
  116382. _currentRules: function _currentRules() {
  116383. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  116384. },
  116385. topState: function topState() {
  116386. return this.conditionStack[this.conditionStack.length - 2];
  116387. },
  116388. pushState: function begin(condition) {
  116389. this.begin(condition);
  116390. } };
  116391. lexer.options = {};
  116392. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  116393. /**/) {
  116394. function strip(start, end) {
  116395. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  116396. }
  116397. var YYSTATE = YY_START;
  116398. switch ($avoiding_name_collisions) {
  116399. case 0:
  116400. if (yy_.yytext.slice(-2) === "\\\\") {
  116401. strip(0, 1);
  116402. this.begin("mu");
  116403. } else if (yy_.yytext.slice(-1) === "\\") {
  116404. strip(0, 1);
  116405. this.begin("emu");
  116406. } else {
  116407. this.begin("mu");
  116408. }
  116409. if (yy_.yytext) return 15;
  116410. break;
  116411. case 1:
  116412. return 15;
  116413. break;
  116414. case 2:
  116415. this.popState();
  116416. return 15;
  116417. break;
  116418. case 3:
  116419. this.begin('raw');return 15;
  116420. break;
  116421. case 4:
  116422. this.popState();
  116423. // Should be using `this.topState()` below, but it currently
  116424. // returns the second top instead of the first top. Opened an
  116425. // issue about it at https://github.com/zaach/jison/issues/291
  116426. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  116427. return 15;
  116428. } else {
  116429. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  116430. return 'END_RAW_BLOCK';
  116431. }
  116432. break;
  116433. case 5:
  116434. return 15;
  116435. break;
  116436. case 6:
  116437. this.popState();
  116438. return 14;
  116439. break;
  116440. case 7:
  116441. return 65;
  116442. break;
  116443. case 8:
  116444. return 68;
  116445. break;
  116446. case 9:
  116447. return 19;
  116448. break;
  116449. case 10:
  116450. this.popState();
  116451. this.begin('raw');
  116452. return 23;
  116453. break;
  116454. case 11:
  116455. return 55;
  116456. break;
  116457. case 12:
  116458. return 60;
  116459. break;
  116460. case 13:
  116461. return 29;
  116462. break;
  116463. case 14:
  116464. return 47;
  116465. break;
  116466. case 15:
  116467. this.popState();return 44;
  116468. break;
  116469. case 16:
  116470. this.popState();return 44;
  116471. break;
  116472. case 17:
  116473. return 34;
  116474. break;
  116475. case 18:
  116476. return 39;
  116477. break;
  116478. case 19:
  116479. return 51;
  116480. break;
  116481. case 20:
  116482. return 48;
  116483. break;
  116484. case 21:
  116485. this.unput(yy_.yytext);
  116486. this.popState();
  116487. this.begin('com');
  116488. break;
  116489. case 22:
  116490. this.popState();
  116491. return 14;
  116492. break;
  116493. case 23:
  116494. return 48;
  116495. break;
  116496. case 24:
  116497. return 73;
  116498. break;
  116499. case 25:
  116500. return 72;
  116501. break;
  116502. case 26:
  116503. return 72;
  116504. break;
  116505. case 27:
  116506. return 87;
  116507. break;
  116508. case 28:
  116509. // ignore whitespace
  116510. break;
  116511. case 29:
  116512. this.popState();return 54;
  116513. break;
  116514. case 30:
  116515. this.popState();return 33;
  116516. break;
  116517. case 31:
  116518. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  116519. break;
  116520. case 32:
  116521. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  116522. break;
  116523. case 33:
  116524. return 85;
  116525. break;
  116526. case 34:
  116527. return 82;
  116528. break;
  116529. case 35:
  116530. return 82;
  116531. break;
  116532. case 36:
  116533. return 83;
  116534. break;
  116535. case 37:
  116536. return 84;
  116537. break;
  116538. case 38:
  116539. return 81;
  116540. break;
  116541. case 39:
  116542. return 75;
  116543. break;
  116544. case 40:
  116545. return 77;
  116546. break;
  116547. case 41:
  116548. return 72;
  116549. break;
  116550. case 42:
  116551. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  116552. break;
  116553. case 43:
  116554. return 'INVALID';
  116555. break;
  116556. case 44:
  116557. return 5;
  116558. break;
  116559. }
  116560. };
  116561. 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\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  116562. 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 } };
  116563. return lexer;
  116564. })();
  116565. parser.lexer = lexer;
  116566. function Parser() {
  116567. this.yy = {};
  116568. }Parser.prototype = parser;parser.Parser = Parser;
  116569. return new Parser();
  116570. })();exports["default"] = handlebars;
  116571. module.exports = exports["default"];
  116572. /***/ }),
  116573. /* 38 */
  116574. /***/ (function(module, exports, __webpack_require__) {
  116575. 'use strict';
  116576. var _interopRequireDefault = __webpack_require__(1)['default'];
  116577. exports.__esModule = true;
  116578. var _visitor = __webpack_require__(39);
  116579. var _visitor2 = _interopRequireDefault(_visitor);
  116580. function WhitespaceControl() {
  116581. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  116582. this.options = options;
  116583. }
  116584. WhitespaceControl.prototype = new _visitor2['default']();
  116585. WhitespaceControl.prototype.Program = function (program) {
  116586. var doStandalone = !this.options.ignoreStandalone;
  116587. var isRoot = !this.isRootSeen;
  116588. this.isRootSeen = true;
  116589. var body = program.body;
  116590. for (var i = 0, l = body.length; i < l; i++) {
  116591. var current = body[i],
  116592. strip = this.accept(current);
  116593. if (!strip) {
  116594. continue;
  116595. }
  116596. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  116597. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  116598. openStandalone = strip.openStandalone && _isPrevWhitespace,
  116599. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  116600. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  116601. if (strip.close) {
  116602. omitRight(body, i, true);
  116603. }
  116604. if (strip.open) {
  116605. omitLeft(body, i, true);
  116606. }
  116607. if (doStandalone && inlineStandalone) {
  116608. omitRight(body, i);
  116609. if (omitLeft(body, i)) {
  116610. // If we are on a standalone node, save the indent info for partials
  116611. if (current.type === 'PartialStatement') {
  116612. // Pull out the whitespace from the final line
  116613. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  116614. }
  116615. }
  116616. }
  116617. if (doStandalone && openStandalone) {
  116618. omitRight((current.program || current.inverse).body);
  116619. // Strip out the previous content node if it's whitespace only
  116620. omitLeft(body, i);
  116621. }
  116622. if (doStandalone && closeStandalone) {
  116623. // Always strip the next node
  116624. omitRight(body, i);
  116625. omitLeft((current.inverse || current.program).body);
  116626. }
  116627. }
  116628. return program;
  116629. };
  116630. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  116631. this.accept(block.program);
  116632. this.accept(block.inverse);
  116633. // Find the inverse program that is involed with whitespace stripping.
  116634. var program = block.program || block.inverse,
  116635. inverse = block.program && block.inverse,
  116636. firstInverse = inverse,
  116637. lastInverse = inverse;
  116638. if (inverse && inverse.chained) {
  116639. firstInverse = inverse.body[0].program;
  116640. // Walk the inverse chain to find the last inverse that is actually in the chain.
  116641. while (lastInverse.chained) {
  116642. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  116643. }
  116644. }
  116645. var strip = {
  116646. open: block.openStrip.open,
  116647. close: block.closeStrip.close,
  116648. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  116649. // so our parent can determine if we actually are standalone
  116650. openStandalone: isNextWhitespace(program.body),
  116651. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  116652. };
  116653. if (block.openStrip.close) {
  116654. omitRight(program.body, null, true);
  116655. }
  116656. if (inverse) {
  116657. var inverseStrip = block.inverseStrip;
  116658. if (inverseStrip.open) {
  116659. omitLeft(program.body, null, true);
  116660. }
  116661. if (inverseStrip.close) {
  116662. omitRight(firstInverse.body, null, true);
  116663. }
  116664. if (block.closeStrip.open) {
  116665. omitLeft(lastInverse.body, null, true);
  116666. }
  116667. // Find standalone else statments
  116668. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  116669. omitLeft(program.body);
  116670. omitRight(firstInverse.body);
  116671. }
  116672. } else if (block.closeStrip.open) {
  116673. omitLeft(program.body, null, true);
  116674. }
  116675. return strip;
  116676. };
  116677. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  116678. return mustache.strip;
  116679. };
  116680. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  116681. /* istanbul ignore next */
  116682. var strip = node.strip || {};
  116683. return {
  116684. inlineStandalone: true,
  116685. open: strip.open,
  116686. close: strip.close
  116687. };
  116688. };
  116689. function isPrevWhitespace(body, i, isRoot) {
  116690. if (i === undefined) {
  116691. i = body.length;
  116692. }
  116693. // Nodes that end with newlines are considered whitespace (but are special
  116694. // cased for strip operations)
  116695. var prev = body[i - 1],
  116696. sibling = body[i - 2];
  116697. if (!prev) {
  116698. return isRoot;
  116699. }
  116700. if (prev.type === 'ContentStatement') {
  116701. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  116702. }
  116703. }
  116704. function isNextWhitespace(body, i, isRoot) {
  116705. if (i === undefined) {
  116706. i = -1;
  116707. }
  116708. var next = body[i + 1],
  116709. sibling = body[i + 2];
  116710. if (!next) {
  116711. return isRoot;
  116712. }
  116713. if (next.type === 'ContentStatement') {
  116714. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  116715. }
  116716. }
  116717. // Marks the node to the right of the position as omitted.
  116718. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  116719. //
  116720. // If i is undefined, then the first child will be marked as such.
  116721. //
  116722. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  116723. // content is met.
  116724. function omitRight(body, i, multiple) {
  116725. var current = body[i == null ? 0 : i + 1];
  116726. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  116727. return;
  116728. }
  116729. var original = current.value;
  116730. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  116731. current.rightStripped = current.value !== original;
  116732. }
  116733. // Marks the node to the left of the position as omitted.
  116734. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  116735. //
  116736. // If i is undefined then the last child will be marked as such.
  116737. //
  116738. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  116739. // content is met.
  116740. function omitLeft(body, i, multiple) {
  116741. var current = body[i == null ? body.length - 1 : i - 1];
  116742. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  116743. return;
  116744. }
  116745. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  116746. var original = current.value;
  116747. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  116748. current.leftStripped = current.value !== original;
  116749. return current.leftStripped;
  116750. }
  116751. exports['default'] = WhitespaceControl;
  116752. module.exports = exports['default'];
  116753. /***/ }),
  116754. /* 39 */
  116755. /***/ (function(module, exports, __webpack_require__) {
  116756. 'use strict';
  116757. var _interopRequireDefault = __webpack_require__(1)['default'];
  116758. exports.__esModule = true;
  116759. var _exception = __webpack_require__(6);
  116760. var _exception2 = _interopRequireDefault(_exception);
  116761. function Visitor() {
  116762. this.parents = [];
  116763. }
  116764. Visitor.prototype = {
  116765. constructor: Visitor,
  116766. mutating: false,
  116767. // Visits a given value. If mutating, will replace the value if necessary.
  116768. acceptKey: function acceptKey(node, name) {
  116769. var value = this.accept(node[name]);
  116770. if (this.mutating) {
  116771. // Hacky sanity check: This may have a few false positives for type for the helper
  116772. // methods but will generally do the right thing without a lot of overhead.
  116773. if (value && !Visitor.prototype[value.type]) {
  116774. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  116775. }
  116776. node[name] = value;
  116777. }
  116778. },
  116779. // Performs an accept operation with added sanity check to ensure
  116780. // required keys are not removed.
  116781. acceptRequired: function acceptRequired(node, name) {
  116782. this.acceptKey(node, name);
  116783. if (!node[name]) {
  116784. throw new _exception2['default'](node.type + ' requires ' + name);
  116785. }
  116786. },
  116787. // Traverses a given array. If mutating, empty respnses will be removed
  116788. // for child elements.
  116789. acceptArray: function acceptArray(array) {
  116790. for (var i = 0, l = array.length; i < l; i++) {
  116791. this.acceptKey(array, i);
  116792. if (!array[i]) {
  116793. array.splice(i, 1);
  116794. i--;
  116795. l--;
  116796. }
  116797. }
  116798. },
  116799. accept: function accept(object) {
  116800. if (!object) {
  116801. return;
  116802. }
  116803. /* istanbul ignore next: Sanity code */
  116804. if (!this[object.type]) {
  116805. throw new _exception2['default']('Unknown type: ' + object.type, object);
  116806. }
  116807. if (this.current) {
  116808. this.parents.unshift(this.current);
  116809. }
  116810. this.current = object;
  116811. var ret = this[object.type](object);
  116812. this.current = this.parents.shift();
  116813. if (!this.mutating || ret) {
  116814. return ret;
  116815. } else if (ret !== false) {
  116816. return object;
  116817. }
  116818. },
  116819. Program: function Program(program) {
  116820. this.acceptArray(program.body);
  116821. },
  116822. MustacheStatement: visitSubExpression,
  116823. Decorator: visitSubExpression,
  116824. BlockStatement: visitBlock,
  116825. DecoratorBlock: visitBlock,
  116826. PartialStatement: visitPartial,
  116827. PartialBlockStatement: function PartialBlockStatement(partial) {
  116828. visitPartial.call(this, partial);
  116829. this.acceptKey(partial, 'program');
  116830. },
  116831. ContentStatement: function ContentStatement() /* content */{},
  116832. CommentStatement: function CommentStatement() /* comment */{},
  116833. SubExpression: visitSubExpression,
  116834. PathExpression: function PathExpression() /* path */{},
  116835. StringLiteral: function StringLiteral() /* string */{},
  116836. NumberLiteral: function NumberLiteral() /* number */{},
  116837. BooleanLiteral: function BooleanLiteral() /* bool */{},
  116838. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  116839. NullLiteral: function NullLiteral() /* literal */{},
  116840. Hash: function Hash(hash) {
  116841. this.acceptArray(hash.pairs);
  116842. },
  116843. HashPair: function HashPair(pair) {
  116844. this.acceptRequired(pair, 'value');
  116845. }
  116846. };
  116847. function visitSubExpression(mustache) {
  116848. this.acceptRequired(mustache, 'path');
  116849. this.acceptArray(mustache.params);
  116850. this.acceptKey(mustache, 'hash');
  116851. }
  116852. function visitBlock(block) {
  116853. visitSubExpression.call(this, block);
  116854. this.acceptKey(block, 'program');
  116855. this.acceptKey(block, 'inverse');
  116856. }
  116857. function visitPartial(partial) {
  116858. this.acceptRequired(partial, 'name');
  116859. this.acceptArray(partial.params);
  116860. this.acceptKey(partial, 'hash');
  116861. }
  116862. exports['default'] = Visitor;
  116863. module.exports = exports['default'];
  116864. /***/ }),
  116865. /* 40 */
  116866. /***/ (function(module, exports, __webpack_require__) {
  116867. 'use strict';
  116868. var _interopRequireDefault = __webpack_require__(1)['default'];
  116869. exports.__esModule = true;
  116870. exports.SourceLocation = SourceLocation;
  116871. exports.id = id;
  116872. exports.stripFlags = stripFlags;
  116873. exports.stripComment = stripComment;
  116874. exports.preparePath = preparePath;
  116875. exports.prepareMustache = prepareMustache;
  116876. exports.prepareRawBlock = prepareRawBlock;
  116877. exports.prepareBlock = prepareBlock;
  116878. exports.prepareProgram = prepareProgram;
  116879. exports.preparePartialBlock = preparePartialBlock;
  116880. var _exception = __webpack_require__(6);
  116881. var _exception2 = _interopRequireDefault(_exception);
  116882. function validateClose(open, close) {
  116883. close = close.path ? close.path.original : close;
  116884. if (open.path.original !== close) {
  116885. var errorNode = { loc: open.path.loc };
  116886. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  116887. }
  116888. }
  116889. function SourceLocation(source, locInfo) {
  116890. this.source = source;
  116891. this.start = {
  116892. line: locInfo.first_line,
  116893. column: locInfo.first_column
  116894. };
  116895. this.end = {
  116896. line: locInfo.last_line,
  116897. column: locInfo.last_column
  116898. };
  116899. }
  116900. function id(token) {
  116901. if (/^\[.*\]$/.test(token)) {
  116902. return token.substr(1, token.length - 2);
  116903. } else {
  116904. return token;
  116905. }
  116906. }
  116907. function stripFlags(open, close) {
  116908. return {
  116909. open: open.charAt(2) === '~',
  116910. close: close.charAt(close.length - 3) === '~'
  116911. };
  116912. }
  116913. function stripComment(comment) {
  116914. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  116915. }
  116916. function preparePath(data, parts, loc) {
  116917. loc = this.locInfo(loc);
  116918. var original = data ? '@' : '',
  116919. dig = [],
  116920. depth = 0,
  116921. depthString = '';
  116922. for (var i = 0, l = parts.length; i < l; i++) {
  116923. var part = parts[i].part,
  116924. // If we have [] syntax then we do not treat path references as operators,
  116925. // i.e. foo.[this] resolves to approximately context.foo['this']
  116926. isLiteral = parts[i].original !== part;
  116927. original += (parts[i].separator || '') + part;
  116928. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  116929. if (dig.length > 0) {
  116930. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  116931. } else if (part === '..') {
  116932. depth++;
  116933. depthString += '../';
  116934. }
  116935. } else {
  116936. dig.push(part);
  116937. }
  116938. }
  116939. return {
  116940. type: 'PathExpression',
  116941. data: data,
  116942. depth: depth,
  116943. parts: dig,
  116944. original: original,
  116945. loc: loc
  116946. };
  116947. }
  116948. function prepareMustache(path, params, hash, open, strip, locInfo) {
  116949. // Must use charAt to support IE pre-10
  116950. var escapeFlag = open.charAt(3) || open.charAt(2),
  116951. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  116952. var decorator = /\*/.test(open);
  116953. return {
  116954. type: decorator ? 'Decorator' : 'MustacheStatement',
  116955. path: path,
  116956. params: params,
  116957. hash: hash,
  116958. escaped: escaped,
  116959. strip: strip,
  116960. loc: this.locInfo(locInfo)
  116961. };
  116962. }
  116963. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  116964. validateClose(openRawBlock, close);
  116965. locInfo = this.locInfo(locInfo);
  116966. var program = {
  116967. type: 'Program',
  116968. body: contents,
  116969. strip: {},
  116970. loc: locInfo
  116971. };
  116972. return {
  116973. type: 'BlockStatement',
  116974. path: openRawBlock.path,
  116975. params: openRawBlock.params,
  116976. hash: openRawBlock.hash,
  116977. program: program,
  116978. openStrip: {},
  116979. inverseStrip: {},
  116980. closeStrip: {},
  116981. loc: locInfo
  116982. };
  116983. }
  116984. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  116985. if (close && close.path) {
  116986. validateClose(openBlock, close);
  116987. }
  116988. var decorator = /\*/.test(openBlock.open);
  116989. program.blockParams = openBlock.blockParams;
  116990. var inverse = undefined,
  116991. inverseStrip = undefined;
  116992. if (inverseAndProgram) {
  116993. if (decorator) {
  116994. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  116995. }
  116996. if (inverseAndProgram.chain) {
  116997. inverseAndProgram.program.body[0].closeStrip = close.strip;
  116998. }
  116999. inverseStrip = inverseAndProgram.strip;
  117000. inverse = inverseAndProgram.program;
  117001. }
  117002. if (inverted) {
  117003. inverted = inverse;
  117004. inverse = program;
  117005. program = inverted;
  117006. }
  117007. return {
  117008. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  117009. path: openBlock.path,
  117010. params: openBlock.params,
  117011. hash: openBlock.hash,
  117012. program: program,
  117013. inverse: inverse,
  117014. openStrip: openBlock.strip,
  117015. inverseStrip: inverseStrip,
  117016. closeStrip: close && close.strip,
  117017. loc: this.locInfo(locInfo)
  117018. };
  117019. }
  117020. function prepareProgram(statements, loc) {
  117021. if (!loc && statements.length) {
  117022. var firstLoc = statements[0].loc,
  117023. lastLoc = statements[statements.length - 1].loc;
  117024. /* istanbul ignore else */
  117025. if (firstLoc && lastLoc) {
  117026. loc = {
  117027. source: firstLoc.source,
  117028. start: {
  117029. line: firstLoc.start.line,
  117030. column: firstLoc.start.column
  117031. },
  117032. end: {
  117033. line: lastLoc.end.line,
  117034. column: lastLoc.end.column
  117035. }
  117036. };
  117037. }
  117038. }
  117039. return {
  117040. type: 'Program',
  117041. body: statements,
  117042. strip: {},
  117043. loc: loc
  117044. };
  117045. }
  117046. function preparePartialBlock(open, program, close, locInfo) {
  117047. validateClose(open, close);
  117048. return {
  117049. type: 'PartialBlockStatement',
  117050. name: open.path,
  117051. params: open.params,
  117052. hash: open.hash,
  117053. program: program,
  117054. openStrip: open.strip,
  117055. closeStrip: close && close.strip,
  117056. loc: this.locInfo(locInfo)
  117057. };
  117058. }
  117059. /***/ }),
  117060. /* 41 */
  117061. /***/ (function(module, exports, __webpack_require__) {
  117062. /* eslint-disable new-cap */
  117063. 'use strict';
  117064. var _interopRequireDefault = __webpack_require__(1)['default'];
  117065. exports.__esModule = true;
  117066. exports.Compiler = Compiler;
  117067. exports.precompile = precompile;
  117068. exports.compile = compile;
  117069. var _exception = __webpack_require__(6);
  117070. var _exception2 = _interopRequireDefault(_exception);
  117071. var _utils = __webpack_require__(5);
  117072. var _ast = __webpack_require__(35);
  117073. var _ast2 = _interopRequireDefault(_ast);
  117074. var slice = [].slice;
  117075. function Compiler() {}
  117076. // the foundHelper register will disambiguate helper lookup from finding a
  117077. // function in a context. This is necessary for mustache compatibility, which
  117078. // requires that context functions in blocks are evaluated by blockHelperMissing,
  117079. // and then proceed as if the resulting value was provided to blockHelperMissing.
  117080. Compiler.prototype = {
  117081. compiler: Compiler,
  117082. equals: function equals(other) {
  117083. var len = this.opcodes.length;
  117084. if (other.opcodes.length !== len) {
  117085. return false;
  117086. }
  117087. for (var i = 0; i < len; i++) {
  117088. var opcode = this.opcodes[i],
  117089. otherOpcode = other.opcodes[i];
  117090. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  117091. return false;
  117092. }
  117093. }
  117094. // We know that length is the same between the two arrays because they are directly tied
  117095. // to the opcode behavior above.
  117096. len = this.children.length;
  117097. for (var i = 0; i < len; i++) {
  117098. if (!this.children[i].equals(other.children[i])) {
  117099. return false;
  117100. }
  117101. }
  117102. return true;
  117103. },
  117104. guid: 0,
  117105. compile: function compile(program, options) {
  117106. this.sourceNode = [];
  117107. this.opcodes = [];
  117108. this.children = [];
  117109. this.options = options;
  117110. this.stringParams = options.stringParams;
  117111. this.trackIds = options.trackIds;
  117112. options.blockParams = options.blockParams || [];
  117113. // These changes will propagate to the other compiler components
  117114. var knownHelpers = options.knownHelpers;
  117115. options.knownHelpers = {
  117116. 'helperMissing': true,
  117117. 'blockHelperMissing': true,
  117118. 'each': true,
  117119. 'if': true,
  117120. 'unless': true,
  117121. 'with': true,
  117122. 'log': true,
  117123. 'lookup': true
  117124. };
  117125. if (knownHelpers) {
  117126. for (var _name in knownHelpers) {
  117127. /* istanbul ignore else */
  117128. if (_name in knownHelpers) {
  117129. this.options.knownHelpers[_name] = knownHelpers[_name];
  117130. }
  117131. }
  117132. }
  117133. return this.accept(program);
  117134. },
  117135. compileProgram: function compileProgram(program) {
  117136. var childCompiler = new this.compiler(),
  117137. // eslint-disable-line new-cap
  117138. result = childCompiler.compile(program, this.options),
  117139. guid = this.guid++;
  117140. this.usePartial = this.usePartial || result.usePartial;
  117141. this.children[guid] = result;
  117142. this.useDepths = this.useDepths || result.useDepths;
  117143. return guid;
  117144. },
  117145. accept: function accept(node) {
  117146. /* istanbul ignore next: Sanity code */
  117147. if (!this[node.type]) {
  117148. throw new _exception2['default']('Unknown type: ' + node.type, node);
  117149. }
  117150. this.sourceNode.unshift(node);
  117151. var ret = this[node.type](node);
  117152. this.sourceNode.shift();
  117153. return ret;
  117154. },
  117155. Program: function Program(program) {
  117156. this.options.blockParams.unshift(program.blockParams);
  117157. var body = program.body,
  117158. bodyLength = body.length;
  117159. for (var i = 0; i < bodyLength; i++) {
  117160. this.accept(body[i]);
  117161. }
  117162. this.options.blockParams.shift();
  117163. this.isSimple = bodyLength === 1;
  117164. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  117165. return this;
  117166. },
  117167. BlockStatement: function BlockStatement(block) {
  117168. transformLiteralToPath(block);
  117169. var program = block.program,
  117170. inverse = block.inverse;
  117171. program = program && this.compileProgram(program);
  117172. inverse = inverse && this.compileProgram(inverse);
  117173. var type = this.classifySexpr(block);
  117174. if (type === 'helper') {
  117175. this.helperSexpr(block, program, inverse);
  117176. } else if (type === 'simple') {
  117177. this.simpleSexpr(block);
  117178. // now that the simple mustache is resolved, we need to
  117179. // evaluate it by executing `blockHelperMissing`
  117180. this.opcode('pushProgram', program);
  117181. this.opcode('pushProgram', inverse);
  117182. this.opcode('emptyHash');
  117183. this.opcode('blockValue', block.path.original);
  117184. } else {
  117185. this.ambiguousSexpr(block, program, inverse);
  117186. // now that the simple mustache is resolved, we need to
  117187. // evaluate it by executing `blockHelperMissing`
  117188. this.opcode('pushProgram', program);
  117189. this.opcode('pushProgram', inverse);
  117190. this.opcode('emptyHash');
  117191. this.opcode('ambiguousBlockValue');
  117192. }
  117193. this.opcode('append');
  117194. },
  117195. DecoratorBlock: function DecoratorBlock(decorator) {
  117196. var program = decorator.program && this.compileProgram(decorator.program);
  117197. var params = this.setupFullMustacheParams(decorator, program, undefined),
  117198. path = decorator.path;
  117199. this.useDecorators = true;
  117200. this.opcode('registerDecorator', params.length, path.original);
  117201. },
  117202. PartialStatement: function PartialStatement(partial) {
  117203. this.usePartial = true;
  117204. var program = partial.program;
  117205. if (program) {
  117206. program = this.compileProgram(partial.program);
  117207. }
  117208. var params = partial.params;
  117209. if (params.length > 1) {
  117210. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  117211. } else if (!params.length) {
  117212. if (this.options.explicitPartialContext) {
  117213. this.opcode('pushLiteral', 'undefined');
  117214. } else {
  117215. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  117216. }
  117217. }
  117218. var partialName = partial.name.original,
  117219. isDynamic = partial.name.type === 'SubExpression';
  117220. if (isDynamic) {
  117221. this.accept(partial.name);
  117222. }
  117223. this.setupFullMustacheParams(partial, program, undefined, true);
  117224. var indent = partial.indent || '';
  117225. if (this.options.preventIndent && indent) {
  117226. this.opcode('appendContent', indent);
  117227. indent = '';
  117228. }
  117229. this.opcode('invokePartial', isDynamic, partialName, indent);
  117230. this.opcode('append');
  117231. },
  117232. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  117233. this.PartialStatement(partialBlock);
  117234. },
  117235. MustacheStatement: function MustacheStatement(mustache) {
  117236. this.SubExpression(mustache);
  117237. if (mustache.escaped && !this.options.noEscape) {
  117238. this.opcode('appendEscaped');
  117239. } else {
  117240. this.opcode('append');
  117241. }
  117242. },
  117243. Decorator: function Decorator(decorator) {
  117244. this.DecoratorBlock(decorator);
  117245. },
  117246. ContentStatement: function ContentStatement(content) {
  117247. if (content.value) {
  117248. this.opcode('appendContent', content.value);
  117249. }
  117250. },
  117251. CommentStatement: function CommentStatement() {},
  117252. SubExpression: function SubExpression(sexpr) {
  117253. transformLiteralToPath(sexpr);
  117254. var type = this.classifySexpr(sexpr);
  117255. if (type === 'simple') {
  117256. this.simpleSexpr(sexpr);
  117257. } else if (type === 'helper') {
  117258. this.helperSexpr(sexpr);
  117259. } else {
  117260. this.ambiguousSexpr(sexpr);
  117261. }
  117262. },
  117263. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  117264. var path = sexpr.path,
  117265. name = path.parts[0],
  117266. isBlock = program != null || inverse != null;
  117267. this.opcode('getContext', path.depth);
  117268. this.opcode('pushProgram', program);
  117269. this.opcode('pushProgram', inverse);
  117270. path.strict = true;
  117271. this.accept(path);
  117272. this.opcode('invokeAmbiguous', name, isBlock);
  117273. },
  117274. simpleSexpr: function simpleSexpr(sexpr) {
  117275. var path = sexpr.path;
  117276. path.strict = true;
  117277. this.accept(path);
  117278. this.opcode('resolvePossibleLambda');
  117279. },
  117280. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  117281. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  117282. path = sexpr.path,
  117283. name = path.parts[0];
  117284. if (this.options.knownHelpers[name]) {
  117285. this.opcode('invokeKnownHelper', params.length, name);
  117286. } else if (this.options.knownHelpersOnly) {
  117287. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  117288. } else {
  117289. path.strict = true;
  117290. path.falsy = true;
  117291. this.accept(path);
  117292. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  117293. }
  117294. },
  117295. PathExpression: function PathExpression(path) {
  117296. this.addDepth(path.depth);
  117297. this.opcode('getContext', path.depth);
  117298. var name = path.parts[0],
  117299. scoped = _ast2['default'].helpers.scopedId(path),
  117300. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  117301. if (blockParamId) {
  117302. this.opcode('lookupBlockParam', blockParamId, path.parts);
  117303. } else if (!name) {
  117304. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  117305. this.opcode('pushContext');
  117306. } else if (path.data) {
  117307. this.options.data = true;
  117308. this.opcode('lookupData', path.depth, path.parts, path.strict);
  117309. } else {
  117310. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  117311. }
  117312. },
  117313. StringLiteral: function StringLiteral(string) {
  117314. this.opcode('pushString', string.value);
  117315. },
  117316. NumberLiteral: function NumberLiteral(number) {
  117317. this.opcode('pushLiteral', number.value);
  117318. },
  117319. BooleanLiteral: function BooleanLiteral(bool) {
  117320. this.opcode('pushLiteral', bool.value);
  117321. },
  117322. UndefinedLiteral: function UndefinedLiteral() {
  117323. this.opcode('pushLiteral', 'undefined');
  117324. },
  117325. NullLiteral: function NullLiteral() {
  117326. this.opcode('pushLiteral', 'null');
  117327. },
  117328. Hash: function Hash(hash) {
  117329. var pairs = hash.pairs,
  117330. i = 0,
  117331. l = pairs.length;
  117332. this.opcode('pushHash');
  117333. for (; i < l; i++) {
  117334. this.pushParam(pairs[i].value);
  117335. }
  117336. while (i--) {
  117337. this.opcode('assignToHash', pairs[i].key);
  117338. }
  117339. this.opcode('popHash');
  117340. },
  117341. // HELPERS
  117342. opcode: function opcode(name) {
  117343. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  117344. },
  117345. addDepth: function addDepth(depth) {
  117346. if (!depth) {
  117347. return;
  117348. }
  117349. this.useDepths = true;
  117350. },
  117351. classifySexpr: function classifySexpr(sexpr) {
  117352. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  117353. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  117354. // a mustache is an eligible helper if:
  117355. // * its id is simple (a single part, not `this` or `..`)
  117356. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  117357. // if a mustache is an eligible helper but not a definite
  117358. // helper, it is ambiguous, and will be resolved in a later
  117359. // pass or at runtime.
  117360. var isEligible = !isBlockParam && (isHelper || isSimple);
  117361. // if ambiguous, we can possibly resolve the ambiguity now
  117362. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  117363. if (isEligible && !isHelper) {
  117364. var _name2 = sexpr.path.parts[0],
  117365. options = this.options;
  117366. if (options.knownHelpers[_name2]) {
  117367. isHelper = true;
  117368. } else if (options.knownHelpersOnly) {
  117369. isEligible = false;
  117370. }
  117371. }
  117372. if (isHelper) {
  117373. return 'helper';
  117374. } else if (isEligible) {
  117375. return 'ambiguous';
  117376. } else {
  117377. return 'simple';
  117378. }
  117379. },
  117380. pushParams: function pushParams(params) {
  117381. for (var i = 0, l = params.length; i < l; i++) {
  117382. this.pushParam(params[i]);
  117383. }
  117384. },
  117385. pushParam: function pushParam(val) {
  117386. var value = val.value != null ? val.value : val.original || '';
  117387. if (this.stringParams) {
  117388. if (value.replace) {
  117389. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  117390. }
  117391. if (val.depth) {
  117392. this.addDepth(val.depth);
  117393. }
  117394. this.opcode('getContext', val.depth || 0);
  117395. this.opcode('pushStringParam', value, val.type);
  117396. if (val.type === 'SubExpression') {
  117397. // SubExpressions get evaluated and passed in
  117398. // in string params mode.
  117399. this.accept(val);
  117400. }
  117401. } else {
  117402. if (this.trackIds) {
  117403. var blockParamIndex = undefined;
  117404. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  117405. blockParamIndex = this.blockParamIndex(val.parts[0]);
  117406. }
  117407. if (blockParamIndex) {
  117408. var blockParamChild = val.parts.slice(1).join('.');
  117409. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  117410. } else {
  117411. value = val.original || value;
  117412. if (value.replace) {
  117413. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  117414. }
  117415. this.opcode('pushId', val.type, value);
  117416. }
  117417. }
  117418. this.accept(val);
  117419. }
  117420. },
  117421. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  117422. var params = sexpr.params;
  117423. this.pushParams(params);
  117424. this.opcode('pushProgram', program);
  117425. this.opcode('pushProgram', inverse);
  117426. if (sexpr.hash) {
  117427. this.accept(sexpr.hash);
  117428. } else {
  117429. this.opcode('emptyHash', omitEmpty);
  117430. }
  117431. return params;
  117432. },
  117433. blockParamIndex: function blockParamIndex(name) {
  117434. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  117435. var blockParams = this.options.blockParams[depth],
  117436. param = blockParams && _utils.indexOf(blockParams, name);
  117437. if (blockParams && param >= 0) {
  117438. return [depth, param];
  117439. }
  117440. }
  117441. }
  117442. };
  117443. function precompile(input, options, env) {
  117444. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  117445. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  117446. }
  117447. options = options || {};
  117448. if (!('data' in options)) {
  117449. options.data = true;
  117450. }
  117451. if (options.compat) {
  117452. options.useDepths = true;
  117453. }
  117454. var ast = env.parse(input, options),
  117455. environment = new env.Compiler().compile(ast, options);
  117456. return new env.JavaScriptCompiler().compile(environment, options);
  117457. }
  117458. function compile(input, options, env) {
  117459. if (options === undefined) options = {};
  117460. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  117461. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  117462. }
  117463. options = _utils.extend({}, options);
  117464. if (!('data' in options)) {
  117465. options.data = true;
  117466. }
  117467. if (options.compat) {
  117468. options.useDepths = true;
  117469. }
  117470. var compiled = undefined;
  117471. function compileInput() {
  117472. var ast = env.parse(input, options),
  117473. environment = new env.Compiler().compile(ast, options),
  117474. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  117475. return env.template(templateSpec);
  117476. }
  117477. // Template is only compiled on first use and cached after that point.
  117478. function ret(context, execOptions) {
  117479. if (!compiled) {
  117480. compiled = compileInput();
  117481. }
  117482. return compiled.call(this, context, execOptions);
  117483. }
  117484. ret._setup = function (setupOptions) {
  117485. if (!compiled) {
  117486. compiled = compileInput();
  117487. }
  117488. return compiled._setup(setupOptions);
  117489. };
  117490. ret._child = function (i, data, blockParams, depths) {
  117491. if (!compiled) {
  117492. compiled = compileInput();
  117493. }
  117494. return compiled._child(i, data, blockParams, depths);
  117495. };
  117496. return ret;
  117497. }
  117498. function argEquals(a, b) {
  117499. if (a === b) {
  117500. return true;
  117501. }
  117502. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  117503. for (var i = 0; i < a.length; i++) {
  117504. if (!argEquals(a[i], b[i])) {
  117505. return false;
  117506. }
  117507. }
  117508. return true;
  117509. }
  117510. }
  117511. function transformLiteralToPath(sexpr) {
  117512. if (!sexpr.path.parts) {
  117513. var literal = sexpr.path;
  117514. // Casting to string here to make false and 0 literal values play nicely with the rest
  117515. // of the system.
  117516. sexpr.path = {
  117517. type: 'PathExpression',
  117518. data: false,
  117519. depth: 0,
  117520. parts: [literal.original + ''],
  117521. original: literal.original + '',
  117522. loc: literal.loc
  117523. };
  117524. }
  117525. }
  117526. /***/ }),
  117527. /* 42 */
  117528. /***/ (function(module, exports, __webpack_require__) {
  117529. 'use strict';
  117530. var _interopRequireDefault = __webpack_require__(1)['default'];
  117531. exports.__esModule = true;
  117532. var _base = __webpack_require__(4);
  117533. var _exception = __webpack_require__(6);
  117534. var _exception2 = _interopRequireDefault(_exception);
  117535. var _utils = __webpack_require__(5);
  117536. var _codeGen = __webpack_require__(43);
  117537. var _codeGen2 = _interopRequireDefault(_codeGen);
  117538. function Literal(value) {
  117539. this.value = value;
  117540. }
  117541. function JavaScriptCompiler() {}
  117542. JavaScriptCompiler.prototype = {
  117543. // PUBLIC API: You can override these methods in a subclass to provide
  117544. // alternative compiled forms for name lookup and buffering semantics
  117545. nameLookup: function nameLookup(parent, name /* , type*/) {
  117546. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  117547. return [parent, '.', name];
  117548. } else {
  117549. return [parent, '[', JSON.stringify(name), ']'];
  117550. }
  117551. },
  117552. depthedLookup: function depthedLookup(name) {
  117553. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  117554. },
  117555. compilerInfo: function compilerInfo() {
  117556. var revision = _base.COMPILER_REVISION,
  117557. versions = _base.REVISION_CHANGES[revision];
  117558. return [revision, versions];
  117559. },
  117560. appendToBuffer: function appendToBuffer(source, location, explicit) {
  117561. // Force a source as this simplifies the merge logic.
  117562. if (!_utils.isArray(source)) {
  117563. source = [source];
  117564. }
  117565. source = this.source.wrap(source, location);
  117566. if (this.environment.isSimple) {
  117567. return ['return ', source, ';'];
  117568. } else if (explicit) {
  117569. // This is a case where the buffer operation occurs as a child of another
  117570. // construct, generally braces. We have to explicitly output these buffer
  117571. // operations to ensure that the emitted code goes in the correct location.
  117572. return ['buffer += ', source, ';'];
  117573. } else {
  117574. source.appendToBuffer = true;
  117575. return source;
  117576. }
  117577. },
  117578. initializeBuffer: function initializeBuffer() {
  117579. return this.quotedString('');
  117580. },
  117581. // END PUBLIC API
  117582. compile: function compile(environment, options, context, asObject) {
  117583. this.environment = environment;
  117584. this.options = options;
  117585. this.stringParams = this.options.stringParams;
  117586. this.trackIds = this.options.trackIds;
  117587. this.precompile = !asObject;
  117588. this.name = this.environment.name;
  117589. this.isChild = !!context;
  117590. this.context = context || {
  117591. decorators: [],
  117592. programs: [],
  117593. environments: []
  117594. };
  117595. this.preamble();
  117596. this.stackSlot = 0;
  117597. this.stackVars = [];
  117598. this.aliases = {};
  117599. this.registers = { list: [] };
  117600. this.hashes = [];
  117601. this.compileStack = [];
  117602. this.inlineStack = [];
  117603. this.blockParams = [];
  117604. this.compileChildren(environment, options);
  117605. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  117606. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  117607. var opcodes = environment.opcodes,
  117608. opcode = undefined,
  117609. firstLoc = undefined,
  117610. i = undefined,
  117611. l = undefined;
  117612. for (i = 0, l = opcodes.length; i < l; i++) {
  117613. opcode = opcodes[i];
  117614. this.source.currentLocation = opcode.loc;
  117615. firstLoc = firstLoc || opcode.loc;
  117616. this[opcode.opcode].apply(this, opcode.args);
  117617. }
  117618. // Flush any trailing content that might be pending.
  117619. this.source.currentLocation = firstLoc;
  117620. this.pushSource('');
  117621. /* istanbul ignore next */
  117622. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  117623. throw new _exception2['default']('Compile completed with content left on stack');
  117624. }
  117625. if (!this.decorators.isEmpty()) {
  117626. this.useDecorators = true;
  117627. this.decorators.prepend('var decorators = container.decorators;\n');
  117628. this.decorators.push('return fn;');
  117629. if (asObject) {
  117630. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  117631. } else {
  117632. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  117633. this.decorators.push('}\n');
  117634. this.decorators = this.decorators.merge();
  117635. }
  117636. } else {
  117637. this.decorators = undefined;
  117638. }
  117639. var fn = this.createFunctionContext(asObject);
  117640. if (!this.isChild) {
  117641. var ret = {
  117642. compiler: this.compilerInfo(),
  117643. main: fn
  117644. };
  117645. if (this.decorators) {
  117646. ret.main_d = this.decorators; // eslint-disable-line camelcase
  117647. ret.useDecorators = true;
  117648. }
  117649. var _context = this.context;
  117650. var programs = _context.programs;
  117651. var decorators = _context.decorators;
  117652. for (i = 0, l = programs.length; i < l; i++) {
  117653. if (programs[i]) {
  117654. ret[i] = programs[i];
  117655. if (decorators[i]) {
  117656. ret[i + '_d'] = decorators[i];
  117657. ret.useDecorators = true;
  117658. }
  117659. }
  117660. }
  117661. if (this.environment.usePartial) {
  117662. ret.usePartial = true;
  117663. }
  117664. if (this.options.data) {
  117665. ret.useData = true;
  117666. }
  117667. if (this.useDepths) {
  117668. ret.useDepths = true;
  117669. }
  117670. if (this.useBlockParams) {
  117671. ret.useBlockParams = true;
  117672. }
  117673. if (this.options.compat) {
  117674. ret.compat = true;
  117675. }
  117676. if (!asObject) {
  117677. ret.compiler = JSON.stringify(ret.compiler);
  117678. this.source.currentLocation = { start: { line: 1, column: 0 } };
  117679. ret = this.objectLiteral(ret);
  117680. if (options.srcName) {
  117681. ret = ret.toStringWithSourceMap({ file: options.destName });
  117682. ret.map = ret.map && ret.map.toString();
  117683. } else {
  117684. ret = ret.toString();
  117685. }
  117686. } else {
  117687. ret.compilerOptions = this.options;
  117688. }
  117689. return ret;
  117690. } else {
  117691. return fn;
  117692. }
  117693. },
  117694. preamble: function preamble() {
  117695. // track the last context pushed into place to allow skipping the
  117696. // getContext opcode when it would be a noop
  117697. this.lastContext = 0;
  117698. this.source = new _codeGen2['default'](this.options.srcName);
  117699. this.decorators = new _codeGen2['default'](this.options.srcName);
  117700. },
  117701. createFunctionContext: function createFunctionContext(asObject) {
  117702. var varDeclarations = '';
  117703. var locals = this.stackVars.concat(this.registers.list);
  117704. if (locals.length > 0) {
  117705. varDeclarations += ', ' + locals.join(', ');
  117706. }
  117707. // Generate minimizer alias mappings
  117708. //
  117709. // When using true SourceNodes, this will update all references to the given alias
  117710. // as the source nodes are reused in situ. For the non-source node compilation mode,
  117711. // aliases will not be used, but this case is already being run on the client and
  117712. // we aren't concern about minimizing the template size.
  117713. var aliasCount = 0;
  117714. for (var alias in this.aliases) {
  117715. // eslint-disable-line guard-for-in
  117716. var node = this.aliases[alias];
  117717. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  117718. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  117719. node.children[0] = 'alias' + aliasCount;
  117720. }
  117721. }
  117722. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  117723. if (this.useBlockParams || this.useDepths) {
  117724. params.push('blockParams');
  117725. }
  117726. if (this.useDepths) {
  117727. params.push('depths');
  117728. }
  117729. // Perform a second pass over the output to merge content when possible
  117730. var source = this.mergeSource(varDeclarations);
  117731. if (asObject) {
  117732. params.push(source);
  117733. return Function.apply(this, params);
  117734. } else {
  117735. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  117736. }
  117737. },
  117738. mergeSource: function mergeSource(varDeclarations) {
  117739. var isSimple = this.environment.isSimple,
  117740. appendOnly = !this.forceBuffer,
  117741. appendFirst = undefined,
  117742. sourceSeen = undefined,
  117743. bufferStart = undefined,
  117744. bufferEnd = undefined;
  117745. this.source.each(function (line) {
  117746. if (line.appendToBuffer) {
  117747. if (bufferStart) {
  117748. line.prepend(' + ');
  117749. } else {
  117750. bufferStart = line;
  117751. }
  117752. bufferEnd = line;
  117753. } else {
  117754. if (bufferStart) {
  117755. if (!sourceSeen) {
  117756. appendFirst = true;
  117757. } else {
  117758. bufferStart.prepend('buffer += ');
  117759. }
  117760. bufferEnd.add(';');
  117761. bufferStart = bufferEnd = undefined;
  117762. }
  117763. sourceSeen = true;
  117764. if (!isSimple) {
  117765. appendOnly = false;
  117766. }
  117767. }
  117768. });
  117769. if (appendOnly) {
  117770. if (bufferStart) {
  117771. bufferStart.prepend('return ');
  117772. bufferEnd.add(';');
  117773. } else if (!sourceSeen) {
  117774. this.source.push('return "";');
  117775. }
  117776. } else {
  117777. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  117778. if (bufferStart) {
  117779. bufferStart.prepend('return buffer + ');
  117780. bufferEnd.add(';');
  117781. } else {
  117782. this.source.push('return buffer;');
  117783. }
  117784. }
  117785. if (varDeclarations) {
  117786. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  117787. }
  117788. return this.source.merge();
  117789. },
  117790. // [blockValue]
  117791. //
  117792. // On stack, before: hash, inverse, program, value
  117793. // On stack, after: return value of blockHelperMissing
  117794. //
  117795. // The purpose of this opcode is to take a block of the form
  117796. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  117797. // replace it on the stack with the result of properly
  117798. // invoking blockHelperMissing.
  117799. blockValue: function blockValue(name) {
  117800. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  117801. params = [this.contextName(0)];
  117802. this.setupHelperArgs(name, 0, params);
  117803. var blockName = this.popStack();
  117804. params.splice(1, 0, blockName);
  117805. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  117806. },
  117807. // [ambiguousBlockValue]
  117808. //
  117809. // On stack, before: hash, inverse, program, value
  117810. // Compiler value, before: lastHelper=value of last found helper, if any
  117811. // On stack, after, if no lastHelper: same as [blockValue]
  117812. // On stack, after, if lastHelper: value
  117813. ambiguousBlockValue: function ambiguousBlockValue() {
  117814. // We're being a bit cheeky and reusing the options value from the prior exec
  117815. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  117816. params = [this.contextName(0)];
  117817. this.setupHelperArgs('', 0, params, true);
  117818. this.flushInline();
  117819. var current = this.topStack();
  117820. params.splice(1, 0, current);
  117821. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  117822. },
  117823. // [appendContent]
  117824. //
  117825. // On stack, before: ...
  117826. // On stack, after: ...
  117827. //
  117828. // Appends the string value of `content` to the current buffer
  117829. appendContent: function appendContent(content) {
  117830. if (this.pendingContent) {
  117831. content = this.pendingContent + content;
  117832. } else {
  117833. this.pendingLocation = this.source.currentLocation;
  117834. }
  117835. this.pendingContent = content;
  117836. },
  117837. // [append]
  117838. //
  117839. // On stack, before: value, ...
  117840. // On stack, after: ...
  117841. //
  117842. // Coerces `value` to a String and appends it to the current buffer.
  117843. //
  117844. // If `value` is truthy, or 0, it is coerced into a string and appended
  117845. // Otherwise, the empty string is appended
  117846. append: function append() {
  117847. if (this.isInline()) {
  117848. this.replaceStack(function (current) {
  117849. return [' != null ? ', current, ' : ""'];
  117850. });
  117851. this.pushSource(this.appendToBuffer(this.popStack()));
  117852. } else {
  117853. var local = this.popStack();
  117854. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  117855. if (this.environment.isSimple) {
  117856. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  117857. }
  117858. }
  117859. },
  117860. // [appendEscaped]
  117861. //
  117862. // On stack, before: value, ...
  117863. // On stack, after: ...
  117864. //
  117865. // Escape `value` and append it to the buffer
  117866. appendEscaped: function appendEscaped() {
  117867. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  117868. },
  117869. // [getContext]
  117870. //
  117871. // On stack, before: ...
  117872. // On stack, after: ...
  117873. // Compiler value, after: lastContext=depth
  117874. //
  117875. // Set the value of the `lastContext` compiler value to the depth
  117876. getContext: function getContext(depth) {
  117877. this.lastContext = depth;
  117878. },
  117879. // [pushContext]
  117880. //
  117881. // On stack, before: ...
  117882. // On stack, after: currentContext, ...
  117883. //
  117884. // Pushes the value of the current context onto the stack.
  117885. pushContext: function pushContext() {
  117886. this.pushStackLiteral(this.contextName(this.lastContext));
  117887. },
  117888. // [lookupOnContext]
  117889. //
  117890. // On stack, before: ...
  117891. // On stack, after: currentContext[name], ...
  117892. //
  117893. // Looks up the value of `name` on the current context and pushes
  117894. // it onto the stack.
  117895. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  117896. var i = 0;
  117897. if (!scoped && this.options.compat && !this.lastContext) {
  117898. // The depthed query is expected to handle the undefined logic for the root level that
  117899. // is implemented below, so we evaluate that directly in compat mode
  117900. this.push(this.depthedLookup(parts[i++]));
  117901. } else {
  117902. this.pushContext();
  117903. }
  117904. this.resolvePath('context', parts, i, falsy, strict);
  117905. },
  117906. // [lookupBlockParam]
  117907. //
  117908. // On stack, before: ...
  117909. // On stack, after: blockParam[name], ...
  117910. //
  117911. // Looks up the value of `parts` on the given block param and pushes
  117912. // it onto the stack.
  117913. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  117914. this.useBlockParams = true;
  117915. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  117916. this.resolvePath('context', parts, 1);
  117917. },
  117918. // [lookupData]
  117919. //
  117920. // On stack, before: ...
  117921. // On stack, after: data, ...
  117922. //
  117923. // Push the data lookup operator
  117924. lookupData: function lookupData(depth, parts, strict) {
  117925. if (!depth) {
  117926. this.pushStackLiteral('data');
  117927. } else {
  117928. this.pushStackLiteral('container.data(data, ' + depth + ')');
  117929. }
  117930. this.resolvePath('data', parts, 0, true, strict);
  117931. },
  117932. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  117933. // istanbul ignore next
  117934. var _this = this;
  117935. if (this.options.strict || this.options.assumeObjects) {
  117936. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  117937. return;
  117938. }
  117939. var len = parts.length;
  117940. for (; i < len; i++) {
  117941. /* eslint-disable no-loop-func */
  117942. this.replaceStack(function (current) {
  117943. var lookup = _this.nameLookup(current, parts[i], type);
  117944. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  117945. // needs to have the special handling for these values.
  117946. if (!falsy) {
  117947. return [' != null ? ', lookup, ' : ', current];
  117948. } else {
  117949. // Otherwise we can use generic falsy handling
  117950. return [' && ', lookup];
  117951. }
  117952. });
  117953. /* eslint-enable no-loop-func */
  117954. }
  117955. },
  117956. // [resolvePossibleLambda]
  117957. //
  117958. // On stack, before: value, ...
  117959. // On stack, after: resolved value, ...
  117960. //
  117961. // If the `value` is a lambda, replace it on the stack by
  117962. // the return value of the lambda
  117963. resolvePossibleLambda: function resolvePossibleLambda() {
  117964. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  117965. },
  117966. // [pushStringParam]
  117967. //
  117968. // On stack, before: ...
  117969. // On stack, after: string, currentContext, ...
  117970. //
  117971. // This opcode is designed for use in string mode, which
  117972. // provides the string value of a parameter along with its
  117973. // depth rather than resolving it immediately.
  117974. pushStringParam: function pushStringParam(string, type) {
  117975. this.pushContext();
  117976. this.pushString(type);
  117977. // If it's a subexpression, the string result
  117978. // will be pushed after this opcode.
  117979. if (type !== 'SubExpression') {
  117980. if (typeof string === 'string') {
  117981. this.pushString(string);
  117982. } else {
  117983. this.pushStackLiteral(string);
  117984. }
  117985. }
  117986. },
  117987. emptyHash: function emptyHash(omitEmpty) {
  117988. if (this.trackIds) {
  117989. this.push('{}'); // hashIds
  117990. }
  117991. if (this.stringParams) {
  117992. this.push('{}'); // hashContexts
  117993. this.push('{}'); // hashTypes
  117994. }
  117995. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  117996. },
  117997. pushHash: function pushHash() {
  117998. if (this.hash) {
  117999. this.hashes.push(this.hash);
  118000. }
  118001. this.hash = { values: [], types: [], contexts: [], ids: [] };
  118002. },
  118003. popHash: function popHash() {
  118004. var hash = this.hash;
  118005. this.hash = this.hashes.pop();
  118006. if (this.trackIds) {
  118007. this.push(this.objectLiteral(hash.ids));
  118008. }
  118009. if (this.stringParams) {
  118010. this.push(this.objectLiteral(hash.contexts));
  118011. this.push(this.objectLiteral(hash.types));
  118012. }
  118013. this.push(this.objectLiteral(hash.values));
  118014. },
  118015. // [pushString]
  118016. //
  118017. // On stack, before: ...
  118018. // On stack, after: quotedString(string), ...
  118019. //
  118020. // Push a quoted version of `string` onto the stack
  118021. pushString: function pushString(string) {
  118022. this.pushStackLiteral(this.quotedString(string));
  118023. },
  118024. // [pushLiteral]
  118025. //
  118026. // On stack, before: ...
  118027. // On stack, after: value, ...
  118028. //
  118029. // Pushes a value onto the stack. This operation prevents
  118030. // the compiler from creating a temporary variable to hold
  118031. // it.
  118032. pushLiteral: function pushLiteral(value) {
  118033. this.pushStackLiteral(value);
  118034. },
  118035. // [pushProgram]
  118036. //
  118037. // On stack, before: ...
  118038. // On stack, after: program(guid), ...
  118039. //
  118040. // Push a program expression onto the stack. This takes
  118041. // a compile-time guid and converts it into a runtime-accessible
  118042. // expression.
  118043. pushProgram: function pushProgram(guid) {
  118044. if (guid != null) {
  118045. this.pushStackLiteral(this.programExpression(guid));
  118046. } else {
  118047. this.pushStackLiteral(null);
  118048. }
  118049. },
  118050. // [registerDecorator]
  118051. //
  118052. // On stack, before: hash, program, params..., ...
  118053. // On stack, after: ...
  118054. //
  118055. // Pops off the decorator's parameters, invokes the decorator,
  118056. // and inserts the decorator into the decorators list.
  118057. registerDecorator: function registerDecorator(paramSize, name) {
  118058. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  118059. options = this.setupHelperArgs(name, paramSize);
  118060. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  118061. },
  118062. // [invokeHelper]
  118063. //
  118064. // On stack, before: hash, inverse, program, params..., ...
  118065. // On stack, after: result of helper invocation
  118066. //
  118067. // Pops off the helper's parameters, invokes the helper,
  118068. // and pushes the helper's return value onto the stack.
  118069. //
  118070. // If the helper is not found, `helperMissing` is called.
  118071. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  118072. var nonHelper = this.popStack(),
  118073. helper = this.setupHelper(paramSize, name),
  118074. simple = isSimple ? [helper.name, ' || '] : '';
  118075. var lookup = ['('].concat(simple, nonHelper);
  118076. if (!this.options.strict) {
  118077. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  118078. }
  118079. lookup.push(')');
  118080. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  118081. },
  118082. // [invokeKnownHelper]
  118083. //
  118084. // On stack, before: hash, inverse, program, params..., ...
  118085. // On stack, after: result of helper invocation
  118086. //
  118087. // This operation is used when the helper is known to exist,
  118088. // so a `helperMissing` fallback is not required.
  118089. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  118090. var helper = this.setupHelper(paramSize, name);
  118091. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  118092. },
  118093. // [invokeAmbiguous]
  118094. //
  118095. // On stack, before: hash, inverse, program, params..., ...
  118096. // On stack, after: result of disambiguation
  118097. //
  118098. // This operation is used when an expression like `{{foo}}`
  118099. // is provided, but we don't know at compile-time whether it
  118100. // is a helper or a path.
  118101. //
  118102. // This operation emits more code than the other options,
  118103. // and can be avoided by passing the `knownHelpers` and
  118104. // `knownHelpersOnly` flags at compile-time.
  118105. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  118106. this.useRegister('helper');
  118107. var nonHelper = this.popStack();
  118108. this.emptyHash();
  118109. var helper = this.setupHelper(0, name, helperCall);
  118110. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  118111. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  118112. if (!this.options.strict) {
  118113. lookup[0] = '(helper = ';
  118114. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  118115. }
  118116. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  118117. },
  118118. // [invokePartial]
  118119. //
  118120. // On stack, before: context, ...
  118121. // On stack after: result of partial invocation
  118122. //
  118123. // This operation pops off a context, invokes a partial with that context,
  118124. // and pushes the result of the invocation back.
  118125. invokePartial: function invokePartial(isDynamic, name, indent) {
  118126. var params = [],
  118127. options = this.setupParams(name, 1, params);
  118128. if (isDynamic) {
  118129. name = this.popStack();
  118130. delete options.name;
  118131. }
  118132. if (indent) {
  118133. options.indent = JSON.stringify(indent);
  118134. }
  118135. options.helpers = 'helpers';
  118136. options.partials = 'partials';
  118137. options.decorators = 'container.decorators';
  118138. if (!isDynamic) {
  118139. params.unshift(this.nameLookup('partials', name, 'partial'));
  118140. } else {
  118141. params.unshift(name);
  118142. }
  118143. if (this.options.compat) {
  118144. options.depths = 'depths';
  118145. }
  118146. options = this.objectLiteral(options);
  118147. params.push(options);
  118148. this.push(this.source.functionCall('container.invokePartial', '', params));
  118149. },
  118150. // [assignToHash]
  118151. //
  118152. // On stack, before: value, ..., hash, ...
  118153. // On stack, after: ..., hash, ...
  118154. //
  118155. // Pops a value off the stack and assigns it to the current hash
  118156. assignToHash: function assignToHash(key) {
  118157. var value = this.popStack(),
  118158. context = undefined,
  118159. type = undefined,
  118160. id = undefined;
  118161. if (this.trackIds) {
  118162. id = this.popStack();
  118163. }
  118164. if (this.stringParams) {
  118165. type = this.popStack();
  118166. context = this.popStack();
  118167. }
  118168. var hash = this.hash;
  118169. if (context) {
  118170. hash.contexts[key] = context;
  118171. }
  118172. if (type) {
  118173. hash.types[key] = type;
  118174. }
  118175. if (id) {
  118176. hash.ids[key] = id;
  118177. }
  118178. hash.values[key] = value;
  118179. },
  118180. pushId: function pushId(type, name, child) {
  118181. if (type === 'BlockParam') {
  118182. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  118183. } else if (type === 'PathExpression') {
  118184. this.pushString(name);
  118185. } else if (type === 'SubExpression') {
  118186. this.pushStackLiteral('true');
  118187. } else {
  118188. this.pushStackLiteral('null');
  118189. }
  118190. },
  118191. // HELPERS
  118192. compiler: JavaScriptCompiler,
  118193. compileChildren: function compileChildren(environment, options) {
  118194. var children = environment.children,
  118195. child = undefined,
  118196. compiler = undefined;
  118197. for (var i = 0, l = children.length; i < l; i++) {
  118198. child = children[i];
  118199. compiler = new this.compiler(); // eslint-disable-line new-cap
  118200. var existing = this.matchExistingProgram(child);
  118201. if (existing == null) {
  118202. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  118203. var index = this.context.programs.length;
  118204. child.index = index;
  118205. child.name = 'program' + index;
  118206. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  118207. this.context.decorators[index] = compiler.decorators;
  118208. this.context.environments[index] = child;
  118209. this.useDepths = this.useDepths || compiler.useDepths;
  118210. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  118211. child.useDepths = this.useDepths;
  118212. child.useBlockParams = this.useBlockParams;
  118213. } else {
  118214. child.index = existing.index;
  118215. child.name = 'program' + existing.index;
  118216. this.useDepths = this.useDepths || existing.useDepths;
  118217. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  118218. }
  118219. }
  118220. },
  118221. matchExistingProgram: function matchExistingProgram(child) {
  118222. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  118223. var environment = this.context.environments[i];
  118224. if (environment && environment.equals(child)) {
  118225. return environment;
  118226. }
  118227. }
  118228. },
  118229. programExpression: function programExpression(guid) {
  118230. var child = this.environment.children[guid],
  118231. programParams = [child.index, 'data', child.blockParams];
  118232. if (this.useBlockParams || this.useDepths) {
  118233. programParams.push('blockParams');
  118234. }
  118235. if (this.useDepths) {
  118236. programParams.push('depths');
  118237. }
  118238. return 'container.program(' + programParams.join(', ') + ')';
  118239. },
  118240. useRegister: function useRegister(name) {
  118241. if (!this.registers[name]) {
  118242. this.registers[name] = true;
  118243. this.registers.list.push(name);
  118244. }
  118245. },
  118246. push: function push(expr) {
  118247. if (!(expr instanceof Literal)) {
  118248. expr = this.source.wrap(expr);
  118249. }
  118250. this.inlineStack.push(expr);
  118251. return expr;
  118252. },
  118253. pushStackLiteral: function pushStackLiteral(item) {
  118254. this.push(new Literal(item));
  118255. },
  118256. pushSource: function pushSource(source) {
  118257. if (this.pendingContent) {
  118258. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  118259. this.pendingContent = undefined;
  118260. }
  118261. if (source) {
  118262. this.source.push(source);
  118263. }
  118264. },
  118265. replaceStack: function replaceStack(callback) {
  118266. var prefix = ['('],
  118267. stack = undefined,
  118268. createdStack = undefined,
  118269. usedLiteral = undefined;
  118270. /* istanbul ignore next */
  118271. if (!this.isInline()) {
  118272. throw new _exception2['default']('replaceStack on non-inline');
  118273. }
  118274. // We want to merge the inline statement into the replacement statement via ','
  118275. var top = this.popStack(true);
  118276. if (top instanceof Literal) {
  118277. // Literals do not need to be inlined
  118278. stack = [top.value];
  118279. prefix = ['(', stack];
  118280. usedLiteral = true;
  118281. } else {
  118282. // Get or create the current stack name for use by the inline
  118283. createdStack = true;
  118284. var _name = this.incrStack();
  118285. prefix = ['((', this.push(_name), ' = ', top, ')'];
  118286. stack = this.topStack();
  118287. }
  118288. var item = callback.call(this, stack);
  118289. if (!usedLiteral) {
  118290. this.popStack();
  118291. }
  118292. if (createdStack) {
  118293. this.stackSlot--;
  118294. }
  118295. this.push(prefix.concat(item, ')'));
  118296. },
  118297. incrStack: function incrStack() {
  118298. this.stackSlot++;
  118299. if (this.stackSlot > this.stackVars.length) {
  118300. this.stackVars.push('stack' + this.stackSlot);
  118301. }
  118302. return this.topStackName();
  118303. },
  118304. topStackName: function topStackName() {
  118305. return 'stack' + this.stackSlot;
  118306. },
  118307. flushInline: function flushInline() {
  118308. var inlineStack = this.inlineStack;
  118309. this.inlineStack = [];
  118310. for (var i = 0, len = inlineStack.length; i < len; i++) {
  118311. var entry = inlineStack[i];
  118312. /* istanbul ignore if */
  118313. if (entry instanceof Literal) {
  118314. this.compileStack.push(entry);
  118315. } else {
  118316. var stack = this.incrStack();
  118317. this.pushSource([stack, ' = ', entry, ';']);
  118318. this.compileStack.push(stack);
  118319. }
  118320. }
  118321. },
  118322. isInline: function isInline() {
  118323. return this.inlineStack.length;
  118324. },
  118325. popStack: function popStack(wrapped) {
  118326. var inline = this.isInline(),
  118327. item = (inline ? this.inlineStack : this.compileStack).pop();
  118328. if (!wrapped && item instanceof Literal) {
  118329. return item.value;
  118330. } else {
  118331. if (!inline) {
  118332. /* istanbul ignore next */
  118333. if (!this.stackSlot) {
  118334. throw new _exception2['default']('Invalid stack pop');
  118335. }
  118336. this.stackSlot--;
  118337. }
  118338. return item;
  118339. }
  118340. },
  118341. topStack: function topStack() {
  118342. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  118343. item = stack[stack.length - 1];
  118344. /* istanbul ignore if */
  118345. if (item instanceof Literal) {
  118346. return item.value;
  118347. } else {
  118348. return item;
  118349. }
  118350. },
  118351. contextName: function contextName(context) {
  118352. if (this.useDepths && context) {
  118353. return 'depths[' + context + ']';
  118354. } else {
  118355. return 'depth' + context;
  118356. }
  118357. },
  118358. quotedString: function quotedString(str) {
  118359. return this.source.quotedString(str);
  118360. },
  118361. objectLiteral: function objectLiteral(obj) {
  118362. return this.source.objectLiteral(obj);
  118363. },
  118364. aliasable: function aliasable(name) {
  118365. var ret = this.aliases[name];
  118366. if (ret) {
  118367. ret.referenceCount++;
  118368. return ret;
  118369. }
  118370. ret = this.aliases[name] = this.source.wrap(name);
  118371. ret.aliasable = true;
  118372. ret.referenceCount = 1;
  118373. return ret;
  118374. },
  118375. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  118376. var params = [],
  118377. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  118378. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  118379. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  118380. return {
  118381. params: params,
  118382. paramsInit: paramsInit,
  118383. name: foundHelper,
  118384. callParams: [callContext].concat(params)
  118385. };
  118386. },
  118387. setupParams: function setupParams(helper, paramSize, params) {
  118388. var options = {},
  118389. contexts = [],
  118390. types = [],
  118391. ids = [],
  118392. objectArgs = !params,
  118393. param = undefined;
  118394. if (objectArgs) {
  118395. params = [];
  118396. }
  118397. options.name = this.quotedString(helper);
  118398. options.hash = this.popStack();
  118399. if (this.trackIds) {
  118400. options.hashIds = this.popStack();
  118401. }
  118402. if (this.stringParams) {
  118403. options.hashTypes = this.popStack();
  118404. options.hashContexts = this.popStack();
  118405. }
  118406. var inverse = this.popStack(),
  118407. program = this.popStack();
  118408. // Avoid setting fn and inverse if neither are set. This allows
  118409. // helpers to do a check for `if (options.fn)`
  118410. if (program || inverse) {
  118411. options.fn = program || 'container.noop';
  118412. options.inverse = inverse || 'container.noop';
  118413. }
  118414. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  118415. // so we need to pop them off the stack in reverse order
  118416. var i = paramSize;
  118417. while (i--) {
  118418. param = this.popStack();
  118419. params[i] = param;
  118420. if (this.trackIds) {
  118421. ids[i] = this.popStack();
  118422. }
  118423. if (this.stringParams) {
  118424. types[i] = this.popStack();
  118425. contexts[i] = this.popStack();
  118426. }
  118427. }
  118428. if (objectArgs) {
  118429. options.args = this.source.generateArray(params);
  118430. }
  118431. if (this.trackIds) {
  118432. options.ids = this.source.generateArray(ids);
  118433. }
  118434. if (this.stringParams) {
  118435. options.types = this.source.generateArray(types);
  118436. options.contexts = this.source.generateArray(contexts);
  118437. }
  118438. if (this.options.data) {
  118439. options.data = 'data';
  118440. }
  118441. if (this.useBlockParams) {
  118442. options.blockParams = 'blockParams';
  118443. }
  118444. return options;
  118445. },
  118446. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  118447. var options = this.setupParams(helper, paramSize, params);
  118448. options = this.objectLiteral(options);
  118449. if (useRegister) {
  118450. this.useRegister('options');
  118451. params.push('options');
  118452. return ['options=', options];
  118453. } else if (params) {
  118454. params.push(options);
  118455. return '';
  118456. } else {
  118457. return options;
  118458. }
  118459. }
  118460. };
  118461. (function () {
  118462. 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(' ');
  118463. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  118464. for (var i = 0, l = reservedWords.length; i < l; i++) {
  118465. compilerWords[reservedWords[i]] = true;
  118466. }
  118467. })();
  118468. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  118469. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  118470. };
  118471. function strictLookup(requireTerminal, compiler, parts, type) {
  118472. var stack = compiler.popStack(),
  118473. i = 0,
  118474. len = parts.length;
  118475. if (requireTerminal) {
  118476. len--;
  118477. }
  118478. for (; i < len; i++) {
  118479. stack = compiler.nameLookup(stack, parts[i], type);
  118480. }
  118481. if (requireTerminal) {
  118482. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  118483. } else {
  118484. return stack;
  118485. }
  118486. }
  118487. exports['default'] = JavaScriptCompiler;
  118488. module.exports = exports['default'];
  118489. /***/ }),
  118490. /* 43 */
  118491. /***/ (function(module, exports, __webpack_require__) {
  118492. /* global define */
  118493. 'use strict';
  118494. exports.__esModule = true;
  118495. var _utils = __webpack_require__(5);
  118496. var SourceNode = undefined;
  118497. try {
  118498. /* istanbul ignore next */
  118499. if (false) {
  118500. // We don't support this in AMD environments. For these environments, we asusme that
  118501. // they are running on the browser and thus have no need for the source-map library.
  118502. var SourceMap = require('source-map');
  118503. SourceNode = SourceMap.SourceNode;
  118504. }
  118505. } catch (err) {}
  118506. /* NOP */
  118507. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  118508. if (!SourceNode) {
  118509. SourceNode = function (line, column, srcFile, chunks) {
  118510. this.src = '';
  118511. if (chunks) {
  118512. this.add(chunks);
  118513. }
  118514. };
  118515. /* istanbul ignore next */
  118516. SourceNode.prototype = {
  118517. add: function add(chunks) {
  118518. if (_utils.isArray(chunks)) {
  118519. chunks = chunks.join('');
  118520. }
  118521. this.src += chunks;
  118522. },
  118523. prepend: function prepend(chunks) {
  118524. if (_utils.isArray(chunks)) {
  118525. chunks = chunks.join('');
  118526. }
  118527. this.src = chunks + this.src;
  118528. },
  118529. toStringWithSourceMap: function toStringWithSourceMap() {
  118530. return { code: this.toString() };
  118531. },
  118532. toString: function toString() {
  118533. return this.src;
  118534. }
  118535. };
  118536. }
  118537. function castChunk(chunk, codeGen, loc) {
  118538. if (_utils.isArray(chunk)) {
  118539. var ret = [];
  118540. for (var i = 0, len = chunk.length; i < len; i++) {
  118541. ret.push(codeGen.wrap(chunk[i], loc));
  118542. }
  118543. return ret;
  118544. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  118545. // Handle primitives that the SourceNode will throw up on
  118546. return chunk + '';
  118547. }
  118548. return chunk;
  118549. }
  118550. function CodeGen(srcFile) {
  118551. this.srcFile = srcFile;
  118552. this.source = [];
  118553. }
  118554. CodeGen.prototype = {
  118555. isEmpty: function isEmpty() {
  118556. return !this.source.length;
  118557. },
  118558. prepend: function prepend(source, loc) {
  118559. this.source.unshift(this.wrap(source, loc));
  118560. },
  118561. push: function push(source, loc) {
  118562. this.source.push(this.wrap(source, loc));
  118563. },
  118564. merge: function merge() {
  118565. var source = this.empty();
  118566. this.each(function (line) {
  118567. source.add([' ', line, '\n']);
  118568. });
  118569. return source;
  118570. },
  118571. each: function each(iter) {
  118572. for (var i = 0, len = this.source.length; i < len; i++) {
  118573. iter(this.source[i]);
  118574. }
  118575. },
  118576. empty: function empty() {
  118577. var loc = this.currentLocation || { start: {} };
  118578. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  118579. },
  118580. wrap: function wrap(chunk) {
  118581. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  118582. if (chunk instanceof SourceNode) {
  118583. return chunk;
  118584. }
  118585. chunk = castChunk(chunk, this, loc);
  118586. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  118587. },
  118588. functionCall: function functionCall(fn, type, params) {
  118589. params = this.generateList(params);
  118590. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  118591. },
  118592. quotedString: function quotedString(str) {
  118593. 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
  118594. .replace(/\u2029/g, '\\u2029') + '"';
  118595. },
  118596. objectLiteral: function objectLiteral(obj) {
  118597. var pairs = [];
  118598. for (var key in obj) {
  118599. if (obj.hasOwnProperty(key)) {
  118600. var value = castChunk(obj[key], this);
  118601. if (value !== 'undefined') {
  118602. pairs.push([this.quotedString(key), ':', value]);
  118603. }
  118604. }
  118605. }
  118606. var ret = this.generateList(pairs);
  118607. ret.prepend('{');
  118608. ret.add('}');
  118609. return ret;
  118610. },
  118611. generateList: function generateList(entries) {
  118612. var ret = this.empty();
  118613. for (var i = 0, len = entries.length; i < len; i++) {
  118614. if (i) {
  118615. ret.add(',');
  118616. }
  118617. ret.add(castChunk(entries[i], this));
  118618. }
  118619. return ret;
  118620. },
  118621. generateArray: function generateArray(entries) {
  118622. var ret = this.generateList(entries);
  118623. ret.prepend('[');
  118624. ret.add(']');
  118625. return ret;
  118626. }
  118627. };
  118628. exports['default'] = CodeGen;
  118629. module.exports = exports['default'];
  118630. /***/ })
  118631. /******/ ])
  118632. });
  118633. ;
  118634. /***/ }),
  118635. /* 63 */
  118636. /***/ (function(module, exports, __webpack_require__) {
  118637. "use strict";
  118638. Object.defineProperty(exports, "__esModule", { value: true });
  118639. /**
  118640. * The EventManager is in charge of registering user interctions with the viewer.
  118641. * It is used in the TemplateManager
  118642. */
  118643. var EventManager = /** @class */ (function () {
  118644. function EventManager(_templateManager) {
  118645. var _this = this;
  118646. this._templateManager = _templateManager;
  118647. this._callbacksContainer = {};
  118648. this._templateManager.onEventTriggered.add(function (eventData) {
  118649. _this._eventTriggered(eventData);
  118650. });
  118651. }
  118652. /**
  118653. * Register a new callback to a specific template.
  118654. * The best example for the usage can be found in the DefaultViewer
  118655. *
  118656. * @param templateName the templateName to register the event to
  118657. * @param callback The callback to be executed
  118658. * @param eventType the type of event to register
  118659. * @param selector an optional selector. if not defined the parent object in the template will be selected
  118660. */
  118661. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  118662. if (!this._callbacksContainer[templateName]) {
  118663. this._callbacksContainer[templateName] = [];
  118664. }
  118665. this._callbacksContainer[templateName].push({
  118666. eventType: eventType,
  118667. callback: callback,
  118668. selector: selector
  118669. });
  118670. };
  118671. /**
  118672. * This will remove a registered event from the defined template.
  118673. * Each one of the variables apart from the template name are optional, but one must be provided.
  118674. *
  118675. * @param templateName the templateName
  118676. * @param callback the callback to remove (optional)
  118677. * @param eventType the event type to remove (optional)
  118678. * @param selector the selector from which to remove the event (optional)
  118679. */
  118680. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  118681. var callbackDefs = this._callbacksContainer[templateName] || [];
  118682. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  118683. };
  118684. EventManager.prototype._eventTriggered = function (data) {
  118685. var templateName = data.template.name;
  118686. var eventType = data.event.type;
  118687. var selector = data.selector;
  118688. var callbackDefs = this._callbacksContainer[templateName] || [];
  118689. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  118690. callbackDef.callback(data);
  118691. });
  118692. };
  118693. /**
  118694. * Dispose the event manager
  118695. */
  118696. EventManager.prototype.dispose = function () {
  118697. this._callbacksContainer = {};
  118698. };
  118699. return EventManager;
  118700. }());
  118701. exports.EventManager = EventManager;
  118702. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQix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, __webpack_require__) {
  118706. /*!
  118707. * PEP v0.4.3 | https://github.com/jquery/PEP
  118708. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  118709. */
  118710. (function (global, factory) {
  118711. true ? module.exports = factory() :
  118712. typeof define === 'function' && define.amd ? define(factory) :
  118713. (global.PointerEventsPolyfill = factory());
  118714. }(this, function () { 'use strict';
  118715. /**
  118716. * This is the constructor for new PointerEvents.
  118717. *
  118718. * New Pointer Events must be given a type, and an optional dictionary of
  118719. * initialization properties.
  118720. *
  118721. * Due to certain platform requirements, events returned from the constructor
  118722. * identify as MouseEvents.
  118723. *
  118724. * @constructor
  118725. * @param {String} inType The type of the event to create.
  118726. * @param {Object} [inDict] An optional dictionary of initial event properties.
  118727. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  118728. */
  118729. var MOUSE_PROPS = [
  118730. 'bubbles',
  118731. 'cancelable',
  118732. 'view',
  118733. 'detail',
  118734. 'screenX',
  118735. 'screenY',
  118736. 'clientX',
  118737. 'clientY',
  118738. 'ctrlKey',
  118739. 'altKey',
  118740. 'shiftKey',
  118741. 'metaKey',
  118742. 'button',
  118743. 'relatedTarget',
  118744. 'pageX',
  118745. 'pageY'
  118746. ];
  118747. var MOUSE_DEFAULTS = [
  118748. false,
  118749. false,
  118750. null,
  118751. null,
  118752. 0,
  118753. 0,
  118754. 0,
  118755. 0,
  118756. false,
  118757. false,
  118758. false,
  118759. false,
  118760. 0,
  118761. null,
  118762. 0,
  118763. 0
  118764. ];
  118765. function PointerEvent(inType, inDict) {
  118766. inDict = inDict || Object.create(null);
  118767. var e = document.createEvent('Event');
  118768. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  118769. // define inherited MouseEvent properties
  118770. // skip bubbles and cancelable since they're set above in initEvent()
  118771. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  118772. p = MOUSE_PROPS[i];
  118773. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  118774. }
  118775. e.buttons = inDict.buttons || 0;
  118776. // Spec requires that pointers without pressure specified use 0.5 for down
  118777. // state and 0 for up state.
  118778. var pressure = 0;
  118779. if (inDict.pressure && e.buttons) {
  118780. pressure = inDict.pressure;
  118781. } else {
  118782. pressure = e.buttons ? 0.5 : 0;
  118783. }
  118784. // add x/y properties aliased to clientX/Y
  118785. e.x = e.clientX;
  118786. e.y = e.clientY;
  118787. // define the properties of the PointerEvent interface
  118788. e.pointerId = inDict.pointerId || 0;
  118789. e.width = inDict.width || 0;
  118790. e.height = inDict.height || 0;
  118791. e.pressure = pressure;
  118792. e.tiltX = inDict.tiltX || 0;
  118793. e.tiltY = inDict.tiltY || 0;
  118794. e.twist = inDict.twist || 0;
  118795. e.tangentialPressure = inDict.tangentialPressure || 0;
  118796. e.pointerType = inDict.pointerType || '';
  118797. e.hwTimestamp = inDict.hwTimestamp || 0;
  118798. e.isPrimary = inDict.isPrimary || false;
  118799. return e;
  118800. }
  118801. /**
  118802. * This module implements a map of pointer states
  118803. */
  118804. var USE_MAP = window.Map && window.Map.prototype.forEach;
  118805. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  118806. function SparseArrayMap() {
  118807. this.array = [];
  118808. this.size = 0;
  118809. }
  118810. SparseArrayMap.prototype = {
  118811. set: function(k, v) {
  118812. if (v === undefined) {
  118813. return this.delete(k);
  118814. }
  118815. if (!this.has(k)) {
  118816. this.size++;
  118817. }
  118818. this.array[k] = v;
  118819. },
  118820. has: function(k) {
  118821. return this.array[k] !== undefined;
  118822. },
  118823. delete: function(k) {
  118824. if (this.has(k)) {
  118825. delete this.array[k];
  118826. this.size--;
  118827. }
  118828. },
  118829. get: function(k) {
  118830. return this.array[k];
  118831. },
  118832. clear: function() {
  118833. this.array.length = 0;
  118834. this.size = 0;
  118835. },
  118836. // return value, key, map
  118837. forEach: function(callback, thisArg) {
  118838. return this.array.forEach(function(v, k) {
  118839. callback.call(thisArg, v, k, this);
  118840. }, this);
  118841. }
  118842. };
  118843. var CLONE_PROPS = [
  118844. // MouseEvent
  118845. 'bubbles',
  118846. 'cancelable',
  118847. 'view',
  118848. 'detail',
  118849. 'screenX',
  118850. 'screenY',
  118851. 'clientX',
  118852. 'clientY',
  118853. 'ctrlKey',
  118854. 'altKey',
  118855. 'shiftKey',
  118856. 'metaKey',
  118857. 'button',
  118858. 'relatedTarget',
  118859. // DOM Level 3
  118860. 'buttons',
  118861. // PointerEvent
  118862. 'pointerId',
  118863. 'width',
  118864. 'height',
  118865. 'pressure',
  118866. 'tiltX',
  118867. 'tiltY',
  118868. 'pointerType',
  118869. 'hwTimestamp',
  118870. 'isPrimary',
  118871. // event instance
  118872. 'type',
  118873. 'target',
  118874. 'currentTarget',
  118875. 'which',
  118876. 'pageX',
  118877. 'pageY',
  118878. 'timeStamp'
  118879. ];
  118880. var CLONE_DEFAULTS = [
  118881. // MouseEvent
  118882. false,
  118883. false,
  118884. null,
  118885. null,
  118886. 0,
  118887. 0,
  118888. 0,
  118889. 0,
  118890. false,
  118891. false,
  118892. false,
  118893. false,
  118894. 0,
  118895. null,
  118896. // DOM Level 3
  118897. 0,
  118898. // PointerEvent
  118899. 0,
  118900. 0,
  118901. 0,
  118902. 0,
  118903. 0,
  118904. 0,
  118905. '',
  118906. 0,
  118907. false,
  118908. // event instance
  118909. '',
  118910. null,
  118911. null,
  118912. 0,
  118913. 0,
  118914. 0,
  118915. 0
  118916. ];
  118917. var BOUNDARY_EVENTS = {
  118918. 'pointerover': 1,
  118919. 'pointerout': 1,
  118920. 'pointerenter': 1,
  118921. 'pointerleave': 1
  118922. };
  118923. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  118924. /**
  118925. * This module is for normalizing events. Mouse and Touch events will be
  118926. * collected here, and fire PointerEvents that have the same semantics, no
  118927. * matter the source.
  118928. * Events fired:
  118929. * - pointerdown: a pointing is added
  118930. * - pointerup: a pointer is removed
  118931. * - pointermove: a pointer is moved
  118932. * - pointerover: a pointer crosses into an element
  118933. * - pointerout: a pointer leaves an element
  118934. * - pointercancel: a pointer will no longer generate events
  118935. */
  118936. var dispatcher = {
  118937. pointermap: new PointerMap(),
  118938. eventMap: Object.create(null),
  118939. captureInfo: Object.create(null),
  118940. // Scope objects for native events.
  118941. // This exists for ease of testing.
  118942. eventSources: Object.create(null),
  118943. eventSourceList: [],
  118944. /**
  118945. * Add a new event source that will generate pointer events.
  118946. *
  118947. * `inSource` must contain an array of event names named `events`, and
  118948. * functions with the names specified in the `events` array.
  118949. * @param {string} name A name for the event source
  118950. * @param {Object} source A new source of platform events.
  118951. */
  118952. registerSource: function(name, source) {
  118953. var s = source;
  118954. var newEvents = s.events;
  118955. if (newEvents) {
  118956. newEvents.forEach(function(e) {
  118957. if (s[e]) {
  118958. this.eventMap[e] = s[e].bind(s);
  118959. }
  118960. }, this);
  118961. this.eventSources[name] = s;
  118962. this.eventSourceList.push(s);
  118963. }
  118964. },
  118965. register: function(element) {
  118966. var l = this.eventSourceList.length;
  118967. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  118968. // call eventsource register
  118969. es.register.call(es, element);
  118970. }
  118971. },
  118972. unregister: function(element) {
  118973. var l = this.eventSourceList.length;
  118974. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  118975. // call eventsource register
  118976. es.unregister.call(es, element);
  118977. }
  118978. },
  118979. contains: /*scope.external.contains || */function(container, contained) {
  118980. try {
  118981. return container.contains(contained);
  118982. } catch (ex) {
  118983. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  118984. return false;
  118985. }
  118986. },
  118987. // EVENTS
  118988. down: function(inEvent) {
  118989. inEvent.bubbles = true;
  118990. this.fireEvent('pointerdown', inEvent);
  118991. },
  118992. move: function(inEvent) {
  118993. inEvent.bubbles = true;
  118994. this.fireEvent('pointermove', inEvent);
  118995. },
  118996. up: function(inEvent) {
  118997. inEvent.bubbles = true;
  118998. this.fireEvent('pointerup', inEvent);
  118999. },
  119000. enter: function(inEvent) {
  119001. inEvent.bubbles = false;
  119002. this.fireEvent('pointerenter', inEvent);
  119003. },
  119004. leave: function(inEvent) {
  119005. inEvent.bubbles = false;
  119006. this.fireEvent('pointerleave', inEvent);
  119007. },
  119008. over: function(inEvent) {
  119009. inEvent.bubbles = true;
  119010. this.fireEvent('pointerover', inEvent);
  119011. },
  119012. out: function(inEvent) {
  119013. inEvent.bubbles = true;
  119014. this.fireEvent('pointerout', inEvent);
  119015. },
  119016. cancel: function(inEvent) {
  119017. inEvent.bubbles = true;
  119018. this.fireEvent('pointercancel', inEvent);
  119019. },
  119020. leaveOut: function(event) {
  119021. this.out(event);
  119022. this.propagate(event, this.leave, false);
  119023. },
  119024. enterOver: function(event) {
  119025. this.over(event);
  119026. this.propagate(event, this.enter, true);
  119027. },
  119028. // LISTENER LOGIC
  119029. eventHandler: function(inEvent) {
  119030. // This is used to prevent multiple dispatch of pointerevents from
  119031. // platform events. This can happen when two elements in different scopes
  119032. // are set up to create pointer events, which is relevant to Shadow DOM.
  119033. if (inEvent._handledByPE) {
  119034. return;
  119035. }
  119036. var type = inEvent.type;
  119037. var fn = this.eventMap && this.eventMap[type];
  119038. if (fn) {
  119039. fn(inEvent);
  119040. }
  119041. inEvent._handledByPE = true;
  119042. },
  119043. // set up event listeners
  119044. listen: function(target, events) {
  119045. events.forEach(function(e) {
  119046. this.addEvent(target, e);
  119047. }, this);
  119048. },
  119049. // remove event listeners
  119050. unlisten: function(target, events) {
  119051. events.forEach(function(e) {
  119052. this.removeEvent(target, e);
  119053. }, this);
  119054. },
  119055. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  119056. target.addEventListener(eventName, this.boundHandler);
  119057. },
  119058. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  119059. target.removeEventListener(eventName, this.boundHandler);
  119060. },
  119061. // EVENT CREATION AND TRACKING
  119062. /**
  119063. * Creates a new Event of type `inType`, based on the information in
  119064. * `inEvent`.
  119065. *
  119066. * @param {string} inType A string representing the type of event to create
  119067. * @param {Event} inEvent A platform event with a target
  119068. * @return {Event} A PointerEvent of type `inType`
  119069. */
  119070. makeEvent: function(inType, inEvent) {
  119071. // relatedTarget must be null if pointer is captured
  119072. if (this.captureInfo[inEvent.pointerId]) {
  119073. inEvent.relatedTarget = null;
  119074. }
  119075. var e = new PointerEvent(inType, inEvent);
  119076. if (inEvent.preventDefault) {
  119077. e.preventDefault = inEvent.preventDefault;
  119078. }
  119079. e._target = e._target || inEvent.target;
  119080. return e;
  119081. },
  119082. // make and dispatch an event in one call
  119083. fireEvent: function(inType, inEvent) {
  119084. var e = this.makeEvent(inType, inEvent);
  119085. return this.dispatchEvent(e);
  119086. },
  119087. /**
  119088. * Returns a snapshot of inEvent, with writable properties.
  119089. *
  119090. * @param {Event} inEvent An event that contains properties to copy.
  119091. * @return {Object} An object containing shallow copies of `inEvent`'s
  119092. * properties.
  119093. */
  119094. cloneEvent: function(inEvent) {
  119095. var eventCopy = Object.create(null);
  119096. var p;
  119097. for (var i = 0; i < CLONE_PROPS.length; i++) {
  119098. p = CLONE_PROPS[i];
  119099. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  119100. // Work around SVGInstanceElement shadow tree
  119101. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  119102. // This is the behavior implemented by Firefox.
  119103. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  119104. if (eventCopy[p] instanceof SVGElementInstance) {
  119105. eventCopy[p] = eventCopy[p].correspondingUseElement;
  119106. }
  119107. }
  119108. }
  119109. // keep the semantics of preventDefault
  119110. if (inEvent.preventDefault) {
  119111. eventCopy.preventDefault = function() {
  119112. inEvent.preventDefault();
  119113. };
  119114. }
  119115. return eventCopy;
  119116. },
  119117. getTarget: function(inEvent) {
  119118. var capture = this.captureInfo[inEvent.pointerId];
  119119. if (!capture) {
  119120. return inEvent._target;
  119121. }
  119122. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  119123. return capture;
  119124. }
  119125. },
  119126. propagate: function(event, fn, propagateDown) {
  119127. var target = event.target;
  119128. var targets = [];
  119129. // Order of conditions due to document.contains() missing in IE.
  119130. while (target !== document && !target.contains(event.relatedTarget)) {
  119131. targets.push(target);
  119132. target = target.parentNode;
  119133. // Touch: Do not propagate if node is detached.
  119134. if (!target) {
  119135. return;
  119136. }
  119137. }
  119138. if (propagateDown) {
  119139. targets.reverse();
  119140. }
  119141. targets.forEach(function(target) {
  119142. event.target = target;
  119143. fn.call(this, event);
  119144. }, this);
  119145. },
  119146. setCapture: function(inPointerId, inTarget, skipDispatch) {
  119147. if (this.captureInfo[inPointerId]) {
  119148. this.releaseCapture(inPointerId, skipDispatch);
  119149. }
  119150. this.captureInfo[inPointerId] = inTarget;
  119151. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  119152. document.addEventListener('pointerup', this.implicitRelease);
  119153. document.addEventListener('pointercancel', this.implicitRelease);
  119154. var e = new PointerEvent('gotpointercapture');
  119155. e.pointerId = inPointerId;
  119156. e._target = inTarget;
  119157. if (!skipDispatch) {
  119158. this.asyncDispatchEvent(e);
  119159. }
  119160. },
  119161. releaseCapture: function(inPointerId, skipDispatch) {
  119162. var t = this.captureInfo[inPointerId];
  119163. if (!t) {
  119164. return;
  119165. }
  119166. this.captureInfo[inPointerId] = undefined;
  119167. document.removeEventListener('pointerup', this.implicitRelease);
  119168. document.removeEventListener('pointercancel', this.implicitRelease);
  119169. var e = new PointerEvent('lostpointercapture');
  119170. e.pointerId = inPointerId;
  119171. e._target = t;
  119172. if (!skipDispatch) {
  119173. this.asyncDispatchEvent(e);
  119174. }
  119175. },
  119176. /**
  119177. * Dispatches the event to its target.
  119178. *
  119179. * @param {Event} inEvent The event to be dispatched.
  119180. * @return {Boolean} True if an event handler returns true, false otherwise.
  119181. */
  119182. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  119183. var t = this.getTarget(inEvent);
  119184. if (t) {
  119185. return t.dispatchEvent(inEvent);
  119186. }
  119187. },
  119188. asyncDispatchEvent: function(inEvent) {
  119189. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  119190. }
  119191. };
  119192. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  119193. var targeting = {
  119194. shadow: function(inEl) {
  119195. if (inEl) {
  119196. return inEl.shadowRoot || inEl.webkitShadowRoot;
  119197. }
  119198. },
  119199. canTarget: function(shadow) {
  119200. return shadow && Boolean(shadow.elementFromPoint);
  119201. },
  119202. targetingShadow: function(inEl) {
  119203. var s = this.shadow(inEl);
  119204. if (this.canTarget(s)) {
  119205. return s;
  119206. }
  119207. },
  119208. olderShadow: function(shadow) {
  119209. var os = shadow.olderShadowRoot;
  119210. if (!os) {
  119211. var se = shadow.querySelector('shadow');
  119212. if (se) {
  119213. os = se.olderShadowRoot;
  119214. }
  119215. }
  119216. return os;
  119217. },
  119218. allShadows: function(element) {
  119219. var shadows = [];
  119220. var s = this.shadow(element);
  119221. while (s) {
  119222. shadows.push(s);
  119223. s = this.olderShadow(s);
  119224. }
  119225. return shadows;
  119226. },
  119227. searchRoot: function(inRoot, x, y) {
  119228. if (inRoot) {
  119229. var t = inRoot.elementFromPoint(x, y);
  119230. var st, sr;
  119231. // is element a shadow host?
  119232. sr = this.targetingShadow(t);
  119233. while (sr) {
  119234. // find the the element inside the shadow root
  119235. st = sr.elementFromPoint(x, y);
  119236. if (!st) {
  119237. // check for older shadows
  119238. sr = this.olderShadow(sr);
  119239. } else {
  119240. // shadowed element may contain a shadow root
  119241. var ssr = this.targetingShadow(st);
  119242. return this.searchRoot(ssr, x, y) || st;
  119243. }
  119244. }
  119245. // light dom element is the target
  119246. return t;
  119247. }
  119248. },
  119249. owner: function(element) {
  119250. var s = element;
  119251. // walk up until you hit the shadow root or document
  119252. while (s.parentNode) {
  119253. s = s.parentNode;
  119254. }
  119255. // the owner element is expected to be a Document or ShadowRoot
  119256. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  119257. s = document;
  119258. }
  119259. return s;
  119260. },
  119261. findTarget: function(inEvent) {
  119262. var x = inEvent.clientX;
  119263. var y = inEvent.clientY;
  119264. // if the listener is in the shadow root, it is much faster to start there
  119265. var s = this.owner(inEvent.target);
  119266. // if x, y is not in this root, fall back to document search
  119267. if (!s.elementFromPoint(x, y)) {
  119268. s = document;
  119269. }
  119270. return this.searchRoot(s, x, y);
  119271. }
  119272. };
  119273. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  119274. var map = Array.prototype.map.call.bind(Array.prototype.map);
  119275. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  119276. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  119277. var MO = window.MutationObserver || window.WebKitMutationObserver;
  119278. var SELECTOR = '[touch-action]';
  119279. var OBSERVER_INIT = {
  119280. subtree: true,
  119281. childList: true,
  119282. attributes: true,
  119283. attributeOldValue: true,
  119284. attributeFilter: ['touch-action']
  119285. };
  119286. function Installer(add, remove, changed, binder) {
  119287. this.addCallback = add.bind(binder);
  119288. this.removeCallback = remove.bind(binder);
  119289. this.changedCallback = changed.bind(binder);
  119290. if (MO) {
  119291. this.observer = new MO(this.mutationWatcher.bind(this));
  119292. }
  119293. }
  119294. Installer.prototype = {
  119295. watchSubtree: function(target) {
  119296. // Only watch scopes that can target find, as these are top-level.
  119297. // Otherwise we can see duplicate additions and removals that add noise.
  119298. //
  119299. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  119300. // a removal without an insertion when a node is redistributed among
  119301. // shadows. Since it all ends up correct in the document, watching only
  119302. // the document will yield the correct mutations to watch.
  119303. if (this.observer && targeting.canTarget(target)) {
  119304. this.observer.observe(target, OBSERVER_INIT);
  119305. }
  119306. },
  119307. enableOnSubtree: function(target) {
  119308. this.watchSubtree(target);
  119309. if (target === document && document.readyState !== 'complete') {
  119310. this.installOnLoad();
  119311. } else {
  119312. this.installNewSubtree(target);
  119313. }
  119314. },
  119315. installNewSubtree: function(target) {
  119316. forEach(this.findElements(target), this.addElement, this);
  119317. },
  119318. findElements: function(target) {
  119319. if (target.querySelectorAll) {
  119320. return target.querySelectorAll(SELECTOR);
  119321. }
  119322. return [];
  119323. },
  119324. removeElement: function(el) {
  119325. this.removeCallback(el);
  119326. },
  119327. addElement: function(el) {
  119328. this.addCallback(el);
  119329. },
  119330. elementChanged: function(el, oldValue) {
  119331. this.changedCallback(el, oldValue);
  119332. },
  119333. concatLists: function(accum, list) {
  119334. return accum.concat(toArray(list));
  119335. },
  119336. // register all touch-action = none nodes on document load
  119337. installOnLoad: function() {
  119338. document.addEventListener('readystatechange', function() {
  119339. if (document.readyState === 'complete') {
  119340. this.installNewSubtree(document);
  119341. }
  119342. }.bind(this));
  119343. },
  119344. isElement: function(n) {
  119345. return n.nodeType === Node.ELEMENT_NODE;
  119346. },
  119347. flattenMutationTree: function(inNodes) {
  119348. // find children with touch-action
  119349. var tree = map(inNodes, this.findElements, this);
  119350. // make sure the added nodes are accounted for
  119351. tree.push(filter(inNodes, this.isElement));
  119352. // flatten the list
  119353. return tree.reduce(this.concatLists, []);
  119354. },
  119355. mutationWatcher: function(mutations) {
  119356. mutations.forEach(this.mutationHandler, this);
  119357. },
  119358. mutationHandler: function(m) {
  119359. if (m.type === 'childList') {
  119360. var added = this.flattenMutationTree(m.addedNodes);
  119361. added.forEach(this.addElement, this);
  119362. var removed = this.flattenMutationTree(m.removedNodes);
  119363. removed.forEach(this.removeElement, this);
  119364. } else if (m.type === 'attributes') {
  119365. this.elementChanged(m.target, m.oldValue);
  119366. }
  119367. }
  119368. };
  119369. function shadowSelector(v) {
  119370. return 'body /shadow-deep/ ' + selector(v);
  119371. }
  119372. function selector(v) {
  119373. return '[touch-action="' + v + '"]';
  119374. }
  119375. function rule(v) {
  119376. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  119377. }
  119378. var attrib2css = [
  119379. 'none',
  119380. 'auto',
  119381. 'pan-x',
  119382. 'pan-y',
  119383. {
  119384. rule: 'pan-x pan-y',
  119385. selectors: [
  119386. 'pan-x pan-y',
  119387. 'pan-y pan-x'
  119388. ]
  119389. }
  119390. ];
  119391. var styles = '';
  119392. // only install stylesheet if the browser has touch action support
  119393. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  119394. // only add shadow selectors if shadowdom is supported
  119395. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  119396. function applyAttributeStyles() {
  119397. if (hasNativePE) {
  119398. attrib2css.forEach(function(r) {
  119399. if (String(r) === r) {
  119400. styles += selector(r) + rule(r) + '\n';
  119401. if (hasShadowRoot) {
  119402. styles += shadowSelector(r) + rule(r) + '\n';
  119403. }
  119404. } else {
  119405. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  119406. if (hasShadowRoot) {
  119407. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  119408. }
  119409. }
  119410. });
  119411. var el = document.createElement('style');
  119412. el.textContent = styles;
  119413. document.head.appendChild(el);
  119414. }
  119415. }
  119416. var pointermap = dispatcher.pointermap;
  119417. // radius around touchend that swallows mouse events
  119418. var DEDUP_DIST = 25;
  119419. // left, middle, right, back, forward
  119420. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  119421. var HAS_BUTTONS = false;
  119422. try {
  119423. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  119424. } catch (e) {}
  119425. // handler block for native mouse events
  119426. var mouseEvents = {
  119427. POINTER_ID: 1,
  119428. POINTER_TYPE: 'mouse',
  119429. events: [
  119430. 'mousedown',
  119431. 'mousemove',
  119432. 'mouseup',
  119433. 'mouseover',
  119434. 'mouseout'
  119435. ],
  119436. register: function(target) {
  119437. dispatcher.listen(target, this.events);
  119438. },
  119439. unregister: function(target) {
  119440. dispatcher.unlisten(target, this.events);
  119441. },
  119442. lastTouches: [],
  119443. // collide with the global mouse listener
  119444. isEventSimulatedFromTouch: function(inEvent) {
  119445. var lts = this.lastTouches;
  119446. var x = inEvent.clientX;
  119447. var y = inEvent.clientY;
  119448. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  119449. // simulated mouse events will be swallowed near a primary touchend
  119450. var dx = Math.abs(x - t.x);
  119451. var dy = Math.abs(y - t.y);
  119452. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  119453. return true;
  119454. }
  119455. }
  119456. },
  119457. prepareEvent: function(inEvent) {
  119458. var e = dispatcher.cloneEvent(inEvent);
  119459. // forward mouse preventDefault
  119460. var pd = e.preventDefault;
  119461. e.preventDefault = function() {
  119462. inEvent.preventDefault();
  119463. pd();
  119464. };
  119465. e.pointerId = this.POINTER_ID;
  119466. e.isPrimary = true;
  119467. e.pointerType = this.POINTER_TYPE;
  119468. return e;
  119469. },
  119470. prepareButtonsForMove: function(e, inEvent) {
  119471. var p = pointermap.get(this.POINTER_ID);
  119472. // Update buttons state after possible out-of-document mouseup.
  119473. if (inEvent.which === 0 || !p) {
  119474. e.buttons = 0;
  119475. } else {
  119476. e.buttons = p.buttons;
  119477. }
  119478. inEvent.buttons = e.buttons;
  119479. },
  119480. mousedown: function(inEvent) {
  119481. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119482. var p = pointermap.get(this.POINTER_ID);
  119483. var e = this.prepareEvent(inEvent);
  119484. if (!HAS_BUTTONS) {
  119485. e.buttons = BUTTON_TO_BUTTONS[e.button];
  119486. if (p) { e.buttons |= p.buttons; }
  119487. inEvent.buttons = e.buttons;
  119488. }
  119489. pointermap.set(this.POINTER_ID, inEvent);
  119490. if (!p || p.buttons === 0) {
  119491. dispatcher.down(e);
  119492. } else {
  119493. dispatcher.move(e);
  119494. }
  119495. }
  119496. },
  119497. mousemove: function(inEvent) {
  119498. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119499. var e = this.prepareEvent(inEvent);
  119500. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119501. e.button = -1;
  119502. pointermap.set(this.POINTER_ID, inEvent);
  119503. dispatcher.move(e);
  119504. }
  119505. },
  119506. mouseup: function(inEvent) {
  119507. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119508. var p = pointermap.get(this.POINTER_ID);
  119509. var e = this.prepareEvent(inEvent);
  119510. if (!HAS_BUTTONS) {
  119511. var up = BUTTON_TO_BUTTONS[e.button];
  119512. // Produces wrong state of buttons in Browsers without `buttons` support
  119513. // when a mouse button that was pressed outside the document is released
  119514. // inside and other buttons are still pressed down.
  119515. e.buttons = p ? p.buttons & ~up : 0;
  119516. inEvent.buttons = e.buttons;
  119517. }
  119518. pointermap.set(this.POINTER_ID, inEvent);
  119519. // Support: Firefox <=44 only
  119520. // FF Ubuntu includes the lifted button in the `buttons` property on
  119521. // mouseup.
  119522. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  119523. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  119524. if (e.buttons === 0) {
  119525. dispatcher.up(e);
  119526. } else {
  119527. dispatcher.move(e);
  119528. }
  119529. }
  119530. },
  119531. mouseover: function(inEvent) {
  119532. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119533. var e = this.prepareEvent(inEvent);
  119534. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119535. e.button = -1;
  119536. pointermap.set(this.POINTER_ID, inEvent);
  119537. dispatcher.enterOver(e);
  119538. }
  119539. },
  119540. mouseout: function(inEvent) {
  119541. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119542. var e = this.prepareEvent(inEvent);
  119543. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119544. e.button = -1;
  119545. dispatcher.leaveOut(e);
  119546. }
  119547. },
  119548. cancel: function(inEvent) {
  119549. var e = this.prepareEvent(inEvent);
  119550. dispatcher.cancel(e);
  119551. this.deactivateMouse();
  119552. },
  119553. deactivateMouse: function() {
  119554. pointermap.delete(this.POINTER_ID);
  119555. }
  119556. };
  119557. var captureInfo = dispatcher.captureInfo;
  119558. var findTarget = targeting.findTarget.bind(targeting);
  119559. var allShadows = targeting.allShadows.bind(targeting);
  119560. var pointermap$1 = dispatcher.pointermap;
  119561. // This should be long enough to ignore compat mouse events made by touch
  119562. var DEDUP_TIMEOUT = 2500;
  119563. var CLICK_COUNT_TIMEOUT = 200;
  119564. var ATTRIB = 'touch-action';
  119565. var INSTALLER;
  119566. // handler block for native touch events
  119567. var touchEvents = {
  119568. events: [
  119569. 'touchstart',
  119570. 'touchmove',
  119571. 'touchend',
  119572. 'touchcancel'
  119573. ],
  119574. register: function(target) {
  119575. INSTALLER.enableOnSubtree(target);
  119576. },
  119577. unregister: function() {
  119578. // TODO(dfreedman): is it worth it to disconnect the MO?
  119579. },
  119580. elementAdded: function(el) {
  119581. var a = el.getAttribute(ATTRIB);
  119582. var st = this.touchActionToScrollType(a);
  119583. if (st) {
  119584. el._scrollType = st;
  119585. dispatcher.listen(el, this.events);
  119586. // set touch-action on shadows as well
  119587. allShadows(el).forEach(function(s) {
  119588. s._scrollType = st;
  119589. dispatcher.listen(s, this.events);
  119590. }, this);
  119591. }
  119592. },
  119593. elementRemoved: function(el) {
  119594. el._scrollType = undefined;
  119595. dispatcher.unlisten(el, this.events);
  119596. // remove touch-action from shadow
  119597. allShadows(el).forEach(function(s) {
  119598. s._scrollType = undefined;
  119599. dispatcher.unlisten(s, this.events);
  119600. }, this);
  119601. },
  119602. elementChanged: function(el, oldValue) {
  119603. var a = el.getAttribute(ATTRIB);
  119604. var st = this.touchActionToScrollType(a);
  119605. var oldSt = this.touchActionToScrollType(oldValue);
  119606. // simply update scrollType if listeners are already established
  119607. if (st && oldSt) {
  119608. el._scrollType = st;
  119609. allShadows(el).forEach(function(s) {
  119610. s._scrollType = st;
  119611. }, this);
  119612. } else if (oldSt) {
  119613. this.elementRemoved(el);
  119614. } else if (st) {
  119615. this.elementAdded(el);
  119616. }
  119617. },
  119618. scrollTypes: {
  119619. EMITTER: 'none',
  119620. XSCROLLER: 'pan-x',
  119621. YSCROLLER: 'pan-y',
  119622. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  119623. },
  119624. touchActionToScrollType: function(touchAction) {
  119625. var t = touchAction;
  119626. var st = this.scrollTypes;
  119627. if (t === 'none') {
  119628. return 'none';
  119629. } else if (t === st.XSCROLLER) {
  119630. return 'X';
  119631. } else if (t === st.YSCROLLER) {
  119632. return 'Y';
  119633. } else if (st.SCROLLER.exec(t)) {
  119634. return 'XY';
  119635. }
  119636. },
  119637. POINTER_TYPE: 'touch',
  119638. firstTouch: null,
  119639. isPrimaryTouch: function(inTouch) {
  119640. return this.firstTouch === inTouch.identifier;
  119641. },
  119642. setPrimaryTouch: function(inTouch) {
  119643. // set primary touch if there no pointers, or the only pointer is the mouse
  119644. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  119645. this.firstTouch = inTouch.identifier;
  119646. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  119647. this.scrolling = false;
  119648. this.cancelResetClickCount();
  119649. }
  119650. },
  119651. removePrimaryPointer: function(inPointer) {
  119652. if (inPointer.isPrimary) {
  119653. this.firstTouch = null;
  119654. this.firstXY = null;
  119655. this.resetClickCount();
  119656. }
  119657. },
  119658. clickCount: 0,
  119659. resetId: null,
  119660. resetClickCount: function() {
  119661. var fn = function() {
  119662. this.clickCount = 0;
  119663. this.resetId = null;
  119664. }.bind(this);
  119665. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  119666. },
  119667. cancelResetClickCount: function() {
  119668. if (this.resetId) {
  119669. clearTimeout(this.resetId);
  119670. }
  119671. },
  119672. typeToButtons: function(type) {
  119673. var ret = 0;
  119674. if (type === 'touchstart' || type === 'touchmove') {
  119675. ret = 1;
  119676. }
  119677. return ret;
  119678. },
  119679. touchToPointer: function(inTouch) {
  119680. var cte = this.currentTouchEvent;
  119681. var e = dispatcher.cloneEvent(inTouch);
  119682. // We reserve pointerId 1 for Mouse.
  119683. // Touch identifiers can start at 0.
  119684. // Add 2 to the touch identifier for compatibility.
  119685. var id = e.pointerId = inTouch.identifier + 2;
  119686. e.target = captureInfo[id] || findTarget(e);
  119687. e.bubbles = true;
  119688. e.cancelable = true;
  119689. e.detail = this.clickCount;
  119690. e.button = 0;
  119691. e.buttons = this.typeToButtons(cte.type);
  119692. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  119693. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  119694. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  119695. e.isPrimary = this.isPrimaryTouch(inTouch);
  119696. e.pointerType = this.POINTER_TYPE;
  119697. // forward modifier keys
  119698. e.altKey = cte.altKey;
  119699. e.ctrlKey = cte.ctrlKey;
  119700. e.metaKey = cte.metaKey;
  119701. e.shiftKey = cte.shiftKey;
  119702. // forward touch preventDefaults
  119703. var self = this;
  119704. e.preventDefault = function() {
  119705. self.scrolling = false;
  119706. self.firstXY = null;
  119707. cte.preventDefault();
  119708. };
  119709. return e;
  119710. },
  119711. processTouches: function(inEvent, inFunction) {
  119712. var tl = inEvent.changedTouches;
  119713. this.currentTouchEvent = inEvent;
  119714. for (var i = 0, t; i < tl.length; i++) {
  119715. t = tl[i];
  119716. inFunction.call(this, this.touchToPointer(t));
  119717. }
  119718. },
  119719. // For single axis scrollers, determines whether the element should emit
  119720. // pointer events or behave as a scroller
  119721. shouldScroll: function(inEvent) {
  119722. if (this.firstXY) {
  119723. var ret;
  119724. var scrollAxis = inEvent.currentTarget._scrollType;
  119725. if (scrollAxis === 'none') {
  119726. // this element is a touch-action: none, should never scroll
  119727. ret = false;
  119728. } else if (scrollAxis === 'XY') {
  119729. // this element should always scroll
  119730. ret = true;
  119731. } else {
  119732. var t = inEvent.changedTouches[0];
  119733. // check the intended scroll axis, and other axis
  119734. var a = scrollAxis;
  119735. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  119736. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  119737. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  119738. // if delta in the scroll axis > delta other axis, scroll instead of
  119739. // making events
  119740. ret = da >= doa;
  119741. }
  119742. this.firstXY = null;
  119743. return ret;
  119744. }
  119745. },
  119746. findTouch: function(inTL, inId) {
  119747. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  119748. if (t.identifier === inId) {
  119749. return true;
  119750. }
  119751. }
  119752. },
  119753. // In some instances, a touchstart can happen without a touchend. This
  119754. // leaves the pointermap in a broken state.
  119755. // Therefore, on every touchstart, we remove the touches that did not fire a
  119756. // touchend event.
  119757. // To keep state globally consistent, we fire a
  119758. // pointercancel for this "abandoned" touch
  119759. vacuumTouches: function(inEvent) {
  119760. var tl = inEvent.touches;
  119761. // pointermap.size should be < tl.length here, as the touchstart has not
  119762. // been processed yet.
  119763. if (pointermap$1.size >= tl.length) {
  119764. var d = [];
  119765. pointermap$1.forEach(function(value, key) {
  119766. // Never remove pointerId == 1, which is mouse.
  119767. // Touch identifiers are 2 smaller than their pointerId, which is the
  119768. // index in pointermap.
  119769. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  119770. var p = value.out;
  119771. d.push(p);
  119772. }
  119773. }, this);
  119774. d.forEach(this.cancelOut, this);
  119775. }
  119776. },
  119777. touchstart: function(inEvent) {
  119778. this.vacuumTouches(inEvent);
  119779. this.setPrimaryTouch(inEvent.changedTouches[0]);
  119780. this.dedupSynthMouse(inEvent);
  119781. if (!this.scrolling) {
  119782. this.clickCount++;
  119783. this.processTouches(inEvent, this.overDown);
  119784. }
  119785. },
  119786. overDown: function(inPointer) {
  119787. pointermap$1.set(inPointer.pointerId, {
  119788. target: inPointer.target,
  119789. out: inPointer,
  119790. outTarget: inPointer.target
  119791. });
  119792. dispatcher.enterOver(inPointer);
  119793. dispatcher.down(inPointer);
  119794. },
  119795. touchmove: function(inEvent) {
  119796. if (!this.scrolling) {
  119797. if (this.shouldScroll(inEvent)) {
  119798. this.scrolling = true;
  119799. this.touchcancel(inEvent);
  119800. } else {
  119801. inEvent.preventDefault();
  119802. this.processTouches(inEvent, this.moveOverOut);
  119803. }
  119804. }
  119805. },
  119806. moveOverOut: function(inPointer) {
  119807. var event = inPointer;
  119808. var pointer = pointermap$1.get(event.pointerId);
  119809. // a finger drifted off the screen, ignore it
  119810. if (!pointer) {
  119811. return;
  119812. }
  119813. var outEvent = pointer.out;
  119814. var outTarget = pointer.outTarget;
  119815. dispatcher.move(event);
  119816. if (outEvent && outTarget !== event.target) {
  119817. outEvent.relatedTarget = event.target;
  119818. event.relatedTarget = outTarget;
  119819. // recover from retargeting by shadow
  119820. outEvent.target = outTarget;
  119821. if (event.target) {
  119822. dispatcher.leaveOut(outEvent);
  119823. dispatcher.enterOver(event);
  119824. } else {
  119825. // clean up case when finger leaves the screen
  119826. event.target = outTarget;
  119827. event.relatedTarget = null;
  119828. this.cancelOut(event);
  119829. }
  119830. }
  119831. pointer.out = event;
  119832. pointer.outTarget = event.target;
  119833. },
  119834. touchend: function(inEvent) {
  119835. this.dedupSynthMouse(inEvent);
  119836. this.processTouches(inEvent, this.upOut);
  119837. },
  119838. upOut: function(inPointer) {
  119839. if (!this.scrolling) {
  119840. dispatcher.up(inPointer);
  119841. dispatcher.leaveOut(inPointer);
  119842. }
  119843. this.cleanUpPointer(inPointer);
  119844. },
  119845. touchcancel: function(inEvent) {
  119846. this.processTouches(inEvent, this.cancelOut);
  119847. },
  119848. cancelOut: function(inPointer) {
  119849. dispatcher.cancel(inPointer);
  119850. dispatcher.leaveOut(inPointer);
  119851. this.cleanUpPointer(inPointer);
  119852. },
  119853. cleanUpPointer: function(inPointer) {
  119854. pointermap$1.delete(inPointer.pointerId);
  119855. this.removePrimaryPointer(inPointer);
  119856. },
  119857. // prevent synth mouse events from creating pointer events
  119858. dedupSynthMouse: function(inEvent) {
  119859. var lts = mouseEvents.lastTouches;
  119860. var t = inEvent.changedTouches[0];
  119861. // only the primary finger will synth mouse events
  119862. if (this.isPrimaryTouch(t)) {
  119863. // remember x/y of last touch
  119864. var lt = { x: t.clientX, y: t.clientY };
  119865. lts.push(lt);
  119866. var fn = (function(lts, lt) {
  119867. var i = lts.indexOf(lt);
  119868. if (i > -1) {
  119869. lts.splice(i, 1);
  119870. }
  119871. }).bind(null, lts, lt);
  119872. setTimeout(fn, DEDUP_TIMEOUT);
  119873. }
  119874. }
  119875. };
  119876. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  119877. touchEvents.elementChanged, touchEvents);
  119878. var pointermap$2 = dispatcher.pointermap;
  119879. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  119880. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  119881. var msEvents = {
  119882. events: [
  119883. 'MSPointerDown',
  119884. 'MSPointerMove',
  119885. 'MSPointerUp',
  119886. 'MSPointerOut',
  119887. 'MSPointerOver',
  119888. 'MSPointerCancel',
  119889. 'MSGotPointerCapture',
  119890. 'MSLostPointerCapture'
  119891. ],
  119892. register: function(target) {
  119893. dispatcher.listen(target, this.events);
  119894. },
  119895. unregister: function(target) {
  119896. dispatcher.unlisten(target, this.events);
  119897. },
  119898. POINTER_TYPES: [
  119899. '',
  119900. 'unavailable',
  119901. 'touch',
  119902. 'pen',
  119903. 'mouse'
  119904. ],
  119905. prepareEvent: function(inEvent) {
  119906. var e = inEvent;
  119907. if (HAS_BITMAP_TYPE) {
  119908. e = dispatcher.cloneEvent(inEvent);
  119909. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  119910. }
  119911. return e;
  119912. },
  119913. cleanup: function(id) {
  119914. pointermap$2.delete(id);
  119915. },
  119916. MSPointerDown: function(inEvent) {
  119917. pointermap$2.set(inEvent.pointerId, inEvent);
  119918. var e = this.prepareEvent(inEvent);
  119919. dispatcher.down(e);
  119920. },
  119921. MSPointerMove: function(inEvent) {
  119922. var e = this.prepareEvent(inEvent);
  119923. dispatcher.move(e);
  119924. },
  119925. MSPointerUp: function(inEvent) {
  119926. var e = this.prepareEvent(inEvent);
  119927. dispatcher.up(e);
  119928. this.cleanup(inEvent.pointerId);
  119929. },
  119930. MSPointerOut: function(inEvent) {
  119931. var e = this.prepareEvent(inEvent);
  119932. dispatcher.leaveOut(e);
  119933. },
  119934. MSPointerOver: function(inEvent) {
  119935. var e = this.prepareEvent(inEvent);
  119936. dispatcher.enterOver(e);
  119937. },
  119938. MSPointerCancel: function(inEvent) {
  119939. var e = this.prepareEvent(inEvent);
  119940. dispatcher.cancel(e);
  119941. this.cleanup(inEvent.pointerId);
  119942. },
  119943. MSLostPointerCapture: function(inEvent) {
  119944. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  119945. dispatcher.dispatchEvent(e);
  119946. },
  119947. MSGotPointerCapture: function(inEvent) {
  119948. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  119949. dispatcher.dispatchEvent(e);
  119950. }
  119951. };
  119952. function applyPolyfill() {
  119953. // only activate if this platform does not have pointer events
  119954. if (!window.PointerEvent) {
  119955. window.PointerEvent = PointerEvent;
  119956. if (window.navigator.msPointerEnabled) {
  119957. var tp = window.navigator.msMaxTouchPoints;
  119958. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  119959. value: tp,
  119960. enumerable: true
  119961. });
  119962. dispatcher.registerSource('ms', msEvents);
  119963. } else {
  119964. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  119965. value: 0,
  119966. enumerable: true
  119967. });
  119968. dispatcher.registerSource('mouse', mouseEvents);
  119969. if (window.ontouchstart !== undefined) {
  119970. dispatcher.registerSource('touch', touchEvents);
  119971. }
  119972. }
  119973. dispatcher.register(document);
  119974. }
  119975. }
  119976. var n = window.navigator;
  119977. var s;
  119978. var r;
  119979. var h;
  119980. function assertActive(id) {
  119981. if (!dispatcher.pointermap.has(id)) {
  119982. var error = new Error('InvalidPointerId');
  119983. error.name = 'InvalidPointerId';
  119984. throw error;
  119985. }
  119986. }
  119987. function assertConnected(elem) {
  119988. var parent = elem.parentNode;
  119989. while (parent && parent !== elem.ownerDocument) {
  119990. parent = parent.parentNode;
  119991. }
  119992. if (!parent) {
  119993. var error = new Error('InvalidStateError');
  119994. error.name = 'InvalidStateError';
  119995. throw error;
  119996. }
  119997. }
  119998. function inActiveButtonState(id) {
  119999. var p = dispatcher.pointermap.get(id);
  120000. return p.buttons !== 0;
  120001. }
  120002. if (n.msPointerEnabled) {
  120003. s = function(pointerId) {
  120004. assertActive(pointerId);
  120005. assertConnected(this);
  120006. if (inActiveButtonState(pointerId)) {
  120007. dispatcher.setCapture(pointerId, this, true);
  120008. this.msSetPointerCapture(pointerId);
  120009. }
  120010. };
  120011. r = function(pointerId) {
  120012. assertActive(pointerId);
  120013. dispatcher.releaseCapture(pointerId, true);
  120014. this.msReleasePointerCapture(pointerId);
  120015. };
  120016. } else {
  120017. s = function setPointerCapture(pointerId) {
  120018. assertActive(pointerId);
  120019. assertConnected(this);
  120020. if (inActiveButtonState(pointerId)) {
  120021. dispatcher.setCapture(pointerId, this);
  120022. }
  120023. };
  120024. r = function releasePointerCapture(pointerId) {
  120025. assertActive(pointerId);
  120026. dispatcher.releaseCapture(pointerId);
  120027. };
  120028. }
  120029. h = function hasPointerCapture(pointerId) {
  120030. return !!dispatcher.captureInfo[pointerId];
  120031. };
  120032. function applyPolyfill$1() {
  120033. if (window.Element && !Element.prototype.setPointerCapture) {
  120034. Object.defineProperties(Element.prototype, {
  120035. 'setPointerCapture': {
  120036. value: s
  120037. },
  120038. 'releasePointerCapture': {
  120039. value: r
  120040. },
  120041. 'hasPointerCapture': {
  120042. value: h
  120043. }
  120044. });
  120045. }
  120046. }
  120047. applyAttributeStyles();
  120048. applyPolyfill();
  120049. applyPolyfill$1();
  120050. var pointerevents = {
  120051. dispatcher: dispatcher,
  120052. Installer: Installer,
  120053. PointerEvent: PointerEvent,
  120054. PointerMap: PointerMap,
  120055. targetFinding: targeting
  120056. };
  120057. return pointerevents;
  120058. }));
  120059. /***/ }),
  120060. /* 65 */
  120061. /***/ (function(module, exports, __webpack_require__) {
  120062. "use strict";
  120063. Object.defineProperty(exports, "__esModule", { value: true });
  120064. var defaultViewer_1 = __webpack_require__(8);
  120065. var mappers_1 = __webpack_require__(3);
  120066. var globals_1 = __webpack_require__(4);
  120067. /**
  120068. * Will attach an init function the the DOMContentLoaded event.
  120069. * The init function will be removed automatically after the event was triggered.
  120070. */
  120071. function initListeners() {
  120072. document.addEventListener("DOMContentLoaded", init);
  120073. function init(event) {
  120074. document.removeEventListener("DOMContentLoaded", init);
  120075. if (globals_1.viewerGlobals.disableInit)
  120076. return;
  120077. InitTags();
  120078. }
  120079. }
  120080. exports.initListeners = initListeners;
  120081. /**
  120082. * Select all HTML tags on the page that match the selector and initialize a viewer
  120083. *
  120084. * @param selector the selector to initialize the viewer on (default is 'babylon')
  120085. */
  120086. function InitTags(selector) {
  120087. if (selector === void 0) { selector = 'babylon'; }
  120088. var elements = document.querySelectorAll(selector);
  120089. for (var i = 0; i < elements.length; ++i) {
  120090. var element = elements.item(i);
  120091. // get the html configuration
  120092. var configMapper = mappers_1.mapperManager.getMapper('dom');
  120093. var config = configMapper.map(element);
  120094. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  120095. }
  120096. }
  120097. exports.InitTags = InitTags;
  120098. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQWtCLEVBQUUsSUFBSSxDQUFDLENBQUM7UUFDdkQsSUFBSSx1QkFBYSxDQUFDL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